SecurityUtils.cs 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Security
  5. {
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.ComponentModel;
  9. using System.Diagnostics;
  10. using System.DirectoryServices.ActiveDirectory;
  11. using System.Globalization;
  12. using System.IdentityModel.Claims;
  13. using System.IdentityModel.Policy;
  14. using System.IdentityModel.Selectors;
  15. using System.IdentityModel.Tokens;
  16. using System.Net;
  17. using System.Net.Security;
  18. using System.Runtime;
  19. using System.Security;
  20. using System.Security.Authentication.ExtendedProtection;
  21. using System.Security.Cryptography;
  22. using System.Security.Cryptography.X509Certificates;
  23. using System.Security.Permissions;
  24. using System.Security.Principal;
  25. using System.ServiceModel;
  26. using System.ServiceModel.Channels;
  27. using System.ServiceModel.Description;
  28. using System.ServiceModel.Diagnostics;
  29. using System.ServiceModel.Dispatcher;
  30. using System.ServiceModel.Security.Tokens;
  31. using System.Text;
  32. using System.Threading;
  33. using System.Xml;
  34. using Microsoft.Win32;
  35. using AuthIdentityEx = System.IdentityModel.AuthIdentityEx;
  36. using CredentialUse = System.IdentityModel.CredentialUse;
  37. using DictionaryManager = System.IdentityModel.DictionaryManager;
  38. using SafeFreeCredentials = System.IdentityModel.SafeFreeCredentials;
  39. using SspiWrapper = System.IdentityModel.SspiWrapper;
  40. static class StoreLocationHelper
  41. {
  42. internal static bool IsDefined(StoreLocation value)
  43. {
  44. return (value == StoreLocation.CurrentUser
  45. || value == StoreLocation.LocalMachine);
  46. }
  47. }
  48. static class ProtectionLevelHelper
  49. {
  50. internal static bool IsDefined(ProtectionLevel value)
  51. {
  52. return (value == ProtectionLevel.None
  53. || value == ProtectionLevel.Sign
  54. || value == ProtectionLevel.EncryptAndSign);
  55. }
  56. internal static void Validate(ProtectionLevel value)
  57. {
  58. if (!IsDefined(value))
  59. {
  60. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
  61. typeof(ProtectionLevel)));
  62. }
  63. }
  64. internal static bool IsStronger(ProtectionLevel v1, ProtectionLevel v2)
  65. {
  66. return ((v1 == ProtectionLevel.EncryptAndSign && v2 != ProtectionLevel.EncryptAndSign)
  67. || (v1 == ProtectionLevel.Sign && v2 == ProtectionLevel.None));
  68. }
  69. internal static bool IsStrongerOrEqual(ProtectionLevel v1, ProtectionLevel v2)
  70. {
  71. return (v1 == ProtectionLevel.EncryptAndSign
  72. || (v1 == ProtectionLevel.Sign && v2 != ProtectionLevel.EncryptAndSign));
  73. }
  74. internal static ProtectionLevel Max(ProtectionLevel v1, ProtectionLevel v2)
  75. {
  76. return IsStronger(v1, v2) ? v1 : v2;
  77. }
  78. internal static int GetOrdinal(Nullable<ProtectionLevel> p)
  79. {
  80. if (p.HasValue)
  81. {
  82. switch ((ProtectionLevel)p)
  83. {
  84. default:
  85. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("p", (int)p,
  86. typeof(ProtectionLevel)));
  87. case ProtectionLevel.None:
  88. return 2;
  89. case ProtectionLevel.Sign:
  90. return 3;
  91. case ProtectionLevel.EncryptAndSign:
  92. return 4;
  93. }
  94. }
  95. else
  96. return 1;
  97. }
  98. }
  99. static class TokenImpersonationLevelHelper
  100. {
  101. internal static bool IsDefined(TokenImpersonationLevel value)
  102. {
  103. return (value == TokenImpersonationLevel.None
  104. || value == TokenImpersonationLevel.Anonymous
  105. || value == TokenImpersonationLevel.Identification
  106. || value == TokenImpersonationLevel.Impersonation
  107. || value == TokenImpersonationLevel.Delegation);
  108. }
  109. internal static void Validate(TokenImpersonationLevel value)
  110. {
  111. if (!IsDefined(value))
  112. {
  113. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
  114. typeof(TokenImpersonationLevel)));
  115. }
  116. }
  117. static TokenImpersonationLevel[] TokenImpersonationLevelOrder = new TokenImpersonationLevel[]
  118. {
  119. TokenImpersonationLevel.None,
  120. TokenImpersonationLevel.Anonymous,
  121. TokenImpersonationLevel.Identification,
  122. TokenImpersonationLevel.Impersonation,
  123. TokenImpersonationLevel.Delegation
  124. };
  125. internal static string ToString(TokenImpersonationLevel impersonationLevel)
  126. {
  127. if (impersonationLevel == TokenImpersonationLevel.Identification)
  128. {
  129. return "identification";
  130. }
  131. else if (impersonationLevel == TokenImpersonationLevel.None)
  132. {
  133. return "none";
  134. }
  135. else if (impersonationLevel == TokenImpersonationLevel.Anonymous)
  136. {
  137. return "anonymous";
  138. }
  139. else if (impersonationLevel == TokenImpersonationLevel.Impersonation)
  140. {
  141. return "impersonation";
  142. }
  143. else if (impersonationLevel == TokenImpersonationLevel.Delegation)
  144. {
  145. return "delegation";
  146. }
  147. Fx.Assert("unknown token impersonation level");
  148. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("impersonationLevel", (int)impersonationLevel,
  149. typeof(TokenImpersonationLevel)));
  150. }
  151. internal static bool IsGreaterOrEqual(TokenImpersonationLevel x, TokenImpersonationLevel y)
  152. {
  153. TokenImpersonationLevelHelper.Validate(x);
  154. TokenImpersonationLevelHelper.Validate(y);
  155. if (x == y)
  156. return true;
  157. int px = 0;
  158. int py = 0;
  159. for (int i = 0; i < TokenImpersonationLevelOrder.Length; i++)
  160. {
  161. if (x == TokenImpersonationLevelOrder[i])
  162. px = i;
  163. if (y == TokenImpersonationLevelOrder[i])
  164. py = i;
  165. }
  166. return (px > py);
  167. }
  168. internal static int Compare(TokenImpersonationLevel x, TokenImpersonationLevel y)
  169. {
  170. int result = 0;
  171. if (x != y)
  172. {
  173. switch (x)
  174. {
  175. case TokenImpersonationLevel.Identification:
  176. result = -1;
  177. break;
  178. case TokenImpersonationLevel.Impersonation:
  179. switch (y)
  180. {
  181. case TokenImpersonationLevel.Identification:
  182. result = 1;
  183. break;
  184. case TokenImpersonationLevel.Delegation:
  185. result = -1;
  186. break;
  187. default:
  188. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("y", (int)y,
  189. typeof(TokenImpersonationLevel)));
  190. }
  191. break;
  192. case TokenImpersonationLevel.Delegation:
  193. result = 1;
  194. break;
  195. default:
  196. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("x", (int)x,
  197. typeof(TokenImpersonationLevel)));
  198. }
  199. }
  200. return result;
  201. }
  202. }
  203. internal class ServiceModelDictionaryManager
  204. {
  205. static DictionaryManager dictionaryManager;
  206. public static DictionaryManager Instance
  207. {
  208. get
  209. {
  210. if (dictionaryManager == null)
  211. dictionaryManager = new DictionaryManager(BinaryMessageEncoderFactory.XmlDictionary);
  212. return dictionaryManager;
  213. }
  214. }
  215. }
  216. static class SecurityUtils
  217. {
  218. public const string Principal = "Principal";
  219. public const string Identities = "Identities";
  220. static bool computedDomain;
  221. static string currentDomain;
  222. static byte[] combinedHashLabel;
  223. static IIdentity anonymousIdentity;
  224. static NetworkCredential dummyNetworkCredential;
  225. static object dummyNetworkCredentialLock = new object();
  226. static X509SecurityTokenAuthenticator nonValidatingX509Authenticator;
  227. static SecurityIdentifier administratorsSid;
  228. const int WindowsServerMajorNumber = 5;
  229. const int WindowsServerMinorNumber = 2;
  230. const int XPMajorNumber = 5;
  231. const int XPMinorNumber = 1;
  232. const string ServicePack1 = "Service Pack 1";
  233. const string ServicePack2 = "Service Pack 2";
  234. volatile static bool shouldValidateSslCipherStrength;
  235. volatile static bool isSslValidationRequirementDetermined = false;
  236. static readonly int MinimumSslCipherStrength = 128;
  237. // these are kept in [....] with IIS70
  238. public const string AuthTypeNTLM = "NTLM";
  239. public const string AuthTypeNegotiate = "Negotiate";
  240. public const string AuthTypeKerberos = "Kerberos";
  241. public const string AuthTypeAnonymous = "";
  242. public const string AuthTypeCertMap = "SSL/PCT"; // mapped from a cert
  243. public const string AuthTypeBasic = "Basic"; //LogonUser
  244. public static ChannelBinding GetChannelBindingFromMessage(Message message)
  245. {
  246. if (message == null)
  247. {
  248. return null;
  249. }
  250. ChannelBindingMessageProperty channelBindingMessageProperty = null;
  251. ChannelBindingMessageProperty.TryGet(message, out channelBindingMessageProperty);
  252. ChannelBinding channelBinding = null;
  253. if (channelBindingMessageProperty != null)
  254. {
  255. channelBinding = channelBindingMessageProperty.ChannelBinding;
  256. }
  257. return channelBinding;
  258. }
  259. internal static bool IsOsGreaterThanXP()
  260. {
  261. return ((Environment.OSVersion.Version.Major >= SecurityUtils.XPMajorNumber && Environment.OSVersion.Version.Minor > SecurityUtils.XPMinorNumber) ||
  262. Environment.OSVersion.Version.Major > SecurityUtils.XPMajorNumber);
  263. }
  264. internal static bool IsOSGreaterThanOrEqualToWin7()
  265. {
  266. Version windows7Version = new Version(6, 1, 0, 0);
  267. return (Environment.OSVersion.Version.Major >= windows7Version.Major && Environment.OSVersion.Version.Minor >= windows7Version.Minor);
  268. }
  269. internal static bool IsCurrentlyTimeEffective(DateTime effectiveTime, DateTime expirationTime, TimeSpan maxClockSkew)
  270. {
  271. DateTime curEffectiveTime = (effectiveTime < DateTime.MinValue.Add(maxClockSkew)) ? effectiveTime : effectiveTime.Subtract(maxClockSkew);
  272. DateTime curExpirationTime = (expirationTime > DateTime.MaxValue.Subtract(maxClockSkew)) ? expirationTime : expirationTime.Add(maxClockSkew);
  273. DateTime curTime = DateTime.UtcNow;
  274. return (curEffectiveTime.ToUniversalTime() <= curTime) && (curTime < curExpirationTime.ToUniversalTime());
  275. }
  276. internal static X509SecurityTokenAuthenticator NonValidatingX509Authenticator
  277. {
  278. get
  279. {
  280. if (nonValidatingX509Authenticator == null)
  281. {
  282. nonValidatingX509Authenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None);
  283. }
  284. return nonValidatingX509Authenticator;
  285. }
  286. }
  287. public static SecurityIdentifier AdministratorsSid
  288. {
  289. get
  290. {
  291. if (administratorsSid == null)
  292. administratorsSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
  293. return administratorsSid;
  294. }
  295. }
  296. internal static IIdentity AnonymousIdentity
  297. {
  298. get
  299. {
  300. if (anonymousIdentity == null)
  301. {
  302. anonymousIdentity = SecurityUtils.CreateIdentity(String.Empty);
  303. }
  304. return anonymousIdentity;
  305. }
  306. }
  307. public static DateTime MaxUtcDateTime
  308. {
  309. get
  310. {
  311. // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow.
  312. return new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc);
  313. }
  314. }
  315. public static DateTime MinUtcDateTime
  316. {
  317. get
  318. {
  319. // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow.
  320. return new DateTime(DateTime.MinValue.Ticks + TimeSpan.TicksPerDay, DateTimeKind.Utc);
  321. }
  322. }
  323. internal static IIdentity CreateIdentity(string name, string authenticationType)
  324. {
  325. return new GenericIdentity(name, authenticationType);
  326. }
  327. internal static IIdentity CreateIdentity(string name)
  328. {
  329. return new GenericIdentity(name);
  330. }
  331. internal static EndpointIdentity CreateWindowsIdentity()
  332. {
  333. return CreateWindowsIdentity(false);
  334. }
  335. internal static EndpointIdentity CreateWindowsIdentity(NetworkCredential serverCredential)
  336. {
  337. if (serverCredential != null && !NetworkCredentialHelper.IsDefault(serverCredential))
  338. {
  339. string upn;
  340. if (serverCredential.Domain != null && serverCredential.Domain.Length > 0)
  341. {
  342. upn = serverCredential.UserName + "@" + serverCredential.Domain;
  343. }
  344. else
  345. {
  346. upn = serverCredential.UserName;
  347. }
  348. return EndpointIdentity.CreateUpnIdentity(upn);
  349. }
  350. else
  351. {
  352. return SecurityUtils.CreateWindowsIdentity();
  353. }
  354. }
  355. static bool IsSystemAccount(WindowsIdentity self)
  356. {
  357. SecurityIdentifier sid = self.User;
  358. if (sid == null)
  359. {
  360. return false;
  361. }
  362. // S-1-5-82 is the prefix for the sid that represents the identity that IIS 7.5 Apppool thread runs under.
  363. return (sid.IsWellKnown(WellKnownSidType.LocalSystemSid)
  364. || sid.IsWellKnown(WellKnownSidType.NetworkServiceSid)
  365. || sid.IsWellKnown(WellKnownSidType.LocalServiceSid)
  366. || self.User.Value.StartsWith("S-1-5-82", StringComparison.OrdinalIgnoreCase));
  367. }
  368. internal static EndpointIdentity CreateWindowsIdentity(bool spnOnly)
  369. {
  370. EndpointIdentity identity = null;
  371. using (WindowsIdentity self = WindowsIdentity.GetCurrent())
  372. {
  373. bool isSystemAccount = IsSystemAccount(self);
  374. if (spnOnly || isSystemAccount)
  375. {
  376. identity = EndpointIdentity.CreateSpnIdentity(String.Format(CultureInfo.InvariantCulture, "host/{0}", DnsCache.MachineName));
  377. }
  378. else
  379. {
  380. // Save windowsIdentity for delay lookup
  381. identity = new UpnEndpointIdentity(CloneWindowsIdentityIfNecessary(self));
  382. }
  383. }
  384. return identity;
  385. }
  386. [Fx.Tag.SecurityNote(Critical = "Calls two critical methods: UnsafeGetWindowsIdentityToken and UnsafeCreateWindowsIdentityFromToken.",
  387. Safe = "'Clone' operation is considered safe despite using WindowsIdentity IntPtr token. Must not let IntPtr token leak in or out.")]
  388. [SecuritySafeCritical]
  389. internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid)
  390. {
  391. return SecurityUtils.CloneWindowsIdentityIfNecessary(wid, null);
  392. }
  393. [Fx.Tag.SecurityNote(Critical = "Calls two critical methods: UnsafeGetWindowsIdentityToken and UnsafeCreateWindowsIdentityFromToken.",
  394. Safe = "'Clone' operation is considered safe despite using WindowsIdentity IntPtr token. Must not let IntPtr token leak in or out.")]
  395. [SecuritySafeCritical]
  396. internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid, string authType)
  397. {
  398. if (wid != null)
  399. {
  400. IntPtr token = UnsafeGetWindowsIdentityToken(wid);
  401. if (token != IntPtr.Zero)
  402. {
  403. return UnsafeCreateWindowsIdentityFromToken(token, authType);
  404. }
  405. }
  406. return wid;
  407. }
  408. [Fx.Tag.SecurityNote(Critical = "Elevates in order to return the WindowsIdentity.Token property, caller must protect return value.")]
  409. [SecurityCritical]
  410. [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
  411. static IntPtr UnsafeGetWindowsIdentityToken(WindowsIdentity wid)
  412. {
  413. return wid.Token;
  414. }
  415. [Fx.Tag.SecurityNote(Critical = "Elevates in order to return the SecurityIdentifier of the current user as a string, caller must protect return value.")]
  416. [SecurityCritical]
  417. [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlPrincipal)]
  418. static string UnsafeGetCurrentUserSidAsString()
  419. {
  420. using (WindowsIdentity self = WindowsIdentity.GetCurrent())
  421. {
  422. return self.User.Value;
  423. }
  424. }
  425. [Fx.Tag.SecurityNote(Critical = "Elevates in order to return the WindowsIdentity.Token property, caller must protect return value.")]
  426. [SecurityCritical]
  427. [SecurityPermission(SecurityAction.Assert, ControlPrincipal = true, UnmanagedCode = true)]
  428. static WindowsIdentity UnsafeCreateWindowsIdentityFromToken(IntPtr token, string authType)
  429. {
  430. if (authType != null)
  431. return new WindowsIdentity(token, authType);
  432. else
  433. return new WindowsIdentity(token);
  434. }
  435. internal static bool AllowsImpersonation(WindowsIdentity windowsIdentity, TokenImpersonationLevel impersonationLevel)
  436. {
  437. if (windowsIdentity == null)
  438. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
  439. TokenImpersonationLevelHelper.Validate(impersonationLevel);
  440. if (impersonationLevel == TokenImpersonationLevel.Identification)
  441. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("impersonationLevel"));
  442. bool result = true;
  443. switch (windowsIdentity.ImpersonationLevel)
  444. {
  445. case TokenImpersonationLevel.None:
  446. case TokenImpersonationLevel.Anonymous:
  447. case TokenImpersonationLevel.Identification:
  448. result = false; break;
  449. case TokenImpersonationLevel.Impersonation:
  450. if (impersonationLevel == TokenImpersonationLevel.Delegation)
  451. result = false;
  452. break;
  453. case TokenImpersonationLevel.Delegation:
  454. break;
  455. default:
  456. result = false;
  457. break;
  458. }
  459. return result;
  460. }
  461. internal static byte[] CombinedHashLabel
  462. {
  463. get
  464. {
  465. if (combinedHashLabel == null)
  466. combinedHashLabel = Encoding.UTF8.GetBytes(TrustApr2004Strings.CombinedHashLabel);
  467. return combinedHashLabel;
  468. }
  469. }
  470. internal static T GetSecurityKey<T>(SecurityToken token)
  471. where T : SecurityKey
  472. {
  473. T result = null;
  474. if (token.SecurityKeys != null)
  475. {
  476. for (int i = 0; i < token.SecurityKeys.Count; ++i)
  477. {
  478. T temp = (token.SecurityKeys[i] as T);
  479. if (temp != null)
  480. {
  481. if (result != null)
  482. {
  483. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.MultipleMatchingCryptosFound, typeof(T).ToString())));
  484. }
  485. else
  486. {
  487. result = temp;
  488. }
  489. }
  490. }
  491. }
  492. return result;
  493. }
  494. internal static bool HasSymmetricSecurityKey(SecurityToken token)
  495. {
  496. return GetSecurityKey<SymmetricSecurityKey>(token) != null;
  497. }
  498. internal static void EnsureExpectedSymmetricMatch(SecurityToken t1, SecurityToken t2, Message message)
  499. {
  500. // nulls are not mismatches
  501. if (t1 == null || t2 == null || ReferenceEquals(t1, t2))
  502. {
  503. return;
  504. }
  505. // check for interop flexibility
  506. SymmetricSecurityKey c1 = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(t1);
  507. SymmetricSecurityKey c2 = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(t2);
  508. if (c1 == null || c2 == null || !CryptoHelper.IsEqual(c1.GetSymmetricKey(), c2.GetSymmetricKey()))
  509. {
  510. throw System.ServiceModel.Diagnostics.TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenNotExpectedInSecurityHeader, t2)), message);
  511. }
  512. }
  513. internal static SymmetricAlgorithm GetSymmetricAlgorithm(string algorithm, SecurityToken token)
  514. {
  515. SymmetricSecurityKey securityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(token);
  516. if (securityKey != null && securityKey.IsSupportedAlgorithm(algorithm))
  517. {
  518. return securityKey.GetSymmetricAlgorithm(algorithm);
  519. }
  520. else
  521. {
  522. return null;
  523. }
  524. }
  525. internal static KeyedHashAlgorithm GetKeyedHashAlgorithm(string algorithm, SecurityToken token)
  526. {
  527. SymmetricSecurityKey securityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(token);
  528. if (securityKey != null && securityKey.IsSupportedAlgorithm(algorithm))
  529. {
  530. return securityKey.GetKeyedHashAlgorithm(algorithm);
  531. }
  532. else
  533. {
  534. return null;
  535. }
  536. }
  537. internal static ReadOnlyCollection<SecurityKey> CreateSymmetricSecurityKeys(byte[] key)
  538. {
  539. List<SecurityKey> temp = new List<SecurityKey>(1);
  540. temp.Add(new InMemorySymmetricSecurityKey(key));
  541. return temp.AsReadOnly();
  542. }
  543. internal static byte[] DecryptKey(SecurityToken unwrappingToken, string encryptionMethod, byte[] wrappedKey, out SecurityKey unwrappingSecurityKey)
  544. {
  545. unwrappingSecurityKey = null;
  546. if (unwrappingToken.SecurityKeys != null)
  547. {
  548. for (int i = 0; i < unwrappingToken.SecurityKeys.Count; ++i)
  549. {
  550. if (unwrappingToken.SecurityKeys[i].IsSupportedAlgorithm(encryptionMethod))
  551. {
  552. unwrappingSecurityKey = unwrappingToken.SecurityKeys[i];
  553. break;
  554. }
  555. }
  556. }
  557. if (unwrappingSecurityKey == null)
  558. {
  559. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.CannotFindMatchingCrypto, encryptionMethod)));
  560. }
  561. return unwrappingSecurityKey.DecryptKey(encryptionMethod, wrappedKey);
  562. }
  563. internal static byte[] EncryptKey(SecurityToken wrappingToken, string encryptionMethod, byte[] keyToWrap)
  564. {
  565. SecurityKey wrappingSecurityKey = null;
  566. if (wrappingToken.SecurityKeys != null)
  567. {
  568. for (int i = 0; i < wrappingToken.SecurityKeys.Count; ++i)
  569. {
  570. if (wrappingToken.SecurityKeys[i].IsSupportedAlgorithm(encryptionMethod))
  571. {
  572. wrappingSecurityKey = wrappingToken.SecurityKeys[i];
  573. break;
  574. }
  575. }
  576. }
  577. if (wrappingSecurityKey == null)
  578. {
  579. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.CannotFindMatchingCrypto, encryptionMethod));
  580. }
  581. return wrappingSecurityKey.EncryptKey(encryptionMethod, keyToWrap);
  582. }
  583. internal static byte[] ReadContentAsBase64(XmlDictionaryReader reader, long maxBufferSize)
  584. {
  585. if (reader == null)
  586. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
  587. // Code cloned from System.Xml.XmlDictionaryReder.
  588. byte[][] buffers = new byte[32][];
  589. byte[] buffer;
  590. // Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
  591. int count = 384;
  592. int bufferCount = 0;
  593. int totalRead = 0;
  594. while (true)
  595. {
  596. buffer = new byte[count];
  597. buffers[bufferCount++] = buffer;
  598. int read = 0;
  599. while (read < buffer.Length)
  600. {
  601. int actual = reader.ReadContentAsBase64(buffer, read, buffer.Length - read);
  602. if (actual == 0)
  603. break;
  604. read += actual;
  605. }
  606. if (totalRead > maxBufferSize - read)
  607. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(SR.GetString(SR.BufferQuotaExceededReadingBase64, maxBufferSize)));
  608. totalRead += read;
  609. if (read < buffer.Length)
  610. break;
  611. count = count * 2;
  612. }
  613. buffer = new byte[totalRead];
  614. int offset = 0;
  615. for (int i = 0; i < bufferCount - 1; i++)
  616. {
  617. Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length);
  618. offset += buffers[i].Length;
  619. }
  620. Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset);
  621. return buffer;
  622. }
  623. internal static byte[] GenerateDerivedKey(SecurityToken tokenToDerive, string derivationAlgorithm, byte[] label, byte[] nonce,
  624. int keySize, int offset)
  625. {
  626. SymmetricSecurityKey symmetricSecurityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(tokenToDerive);
  627. if (symmetricSecurityKey == null || !symmetricSecurityKey.IsSupportedAlgorithm(derivationAlgorithm))
  628. {
  629. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.CannotFindMatchingCrypto, derivationAlgorithm)));
  630. }
  631. return symmetricSecurityKey.GenerateDerivedKey(derivationAlgorithm, label, nonce, keySize, offset);
  632. }
  633. internal static string GetSpnFromIdentity(EndpointIdentity identity, EndpointAddress target)
  634. {
  635. bool foundSpn = false;
  636. string spn = null;
  637. if (identity != null)
  638. {
  639. if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
  640. {
  641. spn = (string)identity.IdentityClaim.Resource;
  642. foundSpn = true;
  643. }
  644. else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
  645. {
  646. spn = (string)identity.IdentityClaim.Resource;
  647. foundSpn = true;
  648. }
  649. else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
  650. {
  651. spn = String.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
  652. foundSpn = true;
  653. }
  654. }
  655. if (!foundSpn)
  656. {
  657. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.CannotDetermineSPNBasedOnAddress, target)));
  658. }
  659. return spn;
  660. }
  661. internal static string GetSpnFromTarget(EndpointAddress target)
  662. {
  663. if (target == null)
  664. {
  665. throw Fx.AssertAndThrow("target should not be null - expecting an EndpointAddress");
  666. }
  667. return string.Format(CultureInfo.InvariantCulture, "host/{0}", target.Uri.DnsSafeHost);
  668. }
  669. internal static bool IsSupportedAlgorithm(string algorithm, SecurityToken token)
  670. {
  671. if (token.SecurityKeys == null)
  672. {
  673. return false;
  674. }
  675. for (int i = 0; i < token.SecurityKeys.Count; ++i)
  676. {
  677. if (token.SecurityKeys[i].IsSupportedAlgorithm(algorithm))
  678. {
  679. return true;
  680. }
  681. }
  682. return false;
  683. }
  684. internal static Claim GetPrimaryIdentityClaim(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
  685. {
  686. return GetPrimaryIdentityClaim(AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies));
  687. }
  688. internal static Claim GetPrimaryIdentityClaim(AuthorizationContext authContext)
  689. {
  690. if (authContext != null)
  691. {
  692. for (int i = 0; i < authContext.ClaimSets.Count; ++i)
  693. {
  694. ClaimSet claimSet = authContext.ClaimSets[i];
  695. foreach (Claim claim in claimSet.FindClaims(null, Rights.Identity))
  696. {
  697. return claim;
  698. }
  699. }
  700. }
  701. return null;
  702. }
  703. internal static int GetServiceAddressAndViaHash(EndpointAddress sr)
  704. {
  705. if (sr == null)
  706. {
  707. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sr");
  708. }
  709. return sr.GetHashCode();
  710. }
  711. internal static string GenerateId()
  712. {
  713. return SecurityUniqueId.Create().Value;
  714. }
  715. internal static string GenerateIdWithPrefix(string prefix)
  716. {
  717. return SecurityUniqueId.Create(prefix).Value;
  718. }
  719. internal static UniqueId GenerateUniqueId()
  720. {
  721. return new UniqueId();
  722. }
  723. internal static string GetPrimaryDomain()
  724. {
  725. using (WindowsIdentity wid = WindowsIdentity.GetCurrent())
  726. {
  727. return GetPrimaryDomain(IsSystemAccount(wid));
  728. }
  729. }
  730. internal static string GetPrimaryDomain(bool isSystemAccount)
  731. {
  732. if (computedDomain == false)
  733. {
  734. try
  735. {
  736. if (isSystemAccount)
  737. {
  738. currentDomain = Domain.GetComputerDomain().Name;
  739. }
  740. else
  741. {
  742. currentDomain = Domain.GetCurrentDomain().Name;
  743. }
  744. }
  745. #pragma warning suppress 56500 // covered by FxCOP
  746. catch (Exception e)
  747. {
  748. if (Fx.IsFatal(e))
  749. {
  750. throw;
  751. }
  752. DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
  753. }
  754. finally
  755. {
  756. computedDomain = true;
  757. }
  758. }
  759. return currentDomain;
  760. }
  761. internal static void EnsureCertificateCanDoKeyExchange(X509Certificate2 certificate)
  762. {
  763. if (certificate == null)
  764. {
  765. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
  766. }
  767. bool canDoKeyExchange = false;
  768. Exception innerException = null;
  769. if (certificate.HasPrivateKey)
  770. {
  771. try
  772. {
  773. canDoKeyExchange = CanKeyDoKeyExchange(certificate);
  774. }
  775. // exceptions can be due to ACLs on the key etc
  776. catch (System.Security.SecurityException e)
  777. {
  778. innerException = e;
  779. }
  780. catch (CryptographicException e)
  781. {
  782. innerException = e;
  783. }
  784. }
  785. if (!canDoKeyExchange)
  786. {
  787. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMayNotDoKeyExchange, certificate.SubjectName.Name), innerException));
  788. }
  789. }
  790. [Fx.Tag.SecurityNote(Critical = "Calls critical method GetKeyContainerInfo.",
  791. Safe = "Info is not leaked.")]
  792. [SecuritySafeCritical]
  793. static bool CanKeyDoKeyExchange(X509Certificate2 certificate)
  794. {
  795. CspKeyContainerInfo info = GetKeyContainerInfo(certificate);
  796. return info != null && info.KeyNumber == KeyNumber.Exchange;
  797. }
  798. [Fx.Tag.SecurityNote(Critical = "Elevates to call properties: X509Certificate2.PrivateKey and CspKeyContainerInfo. Caller must protect the return value.")]
  799. [SecurityCritical]
  800. [KeyContainerPermission(SecurityAction.Assert, Flags = KeyContainerPermissionFlags.Open)]
  801. static CspKeyContainerInfo GetKeyContainerInfo(X509Certificate2 certificate)
  802. {
  803. RSACryptoServiceProvider rsa = certificate.PrivateKey as RSACryptoServiceProvider;
  804. if (rsa != null)
  805. {
  806. return rsa.CspKeyContainerInfo;
  807. }
  808. return null;
  809. }
  810. internal static string GetCertificateId(X509Certificate2 certificate)
  811. {
  812. StringBuilder str = new StringBuilder(256);
  813. AppendCertificateIdentityName(str, certificate);
  814. return str.ToString();
  815. }
  816. internal static ReadOnlyCollection<IAuthorizationPolicy> CreatePrincipalNameAuthorizationPolicies(string principalName)
  817. {
  818. if (principalName == null)
  819. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("principalName");
  820. Claim identityClaim;
  821. Claim primaryPrincipal;
  822. if (principalName.Contains("@") || principalName.Contains(@"\"))
  823. {
  824. identityClaim = new Claim(ClaimTypes.Upn, principalName, Rights.Identity);
  825. primaryPrincipal = Claim.CreateUpnClaim(principalName);
  826. }
  827. else
  828. {
  829. identityClaim = new Claim(ClaimTypes.Spn, principalName, Rights.Identity);
  830. primaryPrincipal = Claim.CreateSpnClaim(principalName);
  831. }
  832. List<Claim> claims = new List<Claim>(2);
  833. claims.Add(identityClaim);
  834. claims.Add(primaryPrincipal);
  835. List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
  836. policies.Add(new UnconditionalPolicy(SecurityUtils.CreateIdentity(principalName), new DefaultClaimSet(ClaimSet.Anonymous, claims)));
  837. return policies.AsReadOnly();
  838. }
  839. internal static string GetIdentityNamesFromPolicies(IList<IAuthorizationPolicy> authPolicies)
  840. {
  841. return GetIdentityNamesFromContext(AuthorizationContext.CreateDefaultAuthorizationContext(authPolicies));
  842. }
  843. internal static string GetIdentityNamesFromContext(AuthorizationContext authContext)
  844. {
  845. if (authContext == null)
  846. return String.Empty;
  847. StringBuilder str = new StringBuilder(256);
  848. for (int i = 0; i < authContext.ClaimSets.Count; ++i)
  849. {
  850. ClaimSet claimSet = authContext.ClaimSets[i];
  851. // Windows
  852. WindowsClaimSet windows = claimSet as WindowsClaimSet;
  853. if (windows != null)
  854. {
  855. if (str.Length > 0)
  856. str.Append(", ");
  857. AppendIdentityName(str, windows.WindowsIdentity);
  858. }
  859. else
  860. {
  861. // X509
  862. X509CertificateClaimSet x509 = claimSet as X509CertificateClaimSet;
  863. if (x509 != null)
  864. {
  865. if (str.Length > 0)
  866. str.Append(", ");
  867. AppendCertificateIdentityName(str, x509.X509Certificate);
  868. }
  869. }
  870. }
  871. if (str.Length <= 0)
  872. {
  873. List<IIdentity> identities = null;
  874. object obj;
  875. if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj))
  876. {
  877. identities = obj as List<IIdentity>;
  878. }
  879. if (identities != null)
  880. {
  881. for (int i = 0; i < identities.Count; ++i)
  882. {
  883. IIdentity identity = identities[i];
  884. if (identity != null)
  885. {
  886. if (str.Length > 0)
  887. str.Append(", ");
  888. AppendIdentityName(str, identity);
  889. }
  890. }
  891. }
  892. }
  893. return str.Length <= 0 ? String.Empty : str.ToString();
  894. }
  895. internal static void AppendCertificateIdentityName(StringBuilder str, X509Certificate2 certificate)
  896. {
  897. string value = certificate.SubjectName.Name;
  898. if (String.IsNullOrEmpty(value))
  899. {
  900. value = certificate.GetNameInfo(X509NameType.DnsName, false);
  901. if (String.IsNullOrEmpty(value))
  902. {
  903. value = certificate.GetNameInfo(X509NameType.SimpleName, false);
  904. if (String.IsNullOrEmpty(value))
  905. {
  906. value = certificate.GetNameInfo(X509NameType.EmailName, false);
  907. if (String.IsNullOrEmpty(value))
  908. {
  909. value = certificate.GetNameInfo(X509NameType.UpnName, false);
  910. }
  911. }
  912. }
  913. }
  914. // Same format as X509Identity
  915. str.Append(String.IsNullOrEmpty(value) ? "<x509>" : value);
  916. str.Append("; ");
  917. str.Append(certificate.Thumbprint);
  918. }
  919. internal static void AppendIdentityName(StringBuilder str, IIdentity identity)
  920. {
  921. string name = null;
  922. try
  923. {
  924. name = identity.Name;
  925. }
  926. #pragma warning suppress 56500
  927. catch (Exception e)
  928. {
  929. if (Fx.IsFatal(e))
  930. {
  931. throw;
  932. }
  933. // suppress exception, this is just info.
  934. }
  935. str.Append(String.IsNullOrEmpty(name) ? "<null>" : name);
  936. WindowsIdentity windows = identity as WindowsIdentity;
  937. if (windows != null)
  938. {
  939. if (windows.User != null)
  940. {
  941. str.Append("; ");
  942. str.Append(windows.User.ToString());
  943. }
  944. }
  945. else
  946. {
  947. WindowsSidIdentity sid = identity as WindowsSidIdentity;
  948. if (sid != null)
  949. {
  950. str.Append("; ");
  951. str.Append(sid.SecurityIdentifier.ToString());
  952. }
  953. }
  954. }
  955. [Fx.Tag.SecurityNote(Critical = "Calls critical methods UnsafeGetDomain, UnsafeGetUserName, UnsafeGetPassword and UnsafeGetCurrentUserSidAsString.")]
  956. [SecurityCritical]
  957. internal static string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
  958. AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
  959. {
  960. const string delimiter = "\0"; // nonprintable characters are invalid for SSPI Domain/UserName/Password
  961. if (IsDefaultNetworkCredential(credential))
  962. {
  963. string sid = UnsafeGetCurrentUserSidAsString();
  964. return string.Concat(inputString, delimiter,
  965. sid, delimiter,
  966. AuthenticationLevelHelper.ToString(authenticationLevel), delimiter,
  967. TokenImpersonationLevelHelper.ToString(impersonationLevel));
  968. }
  969. else
  970. {
  971. return string.Concat(inputString, delimiter,
  972. NetworkCredentialHelper.UnsafeGetDomain(credential), delimiter,
  973. NetworkCredentialHelper.UnsafeGetUsername(credential), delimiter,
  974. NetworkCredentialHelper.UnsafeGetPassword(credential), delimiter,
  975. AuthenticationLevelHelper.ToString(authenticationLevel), delimiter,
  976. TokenImpersonationLevelHelper.ToString(impersonationLevel));
  977. }
  978. }
  979. internal static string GetIdentityName(IIdentity identity)
  980. {
  981. StringBuilder str = new StringBuilder(256);
  982. AppendIdentityName(str, identity);
  983. return str.ToString();
  984. }
  985. /// <SecurityNote>
  986. /// Critical - Calls an UnsafeNativeMethod and a Critical method (GetFipsAlgorithmPolicyKeyFromRegistry)
  987. /// Safe - processes the return and just returns a bool, which is safe
  988. /// </SecurityNote>
  989. internal static bool IsChannelBindingDisabled
  990. {
  991. [SecuritySafeCritical]
  992. get
  993. {
  994. return ((GetSuppressChannelBindingValue() & 0x1) != 0);
  995. }
  996. }
  997. const string suppressChannelBindingRegistryKey = @"System\CurrentControlSet\Control\Lsa";
  998. /// <SecurityNote>
  999. /// Critical - Asserts to get a value from the registry
  1000. /// </SecurityNote>
  1001. [SecurityCritical]
  1002. [RegistryPermission(SecurityAction.Assert, Read = @"HKEY_LOCAL_MACHINE\" + suppressChannelBindingRegistryKey)]
  1003. internal static int GetSuppressChannelBindingValue()
  1004. {
  1005. int channelBindingPolicyKeyValue = 0;
  1006. try
  1007. {
  1008. using (RegistryKey channelBindingPolicyKey = Registry.LocalMachine.OpenSubKey(suppressChannelBindingRegistryKey, false))
  1009. {
  1010. if (channelBindingPolicyKey != null)
  1011. {
  1012. object data = channelBindingPolicyKey.GetValue("SuppressChannelBindingInfo");
  1013. if (data != null)
  1014. channelBindingPolicyKeyValue = (int)data;
  1015. }
  1016. }
  1017. }
  1018. #pragma warning suppress 56500
  1019. catch (Exception e)
  1020. {
  1021. if (Fx.IsFatal(e))
  1022. throw;
  1023. }
  1024. return channelBindingPolicyKeyValue;
  1025. }
  1026. internal static bool IsSecurityBindingSuitableForChannelBinding(TransportSecurityBindingElement securityBindingElement)
  1027. {
  1028. if (securityBindingElement == null)
  1029. {
  1030. return false;
  1031. }
  1032. // channel binding of OperationSupportingTokenParameters, OptionalEndpointSupportingTokenParameters, or OptionalOperationSupportingTokenParameters
  1033. // is not supported in Win7
  1034. if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.Endorsing))
  1035. {
  1036. return true;
  1037. }
  1038. if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.Signed))
  1039. {
  1040. return true;
  1041. }
  1042. if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.SignedEncrypted))
  1043. {
  1044. return true;
  1045. }
  1046. if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.SignedEndorsing))
  1047. {
  1048. return true;
  1049. }
  1050. return false;
  1051. }
  1052. internal static bool AreSecurityTokenParametersSuitableForChannelBinding(Collection<SecurityTokenParameters> tokenParameters)
  1053. {
  1054. if (tokenParameters == null)
  1055. {
  1056. return false;
  1057. }
  1058. foreach (SecurityTokenParameters stp in tokenParameters)
  1059. {
  1060. if (stp is SspiSecurityTokenParameters || stp is KerberosSecurityTokenParameters)
  1061. {
  1062. return true;
  1063. }
  1064. SecureConversationSecurityTokenParameters scstp = stp as SecureConversationSecurityTokenParameters;
  1065. if (scstp != null)
  1066. {
  1067. return IsSecurityBindingSuitableForChannelBinding(scstp.BootstrapSecurityBindingElement as TransportSecurityBindingElement);
  1068. }
  1069. }
  1070. return false;
  1071. }
  1072. internal static void ThrowIfNegotiationFault(Message message, EndpointAddress target)
  1073. {
  1074. if (message.IsFault)
  1075. {
  1076. MessageFault fault = MessageFault.CreateFault(message, TransportDefaults.MaxSecurityFaultSize);
  1077. Exception faultException = new FaultException(fault, message.Headers.Action);
  1078. if (fault.Code != null && fault.Code.IsReceiverFault && fault.Code.SubCode != null)
  1079. {
  1080. FaultCode subCode = fault.Code.SubCode;
  1081. if (subCode.Name == DotNetSecurityStrings.SecurityServerTooBusyFault && subCode.Namespace == DotNetSecurityStrings.Namespace)
  1082. {
  1083. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServerTooBusyException(SR.GetString(SR.SecurityServerTooBusy, target), faultException));
  1084. }
  1085. else if (subCode.Name == AddressingStrings.EndpointUnavailable && subCode.Namespace == message.Version.Addressing.Namespace)
  1086. {
  1087. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.GetString(SR.SecurityEndpointNotFound, target), faultException));
  1088. }
  1089. }
  1090. throw TraceUtility.ThrowHelperError(faultException, message);
  1091. }
  1092. }
  1093. internal static bool IsSecurityFault(MessageFault fault, SecurityStandardsManager standardsManager)
  1094. {
  1095. if (fault.Code.IsSenderFault)
  1096. {
  1097. FaultCode subCode = fault.Code.SubCode;
  1098. if (subCode != null)
  1099. {
  1100. return (subCode.Namespace == standardsManager.SecurityVersion.HeaderNamespace.Value
  1101. || subCode.Namespace == standardsManager.SecureConversationDriver.Namespace.Value
  1102. || subCode.Namespace == standardsManager.TrustDriver.Namespace.Value
  1103. || subCode.Namespace == DotNetSecurityStrings.Namespace);
  1104. }
  1105. }
  1106. return false;
  1107. }
  1108. internal static Exception CreateSecurityFaultException(Message unverifiedMessage)
  1109. {
  1110. MessageFault fault = MessageFault.CreateFault(unverifiedMessage, TransportDefaults.MaxSecurityFaultSize);
  1111. return CreateSecurityFaultException(fault);
  1112. }
  1113. internal static Exception CreateSecurityFaultException(MessageFault fault)
  1114. {
  1115. FaultException faultException = FaultException.CreateFault(fault, typeof(string), typeof(object));
  1116. return new MessageSecurityException(SR.GetString(SR.UnsecuredMessageFaultReceived), faultException);
  1117. }
  1118. internal static MessageFault CreateSecurityContextNotFoundFault(SecurityStandardsManager standardsManager, string action)
  1119. {
  1120. SecureConversationDriver scDriver = standardsManager.SecureConversationDriver;
  1121. FaultCode subCode = new FaultCode(scDriver.BadContextTokenFaultCode.Value, scDriver.Namespace.Value);
  1122. FaultReason reason;
  1123. if (action != null)
  1124. {
  1125. reason = new FaultReason(SR.GetString(SR.BadContextTokenOrActionFaultReason, action), CultureInfo.CurrentCulture);
  1126. }
  1127. else
  1128. {
  1129. reason = new FaultReason(SR.GetString(SR.BadContextTokenFaultReason), CultureInfo.CurrentCulture);
  1130. }
  1131. FaultCode senderCode = FaultCode.CreateSenderFaultCode(subCode);
  1132. return MessageFault.CreateFault(senderCode, reason);
  1133. }
  1134. internal static MessageFault CreateSecurityMessageFault(Exception e, SecurityStandardsManager standardsManager)
  1135. {
  1136. bool isSecurityError = false;
  1137. bool isTokenValidationError = false;
  1138. bool isGenericTokenError = false;
  1139. FaultException faultException = null;
  1140. while (e != null)
  1141. {
  1142. if (e is SecurityTokenValidationException)
  1143. {
  1144. if (e is SecurityContextTokenValidationException)
  1145. {
  1146. return CreateSecurityContextNotFoundFault(SecurityStandardsManager.DefaultInstance, null);
  1147. }
  1148. isSecurityError = true;
  1149. isTokenValidationError = true;
  1150. break;
  1151. }
  1152. else if (e is SecurityTokenException)
  1153. {
  1154. isSecurityError = true;
  1155. isGenericTokenError = true;
  1156. break;
  1157. }
  1158. else if (e is MessageSecurityException)
  1159. {
  1160. MessageSecurityException ms = (MessageSecurityException)e;
  1161. if (ms.Fault != null)
  1162. {
  1163. return ms.Fault;
  1164. }
  1165. isSecurityError = true;
  1166. }
  1167. else if (e is FaultException)
  1168. {
  1169. faultException = (FaultException)e;
  1170. break;
  1171. }
  1172. e = e.InnerException;
  1173. }
  1174. if (!isSecurityError && faultException == null)
  1175. {
  1176. return null;
  1177. }
  1178. FaultCode subCode;
  1179. FaultReason reason;
  1180. SecurityVersion wss = standardsManager.SecurityVersion;
  1181. if (isTokenValidationError)
  1182. {
  1183. subCode = new FaultCode(wss.FailedAuthenticationFaultCode.Value, wss.HeaderNamespace.Value);
  1184. reason = new FaultReason(SR.GetString(SR.FailedAuthenticationFaultReason), CultureInfo.CurrentCulture);
  1185. }
  1186. else if (isGenericTokenError)
  1187. {
  1188. subCode = new FaultCode(wss.InvalidSecurityTokenFaultCode.Value, wss.HeaderNamespace.Value);
  1189. reason = new FaultReason(SR.GetString(SR.InvalidSecurityTokenFaultReason), CultureInfo.CurrentCulture);
  1190. }
  1191. else if (faultException != null)
  1192. {
  1193. // Only support Code and Reason. No detail or action customization.
  1194. return MessageFault.CreateFault(faultException.Code, faultException.Reason);
  1195. }
  1196. else
  1197. {
  1198. subCode = new FaultCode(wss.InvalidSecurityFaultCode.Value, wss.HeaderNamespace.Value);
  1199. reason = new FaultReason(SR.GetString(SR.InvalidSecurityFaultReason), CultureInfo.CurrentCulture);
  1200. }
  1201. FaultCode senderCode = FaultCode.CreateSenderFaultCode(subCode);
  1202. return MessageFault.CreateFault(senderCode, reason);
  1203. }
  1204. internal static bool IsCompositeDuplexBinding(BindingContext context)
  1205. {
  1206. return ((context.Binding.Elements.Find<CompositeDuplexBindingElement>() != null)
  1207. || (context.Binding.Elements.Find<InternalDuplexBindingElement>() != null));
  1208. }
  1209. // The method checks TransportToken, ProtectionToken and all SupportingTokens to find a
  1210. // UserNameSecurityToken. If found, it sets the password of the UserNameSecurityToken to null.
  1211. // Custom UserNameSecurityToken are skipped.
  1212. internal static void ErasePasswordInUsernameTokenIfPresent(SecurityMessageProperty messageProperty)
  1213. {
  1214. if (messageProperty == null)
  1215. {
  1216. // Nothing to fix.
  1217. return;
  1218. }
  1219. if (messageProperty.TransportToken != null)
  1220. {
  1221. UserNameSecurityToken token = messageProperty.TransportToken.SecurityToken as UserNameSecurityToken;
  1222. if ((token != null) && !messageProperty.TransportToken.SecurityToken.GetType().IsSubclassOf(typeof(UserNameSecurityToken)))
  1223. {
  1224. messageProperty.TransportToken = new SecurityTokenSpecification(new UserNameSecurityToken(token.UserName, null, token.Id), messageProperty.TransportToken.SecurityTokenPolicies);
  1225. }
  1226. }
  1227. if (messageProperty.ProtectionToken != null)
  1228. {
  1229. UserNameSecurityToken token = messageProperty.ProtectionToken.SecurityToken as UserNameSecurityToken;
  1230. if ((token != null) && !messageProperty.ProtectionToken.SecurityToken.GetType().IsSubclassOf(typeof(UserNameSecurityToken)))
  1231. {
  1232. messageProperty.ProtectionToken = new SecurityTokenSpecification(new UserNameSecurityToken(token.UserName, null, token.Id), messageProperty.ProtectionToken.SecurityTokenPolicies);
  1233. }
  1234. }
  1235. if (messageProperty.HasIncomingSupportingTokens)
  1236. {
  1237. for (int i = 0; i < messageProperty.IncomingSupportingTokens.Count; ++i)
  1238. {
  1239. SupportingTokenSpecification supportingTokenSpecification = messageProperty.IncomingSupportingTokens[i];
  1240. UserNameSecurityToken token = supportingTokenSpecification.SecurityToken as UserNameSecurityToken;
  1241. if ((token != null) && !supportingTokenSpecification.SecurityToken.GetType().IsSubclassOf(typeof(UserNameSecurityToken)))
  1242. {
  1243. messageProperty.IncomingSupportingTokens[i] = new SupportingTokenSpecification(new UserNameSecurityToken(token.UserName, null, token.Id), supportingTokenSpecification.SecurityTokenPolicies, supportingTokenSpecification.SecurityTokenAttachmentMode, supportingTokenSpecification.SecurityTokenParameters);
  1244. }
  1245. }
  1246. }
  1247. }
  1248. // work-around to Windows SE Bug 141614
  1249. [Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method UnsafeGetPassword to access the credential password without a Demand.",
  1250. Safe = "Only uses the password to construct a cloned NetworkCredential instance, does not leak password value.")]
  1251. [SecuritySafeCritical]
  1252. internal static void FixNetworkCredential(ref NetworkCredential credential)
  1253. {
  1254. if (credential == null)
  1255. {
  1256. return;
  1257. }
  1258. string username = NetworkCredentialHelper.UnsafeGetUsername(credential);
  1259. string domain = NetworkCredentialHelper.UnsafeGetDomain(credential);
  1260. if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(domain))
  1261. {
  1262. // do the splitting only if there is exactly 1 \ or exactly 1 @
  1263. string[] partsWithSlashDelimiter = username.Split('\\');
  1264. string[] partsWithAtDelimiter = username.Split('@');
  1265. if (partsWithSlashDelimiter.Length == 2 && partsWithAtDelimiter.Length == 1)
  1266. {
  1267. if (!string.IsNullOrEmpty(partsWithSlashDelimiter[0]) && !string.IsNullOrEmpty(partsWithSlashDelimiter[1]))
  1268. {
  1269. credential = new NetworkCredential(partsWithSlashDelimiter[1], NetworkCredentialHelper.UnsafeGetPassword(credential), partsWithSlashDelimiter[0]);
  1270. }
  1271. }
  1272. else if (partsWithSlashDelimiter.Length == 1 && partsWithAtDelimiter.Length == 2)
  1273. {
  1274. if (!string.IsNullOrEmpty(partsWithAtDelimiter[0]) && !string.IsNullOrEmpty(partsWithAtDelimiter[1]))
  1275. {
  1276. credential = new NetworkCredential(partsWithAtDelimiter[0], NetworkCredentialHelper.UnsafeGetPassword(credential), partsWithAtDelimiter[1]);
  1277. }
  1278. }
  1279. }
  1280. }
  1281. // WORKAROUND, [....], VSWhidbey 561276: The first NetworkCredential must be created in a lock.
  1282. internal static void PrepareNetworkCredential()
  1283. {
  1284. if (dummyNetworkCredential == null)
  1285. {
  1286. PrepareNetworkCredentialWorker();
  1287. }
  1288. }
  1289. // Since this takes a lock, it probably won't be inlined, but the typical case will be.
  1290. static void PrepareNetworkCredentialWorker()
  1291. {
  1292. lock (dummyNetworkCredentialLock)
  1293. {
  1294. dummyNetworkCredential = new NetworkCredential("dummy", "dummy");
  1295. }
  1296. }
  1297. // This is the workaround, Since store.Certificates returns a full collection
  1298. // of certs in store. These are holding native resources.
  1299. internal static void ResetAllCertificates(X509Certificate2Collection certificates)
  1300. {
  1301. if (certificates != null)
  1302. {
  1303. for (int i = 0; i < certificates.Count; ++i)
  1304. {
  1305. ResetCertificate(certificates[i]);
  1306. }
  1307. }
  1308. }
  1309. [Fx.Tag.SecurityNote(Critical = "Calls critical method X509Certificate2.Reset.",
  1310. Safe = "Per review from CLR security team, this method does nothing unsafe.")]
  1311. [SecuritySafeCritical]
  1312. internal static void ResetCertificate(X509Certificate2 certificate)
  1313. {
  1314. certificate.Reset();
  1315. }
  1316. internal static bool IsDefaultNetworkCredential(NetworkCredential credential)
  1317. {
  1318. return NetworkCredentialHelper.IsDefault(credential);
  1319. }
  1320. internal static void OpenTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout)
  1321. {
  1322. OpenCommunicationObject(tokenProvider as ICommunicationObject, timeout);
  1323. }
  1324. internal static IAsyncResult BeginOpenTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout,
  1325. AsyncCallback callback, object state)
  1326. {
  1327. return new OpenCommunicationObjectAsyncResult(tokenProvider, timeout, callback, state);
  1328. }
  1329. internal static void EndOpenTokenProviderIfRequired(IAsyncResult result)
  1330. {
  1331. OpenCommunicationObjectAsyncResult.End(result);
  1332. }
  1333. internal static IAsyncResult BeginCloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout,
  1334. AsyncCallback callback, object state)
  1335. {
  1336. return new CloseCommunicationObjectAsyncResult(tokenProvider, timeout, callback, state);
  1337. }
  1338. internal static void EndCloseTokenProviderIfRequired(IAsyncResult result)
  1339. {
  1340. CloseCommunicationObjectAsyncResult.End(result);
  1341. }
  1342. internal static void CloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout)
  1343. {
  1344. CloseCommunicationObject(tokenProvider, false, timeout);
  1345. }
  1346. internal static void CloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, bool aborted, TimeSpan timeout)
  1347. {
  1348. CloseCommunicationObject(tokenProvider, aborted, timeout);
  1349. }
  1350. internal static void AbortTokenProviderIfRequired(SecurityTokenProvider tokenProvider)
  1351. {
  1352. CloseCommunicationObject(tokenProvider, true, TimeSpan.Zero);
  1353. }
  1354. internal static void OpenTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout)
  1355. {
  1356. OpenCommunicationObject(tokenAuthenticator as ICommunicationObject, timeout);
  1357. }
  1358. internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout)
  1359. {
  1360. CloseTokenAuthenticatorIfRequired(tokenAuthenticator, false, timeout);
  1361. }
  1362. internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, bool aborted, TimeSpan timeout)
  1363. {
  1364. CloseCommunicationObject(tokenAuthenticator, aborted, timeout);
  1365. }
  1366. internal static IAsyncResult BeginOpenTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout,
  1367. AsyncCallback callback, object state)
  1368. {
  1369. return new OpenCommunicationObjectAsyncResult(tokenAuthenticator, timeout, callback, state);
  1370. }
  1371. internal static void EndOpenTokenAuthenticatorIfRequired(IAsyncResult result)
  1372. {
  1373. OpenCommunicationObjectAsyncResult.End(result);
  1374. }
  1375. internal static IAsyncResult BeginCloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout,
  1376. AsyncCallback callback, object state)
  1377. {
  1378. return new CloseCommunicationObjectAsyncResult(tokenAuthenticator, timeout, callback, state);
  1379. }
  1380. internal static void EndCloseTokenAuthenticatorIfRequired(IAsyncResult result)
  1381. {
  1382. CloseCommunicationObjectAsyncResult.End(result);
  1383. }
  1384. internal static void AbortTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator)
  1385. {
  1386. CloseCommunicationObject(tokenAuthenticator, true, TimeSpan.Zero);
  1387. }
  1388. static void OpenCommunicationObject(ICommunicationObject obj, TimeSpan timeout)
  1389. {
  1390. if (obj != null)
  1391. obj.Open(timeout);
  1392. }
  1393. static void CloseCommunicationObject(Object obj, bool aborted, TimeSpan timeout)
  1394. {
  1395. if (obj != null)
  1396. {
  1397. ICommunicationObject co = obj as ICommunicationObject;
  1398. if (co != null)
  1399. {
  1400. if (aborted)
  1401. {
  1402. try
  1403. {
  1404. co.Abort();
  1405. }
  1406. catch (CommunicationException e)
  1407. {
  1408. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  1409. }
  1410. }
  1411. else
  1412. {
  1413. co.Close(timeout);
  1414. }
  1415. }
  1416. else if (obj is IDisposable)
  1417. {
  1418. ((IDisposable)obj).Dispose();
  1419. }
  1420. }
  1421. }
  1422. class OpenCommunicationObjectAsyncResult : AsyncResult
  1423. {
  1424. ICommunicationObject communicationObject;
  1425. static AsyncCallback onOpen;
  1426. public OpenCommunicationObjectAsyncResult(object obj, TimeSpan timeout, AsyncCallback callback, object state)
  1427. : base(callback, state)
  1428. {
  1429. this.communicationObject = obj as ICommunicationObject;
  1430. bool completeSelf = false;
  1431. if (this.communicationObject == null)
  1432. {
  1433. completeSelf = true;
  1434. }
  1435. else
  1436. {
  1437. if (onOpen == null)
  1438. {
  1439. onOpen = Fx.ThunkCallback(new AsyncCallback(OnOpen));
  1440. }
  1441. IAsyncResult result = this.communicationObject.BeginOpen(timeout, onOpen, this);
  1442. if (result.CompletedSynchronously)
  1443. {
  1444. this.communicationObject.EndOpen(result);
  1445. completeSelf = true;
  1446. }
  1447. }
  1448. if (completeSelf)
  1449. {
  1450. base.Complete(true);
  1451. }
  1452. }
  1453. public static void End(IAsyncResult result)
  1454. {
  1455. AsyncResult.End<OpenCommunicationObjectAsyncResult>(result);
  1456. }
  1457. static void OnOpen(IAsyncResult result)
  1458. {
  1459. if (result.CompletedSynchronously)
  1460. {
  1461. return;
  1462. }
  1463. OpenCommunicationObjectAsyncResult thisPtr =
  1464. (OpenCommunicationObjectAsyncResult)result.AsyncState;
  1465. Exception completionException = null;
  1466. try
  1467. {
  1468. thisPtr.communicationObject.EndOpen(result);
  1469. }
  1470. #pragma warning suppress 56500 // [....], transferring exception to another thread
  1471. catch (Exception e)
  1472. {
  1473. if (Fx.IsFatal(e))
  1474. {
  1475. throw;
  1476. }
  1477. completionException = e;
  1478. }
  1479. thisPtr.Complete(false, completionException);
  1480. }
  1481. }
  1482. class CloseCommunicationObjectAsyncResult : AsyncResult
  1483. {
  1484. ICommunicationObject communicationObject;
  1485. static AsyncCallback onClose;
  1486. public CloseCommunicationObjectAsyncResult(object obj, TimeSpan timeout, AsyncCallback callback, object state)
  1487. : base(callback, state)
  1488. {
  1489. this.communicationObject = obj as ICommunicationObject;
  1490. bool completeSelf = false;
  1491. if (this.communicationObject == null)
  1492. {
  1493. IDisposable disposable = obj as IDisposable;
  1494. if (disposable != null)
  1495. {
  1496. disposable.Dispose();
  1497. }
  1498. completeSelf = true;
  1499. }
  1500. else
  1501. {
  1502. if (onClose == null)
  1503. {
  1504. onClose = Fx.ThunkCallback(new AsyncCallback(OnClose));
  1505. }
  1506. IAsyncResult result = this.communicationObject.BeginClose(timeout, onClose, this);
  1507. if (result.CompletedSynchronously)
  1508. {
  1509. this.communicationObject.EndClose(result);
  1510. completeSelf = true;
  1511. }
  1512. }
  1513. if (completeSelf)
  1514. {
  1515. base.Complete(true);
  1516. }
  1517. }
  1518. public static void End(IAsyncResult result)
  1519. {
  1520. AsyncResult.End<CloseCommunicationObjectAsyncResult>(result);
  1521. }
  1522. static void OnClose(IAsyncResult result)
  1523. {
  1524. if (result.CompletedSynchronously)
  1525. {
  1526. return;
  1527. }
  1528. CloseCommunicationObjectAsyncResult thisPtr =
  1529. (CloseCommunicationObjectAsyncResult)result.AsyncState;
  1530. Exception completionException = null;
  1531. try
  1532. {
  1533. thisPtr.communicationObject.EndClose(result);
  1534. }
  1535. #pragma warning suppress 56500 // [....], transferring exception to another thread
  1536. catch (Exception e)
  1537. {
  1538. if (Fx.IsFatal(e))
  1539. {
  1540. throw;
  1541. }
  1542. completionException = e;
  1543. }
  1544. thisPtr.Complete(false, completionException);
  1545. }
  1546. }
  1547. internal static void MatchRstWithEndpointFilter(Message rst, IMessageFilterTable<EndpointAddress> endpointFilterTable, Uri listenUri)
  1548. {
  1549. if (endpointFilterTable == null)
  1550. {
  1551. return;
  1552. }
  1553. Collection<EndpointAddress> result = new Collection<EndpointAddress>();
  1554. if (!endpointFilterTable.GetMatchingValues(rst, result))
  1555. {
  1556. throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.RequestSecurityTokenDoesNotMatchEndpointFilters, listenUri)), rst);
  1557. }
  1558. }
  1559. // match the RST with the endpoint filters in case there is at least 1 asymmetric signature in the message
  1560. internal static bool ShouldMatchRstWithEndpointFilter(SecurityBindingElement sbe)
  1561. {
  1562. foreach (SecurityTokenParameters parameters in new SecurityTokenParametersEnumerable(sbe, true))
  1563. {
  1564. if (parameters.HasAsymmetricKey)
  1565. {
  1566. return true;
  1567. }
  1568. }
  1569. return false;
  1570. }
  1571. internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenManager tokenManager)
  1572. {
  1573. SecurityTokenSerializer tokenSerializer = tokenManager.CreateSecurityTokenSerializer(securityVersion.SecurityTokenVersion);
  1574. return new SecurityStandardsManager(securityVersion, tokenSerializer);
  1575. }
  1576. internal static SecurityStandardsManager CreateSecurityStandardsManager(SecurityTokenRequirement requirement, SecurityTokenManager tokenManager)
  1577. {
  1578. MessageSecurityTokenVersion securityVersion = (MessageSecurityTokenVersion)requirement.GetProperty<MessageSecurityTokenVersion>(ServiceModelSecurityTokenRequirement.MessageSecurityVersionProperty);
  1579. if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10)
  1580. return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager);
  1581. else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005)
  1582. return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11, tokenManager);
  1583. else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10)
  1584. return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager);
  1585. else if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10)
  1586. return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager);
  1587. else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13)
  1588. return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, tokenManager);
  1589. else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10)
  1590. return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager);
  1591. else
  1592. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  1593. }
  1594. internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenSerializer securityTokenSerializer)
  1595. {
  1596. if (securityVersion == null)
  1597. {
  1598. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("securityVersion"));
  1599. }
  1600. if (securityTokenSerializer == null)
  1601. {
  1602. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer");
  1603. }
  1604. return new SecurityStandardsManager(securityVersion, securityTokenSerializer);
  1605. }
  1606. static bool TryCreateIdentity(ClaimSet claimSet, string claimType, out EndpointIdentity identity)
  1607. {
  1608. identity = null;
  1609. foreach (Claim claim in claimSet.FindClaims(claimType, null))
  1610. {
  1611. identity = EndpointIdentity.CreateIdentity(claim);
  1612. return true;
  1613. }
  1614. return false;
  1615. }
  1616. internal static EndpointIdentity GetServiceCertificateIdentity(X509Certificate2 certificate)
  1617. {
  1618. using (X509CertificateClaimSet claimSet = new X509CertificateClaimSet(certificate))
  1619. {
  1620. EndpointIdentity identity;
  1621. if (!TryCreateIdentity(claimSet, ClaimTypes.Dns, out identity))
  1622. {
  1623. TryCreateIdentity(claimSet, ClaimTypes.Rsa, out identity);
  1624. }
  1625. return identity;
  1626. }
  1627. }
  1628. [Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method UnsafeGetPassword to access the credential password without a Demand.",
  1629. Safe = "Only uses the password to construct a new NetworkCredential which will then protect access, password does not leak from this method.")]
  1630. [SecuritySafeCritical]
  1631. internal static NetworkCredential GetNetworkCredentialsCopy(NetworkCredential networkCredential)
  1632. {
  1633. NetworkCredential result;
  1634. if (networkCredential != null && !NetworkCredentialHelper.IsDefault(networkCredential))
  1635. {
  1636. result = new NetworkCredential(NetworkCredentialHelper.UnsafeGetUsername(networkCredential), NetworkCredentialHelper.UnsafeGetPassword(networkCredential), NetworkCredentialHelper.UnsafeGetDomain(networkCredential));
  1637. }
  1638. else
  1639. {
  1640. result = networkCredential;
  1641. }
  1642. return result;
  1643. }
  1644. internal static NetworkCredential GetNetworkCredentialOrDefault(NetworkCredential credential)
  1645. {
  1646. // because of VSW 564452, we dont use CredentialCache.DefaultNetworkCredentials in our OM. Instead we
  1647. // use an empty NetworkCredential to denote the default credentials
  1648. if (NetworkCredentialHelper.IsNullOrEmpty(credential))
  1649. {
  1650. // FYI: this will fail with SecurityException in PT due to Demand for EnvironmentPermission.
  1651. // Typically a PT app should not have access to DefaultNetworkCredentials. If there is a valid reason,
  1652. // see UnsafeGetDefaultNetworkCredentials.
  1653. return CredentialCache.DefaultNetworkCredentials;
  1654. }
  1655. else
  1656. {
  1657. return credential;
  1658. }
  1659. }
  1660. static class NetworkCredentialHelper
  1661. {
  1662. [Fx.Tag.SecurityNote(Critical = "Uses unsafe critical methods UnsafeGetUsername, UnsafeGetPassword, and UnsafeGetDomain to access the credential details without a Demand.",
  1663. Safe = "Only uses the protected values to test for null/empty. Does not leak.")]
  1664. [SecuritySafeCritical]
  1665. static internal bool IsNullOrEmpty(NetworkCredential credential)
  1666. {
  1667. return credential == null ||
  1668. (
  1669. String.IsNullOrEmpty(UnsafeGetUsername(credential)) &&
  1670. String.IsNullOrEmpty(UnsafeGetDomain(credential)) &&
  1671. String.IsNullOrEmpty(UnsafeGetPassword(credential))
  1672. );
  1673. }
  1674. [Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method UnsafeGetDefaultNetworkCredentials to access the default network credentials without a Demand.",
  1675. Safe = "Only uses the default credentials to test for equality and uses the system credential's .Equals, not the caller's.")]
  1676. [SecuritySafeCritical]
  1677. static internal bool IsDefault(NetworkCredential credential)
  1678. {
  1679. return UnsafeGetDefaultNetworkCredentials().Equals(credential);
  1680. }
  1681. [Fx.Tag.SecurityNote(Critical = "Asserts SecurityPermission(UnmanagedCode) in order to get the NetworkCredential password."
  1682. + "This is used for example to test for empty/null or to construct a cloned NetworkCredential."
  1683. + "Callers absolutely must not leak the return value.")]
  1684. [SecurityCritical]
  1685. [EnvironmentPermission(SecurityAction.Assert, Read = "USERNAME")]
  1686. static internal string UnsafeGetUsername(NetworkCredential credential)
  1687. {
  1688. return credential.UserName;
  1689. }
  1690. [Fx.Tag.SecurityNote(Critical = "Asserts SecurityPermission(UnmanagedCode) in order to get the NetworkCredential password."
  1691. + "This is used for example to test for empty/null or to construct a cloned NetworkCredential."
  1692. + "Callers absolutely must not leak the return value.")]
  1693. [SecurityCritical]
  1694. [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
  1695. static internal string UnsafeGetPassword(NetworkCredential credential)
  1696. {
  1697. return credential.Password;
  1698. }
  1699. [Fx.Tag.SecurityNote(Critical = "Asserts SecurityPermission(UnmanagedCode) in order to get the NetworkCredential password."
  1700. + "This is used for example to test for empty/null or to construct a cloned NetworkCredential."
  1701. + "Callers absolutely must not leak the return value.")]
  1702. [SecurityCritical]
  1703. [EnvironmentPermission(SecurityAction.Assert, Read = "USERDOMAIN")]
  1704. static internal string UnsafeGetDomain(NetworkCredential credential)
  1705. {
  1706. return credential.Domain;
  1707. }
  1708. [Fx.Tag.SecurityNote(Critical = "Asserts EnvironmentPermission(Read='USERNAME') in order to get the DefaultNetworkCredentials in PT."
  1709. + "This is used for example to test for instance equality with a specific NetworkCredential."
  1710. + "Callers absolutely must not leak the return value.")]
  1711. [SecurityCritical]
  1712. [EnvironmentPermission(SecurityAction.Assert, Read = "USERNAME")]
  1713. static NetworkCredential UnsafeGetDefaultNetworkCredentials()
  1714. {
  1715. return CredentialCache.DefaultNetworkCredentials;
  1716. }
  1717. }
  1718. internal static SafeFreeCredentials GetCredentialsHandle(string package, NetworkCredential credential, bool isServer, params string[] additionalPackages)
  1719. {
  1720. SafeFreeCredentials credentialsHandle;
  1721. CredentialUse credentialUse = isServer ? CredentialUse.Inbound : CredentialUse.Outbound;
  1722. if (credential == null || NetworkCredentialHelper.IsDefault(credential))
  1723. {
  1724. AuthIdentityEx authIdentity = new AuthIdentityEx(null, null, null, additionalPackages);
  1725. credentialsHandle = SspiWrapper.AcquireCredentialsHandle(package, credentialUse, ref authIdentity);
  1726. }
  1727. else
  1728. {
  1729. SecurityUtils.FixNetworkCredential(ref credential);
  1730. // we're not using DefaultCredentials, we need a
  1731. // AuthIdentity struct to contain credentials
  1732. AuthIdentityEx authIdentity = new AuthIdentityEx(credential.UserName, credential.Password, credential.Domain);
  1733. credentialsHandle = SspiWrapper.AcquireCredentialsHandle(package, credentialUse, ref authIdentity);
  1734. }
  1735. return credentialsHandle;
  1736. }
  1737. internal static SafeFreeCredentials GetCredentialsHandle(Binding binding, KeyedByTypeCollection<IEndpointBehavior> behaviors)
  1738. {
  1739. ClientCredentials clientCredentials = (behaviors == null) ? null : behaviors.Find<ClientCredentials>();
  1740. return GetCredentialsHandle(binding, clientCredentials);
  1741. }
  1742. internal static SafeFreeCredentials GetCredentialsHandle(Binding binding, ClientCredentials clientCredentials)
  1743. {
  1744. SecurityBindingElement sbe = (binding == null) ? null : binding.CreateBindingElements().Find<SecurityBindingElement>();
  1745. return GetCredentialsHandle(sbe, clientCredentials);
  1746. }
  1747. internal static SafeFreeCredentials GetCredentialsHandle(SecurityBindingElement sbe, BindingContext context)
  1748. {
  1749. ClientCredentials clientCredentials = (context == null) ? null : context.BindingParameters.Find<ClientCredentials>();
  1750. return GetCredentialsHandle(sbe, clientCredentials);
  1751. }
  1752. internal static SafeFreeCredentials GetCredentialsHandle(SecurityBindingElement sbe, ClientCredentials clientCredentials)
  1753. {
  1754. if (sbe == null)
  1755. {
  1756. return null;
  1757. }
  1758. bool isSspi = false;
  1759. bool isKerberos = false;
  1760. foreach (SecurityTokenParameters stp in new SecurityTokenParametersEnumerable(sbe, true))
  1761. {
  1762. if (stp is SecureConversationSecurityTokenParameters)
  1763. {
  1764. SafeFreeCredentials result = GetCredentialsHandle(((SecureConversationSecurityTokenParameters)stp).BootstrapSecurityBindingElement, clientCredentials);
  1765. if (result != null)
  1766. {
  1767. return result;
  1768. }
  1769. continue;
  1770. }
  1771. else if (stp is IssuedSecurityTokenParameters)
  1772. {
  1773. SafeFreeCredentials result = GetCredentialsHandle(((IssuedSecurityTokenParameters)stp).IssuerBinding, clientCredentials);
  1774. if (result != null)
  1775. {
  1776. return result;
  1777. }
  1778. continue;
  1779. }
  1780. else if (stp is SspiSecurityTokenParameters)
  1781. {
  1782. isSspi = true;
  1783. break;
  1784. }
  1785. else if (stp is KerberosSecurityTokenParameters)
  1786. {
  1787. isKerberos = true;
  1788. break;
  1789. }
  1790. }
  1791. if (!isSspi && !isKerberos)
  1792. {
  1793. return null;
  1794. }
  1795. NetworkCredential credential = null;
  1796. if (clientCredentials != null)
  1797. {
  1798. credential = SecurityUtils.GetNetworkCredentialOrDefault(clientCredentials.Windows.ClientCredential);
  1799. }
  1800. if (isKerberos)
  1801. {
  1802. return SecurityUtils.GetCredentialsHandle("Kerberos", credential, false);
  1803. }
  1804. // if OS is less that Vista cannot use !NTLM, Windows SE 142400
  1805. // To disable AllowNtlm warning.
  1806. #pragma warning disable 618
  1807. else if (clientCredentials != null && !clientCredentials.Windows.AllowNtlm)
  1808. {
  1809. if (SecurityUtils.IsOsGreaterThanXP())
  1810. {
  1811. return SecurityUtils.GetCredentialsHandle("Negotiate", credential, false, "!NTLM");
  1812. }
  1813. else
  1814. {
  1815. return SecurityUtils.GetCredentialsHandle("Kerberos", credential, false);
  1816. }
  1817. }
  1818. #pragma warning restore 618
  1819. return SecurityUtils.GetCredentialsHandle("Negotiate", credential, false);
  1820. }
  1821. internal static byte[] CloneBuffer(byte[] buffer)
  1822. {
  1823. byte[] copy = DiagnosticUtility.Utility.AllocateByteArray(buffer.Length);
  1824. Buffer.BlockCopy(buffer, 0, copy, 0, buffer.Length);
  1825. return copy;
  1826. }
  1827. internal static X509Certificate2 GetCertificateFromStore(StoreName storeName, StoreLocation storeLocation,
  1828. X509FindType findType, object findValue, EndpointAddress target)
  1829. {
  1830. X509Certificate2 certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, true);
  1831. if (certificate == null)
  1832. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotFindCert, storeName, storeLocation, findType, findValue)));
  1833. return certificate;
  1834. }
  1835. internal static bool TryGetCertificateFromStore(StoreName storeName, StoreLocation storeLocation,
  1836. X509FindType findType, object findValue, EndpointAddress target, out X509Certificate2 certificate)
  1837. {
  1838. certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, false);
  1839. return (certificate != null);
  1840. }
  1841. static X509Certificate2 GetCertificateFromStoreCore(StoreName storeName, StoreLocation storeLocation,
  1842. X509FindType findType, object findValue, EndpointAddress target, bool throwIfMultipleOrNoMatch)
  1843. {
  1844. if (findValue == null)
  1845. {
  1846. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
  1847. }
  1848. X509CertificateStore store = new X509CertificateStore(storeName, storeLocation);
  1849. X509Certificate2Collection certs = null;
  1850. try
  1851. {
  1852. store.Open(OpenFlags.ReadOnly);
  1853. certs = store.Find(findType, findValue, false);
  1854. if (certs.Count == 1)
  1855. {
  1856. return new X509Certificate2(certs[0]);
  1857. }
  1858. if (throwIfMultipleOrNoMatch)
  1859. {
  1860. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateCertificateLoadException(
  1861. storeName, storeLocation, findType, findValue, target, certs.Count));
  1862. }
  1863. else
  1864. {
  1865. return null;
  1866. }
  1867. }
  1868. finally
  1869. {
  1870. SecurityUtils.ResetAllCertificates(certs);
  1871. store.Close();
  1872. }
  1873. }
  1874. static Exception CreateCertificateLoadException(StoreName storeName, StoreLocation storeLocation,
  1875. X509FindType findType, object findValue, EndpointAddress target, int certCount)
  1876. {
  1877. if (certCount == 0)
  1878. {
  1879. if (target == null)
  1880. {
  1881. return new InvalidOperationException(SR.GetString(SR.CannotFindCert, storeName, storeLocation, findType, findValue));
  1882. }
  1883. else
  1884. {
  1885. return new InvalidOperationException(SR.GetString(SR.CannotFindCertForTarget, storeName, storeLocation, findType, findValue, target));
  1886. }
  1887. }
  1888. else
  1889. {
  1890. if (target == null)
  1891. {
  1892. return new InvalidOperationException(SR.GetString(SR.FoundMultipleCerts, storeName, storeLocation, findType, findValue));
  1893. }
  1894. else
  1895. {
  1896. return new InvalidOperationException(SR.GetString(SR.FoundMultipleCertsForTarget, storeName, storeLocation, findType, findValue, target));
  1897. }
  1898. }
  1899. }
  1900. public static SecurityBindingElement GetIssuerSecurityBindingElement(ServiceModelSecurityTokenRequirement requirement)
  1901. {
  1902. SecurityBindingElement bindingElement = requirement.SecureConversationSecurityBindingElement;
  1903. if (bindingElement != null)
  1904. {
  1905. return bindingElement;
  1906. }
  1907. Binding binding = requirement.IssuerBinding;
  1908. if (binding == null)
  1909. {
  1910. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.IssuerBindingNotPresentInTokenRequirement, requirement));
  1911. }
  1912. BindingElementCollection bindingElements = binding.CreateBindingElements();
  1913. return bindingElements.Find<SecurityBindingElement>();
  1914. }
  1915. public static int GetMaxNegotiationBufferSize(BindingContext bindingContext)
  1916. {
  1917. TransportBindingElement transport = bindingContext.RemainingBindingElements.Find<TransportBindingElement>();
  1918. Fx.Assert(transport != null, "TransportBindingElement is null!");
  1919. int maxNegoMessageSize;
  1920. if (transport is ConnectionOrientedTransportBindingElement)
  1921. {
  1922. maxNegoMessageSize = ((ConnectionOrientedTransportBindingElement)transport).MaxBufferSize;
  1923. }
  1924. else if (transport is HttpTransportBindingElement)
  1925. {
  1926. maxNegoMessageSize = ((HttpTransportBindingElement)transport).MaxBufferSize;
  1927. }
  1928. else
  1929. {
  1930. maxNegoMessageSize = TransportDefaults.MaxBufferSize;
  1931. }
  1932. return maxNegoMessageSize;
  1933. }
  1934. public static bool TryCreateKeyFromIntrinsicKeyClause(SecurityKeyIdentifierClause keyIdentifierClause, SecurityTokenResolver resolver, out SecurityKey key)
  1935. {
  1936. key = null;
  1937. if (keyIdentifierClause.CanCreateKey)
  1938. {
  1939. key = keyIdentifierClause.CreateKey();
  1940. return true;
  1941. }
  1942. if (keyIdentifierClause is EncryptedKeyIdentifierClause)
  1943. {
  1944. EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
  1945. // PreSharp Bug: Parameter 'keyClause' to this public method must be validated: A null-dereference can occur here.
  1946. #pragma warning suppress 56506 // keyClause will not be null due to the if condition above.
  1947. for (int i = 0; i < keyClause.EncryptingKeyIdentifier.Count; i++)
  1948. {
  1949. SecurityKey unwrappingSecurityKey = null;
  1950. if (resolver.TryResolveSecurityKey(keyClause.EncryptingKeyIdentifier[i], out unwrappingSecurityKey))
  1951. {
  1952. byte[] wrappedKey = keyClause.GetEncryptedKey();
  1953. string wrappingAlgorithm = keyClause.EncryptionMethod;
  1954. byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
  1955. key = new InMemorySymmetricSecurityKey(unwrappedKey, false);
  1956. return true;
  1957. }
  1958. }
  1959. }
  1960. return false;
  1961. }
  1962. public static WrappedKeySecurityToken CreateTokenFromEncryptedKeyClause(EncryptedKeyIdentifierClause keyClause, SecurityToken unwrappingToken)
  1963. {
  1964. SecurityKeyIdentifier wrappingTokenReference = keyClause.EncryptingKeyIdentifier;
  1965. byte[] wrappedKey = keyClause.GetEncryptedKey();
  1966. SecurityKey unwrappingSecurityKey = unwrappingToken.SecurityKeys[0];
  1967. string wrappingAlgorithm = keyClause.EncryptionMethod;
  1968. byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
  1969. return new WrappedKeySecurityToken(SecurityUtils.GenerateId(), unwrappedKey, wrappingAlgorithm,
  1970. unwrappingToken, wrappingTokenReference, wrappedKey, unwrappingSecurityKey
  1971. );
  1972. }
  1973. public static void ValidateAnonymityConstraint(WindowsIdentity identity, bool allowUnauthenticatedCallers)
  1974. {
  1975. if (!allowUnauthenticatedCallers && identity.User.IsWellKnown(WellKnownSidType.AnonymousSid))
  1976. {
  1977. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(
  1978. new SecurityTokenValidationException(SR.GetString(SR.AnonymousLogonsAreNotAllowed)));
  1979. }
  1980. }
  1981. static bool ComputeSslCipherStrengthRequirementFlag()
  1982. {
  1983. // validate only for XP versions < XP SP3 and windows server versions < Win2K3 SP2
  1984. if ((Environment.OSVersion.Version.Major > WindowsServerMajorNumber)
  1985. || (Environment.OSVersion.Version.Major == WindowsServerMajorNumber && Environment.OSVersion.Version.Minor > WindowsServerMinorNumber))
  1986. {
  1987. return false;
  1988. }
  1989. // version <= Win2K3
  1990. if (Environment.OSVersion.Version.Major == XPMajorNumber && Environment.OSVersion.Version.Minor == XPMinorNumber)
  1991. {
  1992. if ((Environment.OSVersion.ServicePack == string.Empty) || String.Equals(Environment.OSVersion.ServicePack, ServicePack1, StringComparison.OrdinalIgnoreCase) || String.Equals(Environment.OSVersion.ServicePack, ServicePack2, StringComparison.OrdinalIgnoreCase))
  1993. {
  1994. return true;
  1995. }
  1996. else
  1997. {
  1998. // the OS is XP SP3 or higher
  1999. return false;
  2000. }
  2001. }
  2002. else if (Environment.OSVersion.Version.Major == WindowsServerMajorNumber && Environment.OSVersion.Version.Minor == WindowsServerMinorNumber)
  2003. {
  2004. if (Environment.OSVersion.ServicePack == string.Empty || String.Equals(Environment.OSVersion.ServicePack, ServicePack1, StringComparison.OrdinalIgnoreCase))
  2005. {
  2006. return true;
  2007. }
  2008. else
  2009. {
  2010. // the OS is Win2K3 SP2 or higher
  2011. return false;
  2012. }
  2013. }
  2014. else
  2015. {
  2016. // this is <= XP. We should never get here but if we do validate SSL strength
  2017. return true;
  2018. }
  2019. }
  2020. public static bool ShouldValidateSslCipherStrength()
  2021. {
  2022. if (!isSslValidationRequirementDetermined)
  2023. {
  2024. shouldValidateSslCipherStrength = ComputeSslCipherStrengthRequirementFlag();
  2025. Thread.MemoryBarrier();
  2026. isSslValidationRequirementDetermined = true;
  2027. }
  2028. return shouldValidateSslCipherStrength;
  2029. }
  2030. public static void ValidateSslCipherStrength(int keySizeInBits)
  2031. {
  2032. if (ShouldValidateSslCipherStrength() && keySizeInBits < MinimumSslCipherStrength)
  2033. {
  2034. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.SslCipherKeyTooSmall, keySizeInBits, MinimumSslCipherStrength)));
  2035. }
  2036. }
  2037. public static bool TryCreateX509CertificateFromRawData(byte[] rawData, out X509Certificate2 certificate)
  2038. {
  2039. certificate = (rawData == null || rawData.Length == 0) ? null : new X509Certificate2(rawData);
  2040. return certificate != null && certificate.Handle != IntPtr.Zero;
  2041. }
  2042. internal static string GetKeyDerivationAlgorithm(SecureConversationVersion version)
  2043. {
  2044. string derivationAlgorithm = null;
  2045. if (version == SecureConversationVersion.WSSecureConversationFeb2005)
  2046. {
  2047. derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivation;
  2048. }
  2049. else if (version == SecureConversationVersion.WSSecureConversation13)
  2050. {
  2051. derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivationDec2005;
  2052. }
  2053. else
  2054. {
  2055. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  2056. }
  2057. return derivationAlgorithm;
  2058. }
  2059. }
  2060. struct SecurityUniqueId
  2061. {
  2062. static long nextId = 0;
  2063. static string commonPrefix = "uuid-" + Guid.NewGuid().ToString() + "-";
  2064. long id;
  2065. string prefix;
  2066. string val;
  2067. SecurityUniqueId(string prefix, long id)
  2068. {
  2069. this.id = id;
  2070. this.prefix = prefix;
  2071. this.val = null;
  2072. }
  2073. public static SecurityUniqueId Create()
  2074. {
  2075. return SecurityUniqueId.Create(commonPrefix);
  2076. }
  2077. public static SecurityUniqueId Create(string prefix)
  2078. {
  2079. return new SecurityUniqueId(prefix, Interlocked.Increment(ref nextId));
  2080. }
  2081. public string Value
  2082. {
  2083. get
  2084. {
  2085. if (this.val == null)
  2086. this.val = this.prefix + this.id.ToString(CultureInfo.InvariantCulture);
  2087. return this.val;
  2088. }
  2089. }
  2090. }
  2091. static class EmptyReadOnlyCollection<T>
  2092. {
  2093. public static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new List<T>());
  2094. }
  2095. class OperationWithTimeoutAsyncResult : TraceAsyncResult
  2096. {
  2097. static readonly Action<object> scheduledCallback = new Action<object>(OnScheduled);
  2098. TimeoutHelper timeoutHelper;
  2099. OperationWithTimeoutCallback operationWithTimeout;
  2100. public OperationWithTimeoutAsyncResult(OperationWithTimeoutCallback operationWithTimeout, TimeSpan timeout, AsyncCallback callback, object state)
  2101. : base(callback, state)
  2102. {
  2103. this.operationWithTimeout = operationWithTimeout;
  2104. this.timeoutHelper = new TimeoutHelper(timeout);
  2105. ActionItem.Schedule(scheduledCallback, this);
  2106. }
  2107. static void OnScheduled(object state)
  2108. {
  2109. OperationWithTimeoutAsyncResult thisResult = (OperationWithTimeoutAsyncResult)state;
  2110. Exception completionException = null;
  2111. try
  2112. {
  2113. using (thisResult.CallbackActivity == null ? null : ServiceModelActivity.BoundOperation(thisResult.CallbackActivity))
  2114. {
  2115. thisResult.operationWithTimeout(thisResult.timeoutHelper.RemainingTime());
  2116. }
  2117. }
  2118. #pragma warning suppress 56500 // covered by FxCOP
  2119. catch (Exception e)
  2120. {
  2121. if (Fx.IsFatal(e))
  2122. {
  2123. throw;
  2124. }
  2125. completionException = e;
  2126. }
  2127. thisResult.Complete(false, completionException);
  2128. }
  2129. public static void End(IAsyncResult result)
  2130. {
  2131. AsyncResult.End<OperationWithTimeoutAsyncResult>(result);
  2132. }
  2133. }
  2134. }