SecurityBindingElement.cs 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System;
  7. using System.Diagnostics;
  8. using System.Collections.Generic;
  9. using System.Collections.ObjectModel;
  10. using System.Globalization;
  11. using System.IdentityModel.Selectors;
  12. using System.IdentityModel.Tokens;
  13. using System.Net.Security;
  14. using System.Runtime;
  15. using System.Security.Authentication.ExtendedProtection;
  16. using System.ServiceModel;
  17. using System.ServiceModel.Configuration;
  18. using System.ServiceModel.Diagnostics;
  19. using System.ServiceModel.Description;
  20. using System.ServiceModel.Security;
  21. using System.ServiceModel.Security.Tokens;
  22. using System.Text;
  23. using System.Xml;
  24. public abstract class SecurityBindingElement : BindingElement
  25. {
  26. internal const string defaultAlgorithmSuiteString = ConfigurationStrings.Default;
  27. internal static readonly SecurityAlgorithmSuite defaultDefaultAlgorithmSuite = SecurityAlgorithmSuite.Default;
  28. internal const bool defaultIncludeTimestamp = true;
  29. internal const bool defaultAllowInsecureTransport = false;
  30. internal const MessageProtectionOrder defaultMessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;
  31. internal const bool defaultRequireSignatureConfirmation = false;
  32. internal const bool defaultEnableUnsecuredResponse = false;
  33. internal const bool defaultProtectTokens = false;
  34. SecurityAlgorithmSuite defaultAlgorithmSuite;
  35. SupportingTokenParameters endpointSupportingTokenParameters;
  36. SupportingTokenParameters optionalEndpointSupportingTokenParameters;
  37. bool includeTimestamp;
  38. SecurityKeyEntropyMode keyEntropyMode;
  39. Dictionary<string, SupportingTokenParameters> operationSupportingTokenParameters;
  40. Dictionary<string, SupportingTokenParameters> optionalOperationSupportingTokenParameters;
  41. LocalClientSecuritySettings localClientSettings;
  42. LocalServiceSecuritySettings localServiceSettings;
  43. MessageSecurityVersion messageSecurityVersion;
  44. SecurityHeaderLayout securityHeaderLayout;
  45. InternalDuplexBindingElement internalDuplexBindingElement;
  46. long maxReceivedMessageSize = TransportDefaults.MaxReceivedMessageSize;
  47. XmlDictionaryReaderQuotas readerQuotas;
  48. bool doNotEmitTrust = false; // true if user create a basic http standard binding, the custombinding equivalent will not set this flag
  49. bool supportsExtendedProtectionPolicy;
  50. bool allowInsecureTransport;
  51. bool enableUnsecuredResponse;
  52. bool protectTokens = defaultProtectTokens;
  53. internal SecurityBindingElement()
  54. : base()
  55. {
  56. this.messageSecurityVersion = MessageSecurityVersion.Default;
  57. this.keyEntropyMode = AcceleratedTokenProvider.defaultKeyEntropyMode;
  58. this.includeTimestamp = defaultIncludeTimestamp;
  59. this.defaultAlgorithmSuite = defaultDefaultAlgorithmSuite;
  60. this.localClientSettings = new LocalClientSecuritySettings();
  61. this.localServiceSettings = new LocalServiceSecuritySettings();
  62. this.endpointSupportingTokenParameters = new SupportingTokenParameters();
  63. this.optionalEndpointSupportingTokenParameters = new SupportingTokenParameters();
  64. this.operationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>();
  65. this.optionalOperationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>();
  66. this.securityHeaderLayout = SecurityProtocolFactory.defaultSecurityHeaderLayout;
  67. this.allowInsecureTransport = defaultAllowInsecureTransport;
  68. this.enableUnsecuredResponse = defaultEnableUnsecuredResponse;
  69. this.protectTokens = defaultProtectTokens;
  70. }
  71. internal SecurityBindingElement(SecurityBindingElement elementToBeCloned)
  72. : base(elementToBeCloned)
  73. {
  74. if (elementToBeCloned == null)
  75. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elementToBeCloned");
  76. this.defaultAlgorithmSuite = elementToBeCloned.defaultAlgorithmSuite;
  77. this.includeTimestamp = elementToBeCloned.includeTimestamp;
  78. this.keyEntropyMode = elementToBeCloned.keyEntropyMode;
  79. this.messageSecurityVersion = elementToBeCloned.messageSecurityVersion;
  80. this.securityHeaderLayout = elementToBeCloned.securityHeaderLayout;
  81. this.endpointSupportingTokenParameters = (SupportingTokenParameters)elementToBeCloned.endpointSupportingTokenParameters.Clone();
  82. this.optionalEndpointSupportingTokenParameters = (SupportingTokenParameters)elementToBeCloned.optionalEndpointSupportingTokenParameters.Clone();
  83. this.operationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>();
  84. foreach (string key in elementToBeCloned.operationSupportingTokenParameters.Keys)
  85. {
  86. this.operationSupportingTokenParameters[key] = (SupportingTokenParameters)elementToBeCloned.operationSupportingTokenParameters[key].Clone();
  87. }
  88. this.optionalOperationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>();
  89. foreach (string key in elementToBeCloned.optionalOperationSupportingTokenParameters.Keys)
  90. {
  91. this.optionalOperationSupportingTokenParameters[key] = (SupportingTokenParameters)elementToBeCloned.optionalOperationSupportingTokenParameters[key].Clone();
  92. }
  93. this.localClientSettings = (LocalClientSecuritySettings)elementToBeCloned.localClientSettings.Clone();
  94. this.localServiceSettings = (LocalServiceSecuritySettings)elementToBeCloned.localServiceSettings.Clone();
  95. this.internalDuplexBindingElement = elementToBeCloned.internalDuplexBindingElement;
  96. this.maxReceivedMessageSize = elementToBeCloned.maxReceivedMessageSize;
  97. this.readerQuotas = elementToBeCloned.readerQuotas;
  98. this.doNotEmitTrust = elementToBeCloned.doNotEmitTrust;
  99. this.allowInsecureTransport = elementToBeCloned.allowInsecureTransport;
  100. this.enableUnsecuredResponse = elementToBeCloned.enableUnsecuredResponse;
  101. this.supportsExtendedProtectionPolicy = elementToBeCloned.supportsExtendedProtectionPolicy;
  102. this.protectTokens = elementToBeCloned.protectTokens;
  103. }
  104. internal bool SupportsExtendedProtectionPolicy
  105. {
  106. get { return this.supportsExtendedProtectionPolicy; }
  107. set { this.supportsExtendedProtectionPolicy = value; }
  108. }
  109. public SupportingTokenParameters EndpointSupportingTokenParameters
  110. {
  111. get
  112. {
  113. return this.endpointSupportingTokenParameters;
  114. }
  115. }
  116. public SupportingTokenParameters OptionalEndpointSupportingTokenParameters
  117. {
  118. get
  119. {
  120. return this.optionalEndpointSupportingTokenParameters;
  121. }
  122. }
  123. public IDictionary<string, SupportingTokenParameters> OperationSupportingTokenParameters
  124. {
  125. get
  126. {
  127. return this.operationSupportingTokenParameters;
  128. }
  129. }
  130. public IDictionary<string, SupportingTokenParameters> OptionalOperationSupportingTokenParameters
  131. {
  132. get
  133. {
  134. return this.optionalOperationSupportingTokenParameters;
  135. }
  136. }
  137. public SecurityHeaderLayout SecurityHeaderLayout
  138. {
  139. get
  140. {
  141. return this.securityHeaderLayout;
  142. }
  143. set
  144. {
  145. if (!SecurityHeaderLayoutHelper.IsDefined(value))
  146. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
  147. this.securityHeaderLayout = value;
  148. }
  149. }
  150. public MessageSecurityVersion MessageSecurityVersion
  151. {
  152. get
  153. {
  154. return this.messageSecurityVersion;
  155. }
  156. set
  157. {
  158. if (value == null)
  159. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
  160. this.messageSecurityVersion = value;
  161. }
  162. }
  163. public bool EnableUnsecuredResponse
  164. {
  165. get
  166. {
  167. return this.enableUnsecuredResponse;
  168. }
  169. set
  170. {
  171. this.enableUnsecuredResponse = value;
  172. }
  173. }
  174. public bool IncludeTimestamp
  175. {
  176. get
  177. {
  178. return this.includeTimestamp;
  179. }
  180. set
  181. {
  182. this.includeTimestamp = value;
  183. }
  184. }
  185. public bool AllowInsecureTransport
  186. {
  187. get
  188. {
  189. return this.allowInsecureTransport;
  190. }
  191. set
  192. {
  193. this.allowInsecureTransport = value;
  194. }
  195. }
  196. public SecurityAlgorithmSuite DefaultAlgorithmSuite
  197. {
  198. get
  199. {
  200. return this.defaultAlgorithmSuite;
  201. }
  202. set
  203. {
  204. if (value == null)
  205. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
  206. this.defaultAlgorithmSuite = value;
  207. }
  208. }
  209. public bool ProtectTokens
  210. {
  211. get
  212. {
  213. return this.protectTokens;
  214. }
  215. set
  216. {
  217. this.protectTokens = value;
  218. }
  219. }
  220. public LocalClientSecuritySettings LocalClientSettings
  221. {
  222. get
  223. {
  224. return this.localClientSettings;
  225. }
  226. }
  227. public LocalServiceSecuritySettings LocalServiceSettings
  228. {
  229. get
  230. {
  231. return this.localServiceSettings;
  232. }
  233. }
  234. public SecurityKeyEntropyMode KeyEntropyMode
  235. {
  236. get
  237. {
  238. return this.keyEntropyMode;
  239. }
  240. set
  241. {
  242. if (!SecurityKeyEntropyModeHelper.IsDefined(value))
  243. {
  244. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
  245. }
  246. this.keyEntropyMode = value;
  247. }
  248. }
  249. internal virtual bool SessionMode
  250. {
  251. get { return false; }
  252. }
  253. internal virtual bool SupportsDuplex
  254. {
  255. get { return false; }
  256. }
  257. internal virtual bool SupportsRequestReply
  258. {
  259. get { return false; }
  260. }
  261. internal long MaxReceivedMessageSize
  262. {
  263. get { return this.maxReceivedMessageSize; }
  264. set { this.maxReceivedMessageSize = value; }
  265. }
  266. internal bool DoNotEmitTrust
  267. {
  268. get { return this.doNotEmitTrust; }
  269. set { this.doNotEmitTrust = value; }
  270. }
  271. internal XmlDictionaryReaderQuotas ReaderQuotas
  272. {
  273. get { return this.readerQuotas; }
  274. set { this.readerQuotas = value; }
  275. }
  276. void GetSupportingTokensCapabilities(ICollection<SecurityTokenParameters> parameters, out bool supportsClientAuth, out bool supportsWindowsIdentity)
  277. {
  278. supportsClientAuth = false;
  279. supportsWindowsIdentity = false;
  280. foreach (SecurityTokenParameters p in parameters)
  281. {
  282. if (p.SupportsClientAuthentication)
  283. supportsClientAuth = true;
  284. if (p.SupportsClientWindowsIdentity)
  285. supportsWindowsIdentity = true;
  286. }
  287. }
  288. void GetSupportingTokensCapabilities(SupportingTokenParameters requirements, out bool supportsClientAuth, out bool supportsWindowsIdentity)
  289. {
  290. supportsClientAuth = false;
  291. supportsWindowsIdentity = false;
  292. bool tmpSupportsClientAuth;
  293. bool tmpSupportsWindowsIdentity;
  294. this.GetSupportingTokensCapabilities(requirements.Endorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity);
  295. supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth;
  296. supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity;
  297. this.GetSupportingTokensCapabilities(requirements.SignedEndorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity);
  298. supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth;
  299. supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity;
  300. this.GetSupportingTokensCapabilities(requirements.SignedEncrypted, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity);
  301. supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth;
  302. supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity;
  303. }
  304. internal void GetSupportingTokensCapabilities(out bool supportsClientAuth, out bool supportsWindowsIdentity)
  305. {
  306. this.GetSupportingTokensCapabilities(this.EndpointSupportingTokenParameters, out supportsClientAuth, out supportsWindowsIdentity);
  307. }
  308. // SecureConversation needs a demuxer below security to 1) demux between the security sessions and 2) demux the SCT issue and renewal messages
  309. // to the authenticator
  310. internal void AddDemuxerForSecureConversation(ChannelBuilder builder, BindingContext secureConversationBindingContext)
  311. {
  312. // add a demuxer element right below security unless there's a demuxer already present below and the only
  313. // binding elements between security and the demuxer are "ancillary" binding elements like message encoding element and
  314. // stream-security upgrade element. We could always add the channel demuxer below security but not doing so in the ancillary
  315. // binding elements case improves perf
  316. int numChannelDemuxersBelowSecurity = 0;
  317. bool doesBindingHaveShapeChangingElements = false;
  318. for (int i = 0; i < builder.Binding.Elements.Count; ++i)
  319. {
  320. if ((builder.Binding.Elements[i] is MessageEncodingBindingElement) || (builder.Binding.Elements[i] is StreamUpgradeBindingElement))
  321. {
  322. continue;
  323. }
  324. if (builder.Binding.Elements[i] is ChannelDemuxerBindingElement)
  325. {
  326. ++numChannelDemuxersBelowSecurity;
  327. }
  328. else if (builder.Binding.Elements[i] is TransportBindingElement)
  329. {
  330. break;
  331. }
  332. else
  333. {
  334. doesBindingHaveShapeChangingElements = true;
  335. }
  336. }
  337. if (numChannelDemuxersBelowSecurity == 1 && !doesBindingHaveShapeChangingElements)
  338. {
  339. return;
  340. }
  341. ChannelDemuxerBindingElement demuxer = new ChannelDemuxerBindingElement(false);
  342. demuxer.MaxPendingSessions = this.LocalServiceSettings.MaxPendingSessions;
  343. demuxer.PeekTimeout = this.LocalServiceSettings.NegotiationTimeout;
  344. builder.Binding.Elements.Insert(0, demuxer);
  345. secureConversationBindingContext.RemainingBindingElements.Insert(0, demuxer);
  346. }
  347. internal void ApplyPropertiesOnDemuxer(ChannelBuilder builder, BindingContext context)
  348. {
  349. Collection<ChannelDemuxerBindingElement> demuxerElements = builder.Binding.Elements.FindAll<ChannelDemuxerBindingElement>();
  350. foreach (ChannelDemuxerBindingElement element in demuxerElements)
  351. {
  352. if (element != null)
  353. {
  354. element.MaxPendingSessions = this.LocalServiceSettings.MaxPendingSessions;
  355. element.PeekTimeout = this.LocalServiceSettings.NegotiationTimeout;
  356. }
  357. }
  358. }
  359. static BindingContext CreateIssuerBindingContextForNegotiation(BindingContext issuerBindingContext)
  360. {
  361. TransportBindingElement transport = issuerBindingContext.RemainingBindingElements.Find<TransportBindingElement>();
  362. if (transport == null)
  363. {
  364. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TransportBindingElementNotFound)));
  365. }
  366. ChannelDemuxerBindingElement demuxer = null;
  367. // pick the demuxer above transport (i.e. the last demuxer in the array)
  368. for (int i = 0; i < issuerBindingContext.RemainingBindingElements.Count; ++i)
  369. {
  370. if (issuerBindingContext.RemainingBindingElements[i] is ChannelDemuxerBindingElement)
  371. {
  372. demuxer = (ChannelDemuxerBindingElement) issuerBindingContext.RemainingBindingElements[i];
  373. }
  374. }
  375. if (demuxer == null)
  376. {
  377. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ChannelDemuxerBindingElementNotFound)));
  378. }
  379. BindingElementCollection negotiationBindingElements = new BindingElementCollection();
  380. negotiationBindingElements.Add(demuxer.Clone());
  381. negotiationBindingElements.Add(transport.Clone());
  382. CustomBinding binding = new CustomBinding(negotiationBindingElements);
  383. binding.OpenTimeout = issuerBindingContext.Binding.OpenTimeout;
  384. binding.CloseTimeout = issuerBindingContext.Binding.CloseTimeout;
  385. binding.SendTimeout = issuerBindingContext.Binding.SendTimeout;
  386. binding.ReceiveTimeout = issuerBindingContext.Binding.ReceiveTimeout;
  387. if (issuerBindingContext.ListenUriBaseAddress != null)
  388. {
  389. return new BindingContext(binding, new BindingParameterCollection(issuerBindingContext.BindingParameters), issuerBindingContext.ListenUriBaseAddress,
  390. issuerBindingContext.ListenUriRelativeAddress, issuerBindingContext.ListenUriMode);
  391. }
  392. else
  393. {
  394. return new BindingContext(binding, new BindingParameterCollection(issuerBindingContext.BindingParameters));
  395. }
  396. }
  397. protected static void SetIssuerBindingContextIfRequired(SecurityTokenParameters parameters, BindingContext issuerBindingContext)
  398. {
  399. if (parameters is SslSecurityTokenParameters)
  400. {
  401. ((SslSecurityTokenParameters)parameters).IssuerBindingContext = CreateIssuerBindingContextForNegotiation(issuerBindingContext);
  402. }
  403. else if (parameters is SspiSecurityTokenParameters)
  404. {
  405. ((SspiSecurityTokenParameters)parameters).IssuerBindingContext = CreateIssuerBindingContextForNegotiation(issuerBindingContext);
  406. }
  407. }
  408. static void SetIssuerBindingContextIfRequired(SupportingTokenParameters supportingParameters, BindingContext issuerBindingContext)
  409. {
  410. for (int i = 0; i < supportingParameters.Endorsing.Count; ++i)
  411. {
  412. SetIssuerBindingContextIfRequired(supportingParameters.Endorsing[i], issuerBindingContext);
  413. }
  414. for (int i = 0; i < supportingParameters.SignedEndorsing.Count; ++i)
  415. {
  416. SetIssuerBindingContextIfRequired(supportingParameters.SignedEndorsing[i], issuerBindingContext);
  417. }
  418. for (int i = 0; i < supportingParameters.Signed.Count; ++i)
  419. {
  420. SetIssuerBindingContextIfRequired(supportingParameters.Signed[i], issuerBindingContext);
  421. }
  422. for (int i = 0; i < supportingParameters.SignedEncrypted.Count; ++i)
  423. {
  424. SetIssuerBindingContextIfRequired(supportingParameters.SignedEncrypted[i], issuerBindingContext);
  425. }
  426. }
  427. void SetIssuerBindingContextIfRequired(BindingContext issuerBindingContext)
  428. {
  429. SetIssuerBindingContextIfRequired(this.EndpointSupportingTokenParameters, issuerBindingContext);
  430. SetIssuerBindingContextIfRequired(this.OptionalEndpointSupportingTokenParameters, issuerBindingContext);
  431. foreach (SupportingTokenParameters parameters in this.OperationSupportingTokenParameters.Values)
  432. {
  433. SetIssuerBindingContextIfRequired(parameters, issuerBindingContext);
  434. }
  435. foreach (SupportingTokenParameters parameters in this.OptionalOperationSupportingTokenParameters.Values)
  436. {
  437. SetIssuerBindingContextIfRequired(parameters, issuerBindingContext);
  438. }
  439. }
  440. internal bool RequiresChannelDemuxer(SecurityTokenParameters parameters)
  441. {
  442. return ((parameters is SecureConversationSecurityTokenParameters)
  443. || (parameters is SslSecurityTokenParameters)
  444. || (parameters is SspiSecurityTokenParameters));
  445. }
  446. internal virtual bool RequiresChannelDemuxer()
  447. {
  448. foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.Endorsing)
  449. {
  450. if (RequiresChannelDemuxer(parameters))
  451. {
  452. return true;
  453. }
  454. }
  455. foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.SignedEndorsing)
  456. {
  457. if (RequiresChannelDemuxer(parameters))
  458. {
  459. return true;
  460. }
  461. }
  462. foreach (SecurityTokenParameters parameters in OptionalEndpointSupportingTokenParameters.Endorsing)
  463. {
  464. if (RequiresChannelDemuxer(parameters))
  465. {
  466. return true;
  467. }
  468. }
  469. foreach (SecurityTokenParameters parameters in OptionalEndpointSupportingTokenParameters.SignedEndorsing)
  470. {
  471. if (RequiresChannelDemuxer(parameters))
  472. {
  473. return true;
  474. }
  475. }
  476. foreach (SupportingTokenParameters supportingParameters in OperationSupportingTokenParameters.Values)
  477. {
  478. foreach (SecurityTokenParameters parameters in supportingParameters.Endorsing)
  479. {
  480. if (RequiresChannelDemuxer(parameters))
  481. {
  482. return true;
  483. }
  484. }
  485. foreach (SecurityTokenParameters parameters in supportingParameters.SignedEndorsing)
  486. {
  487. if (RequiresChannelDemuxer(parameters))
  488. {
  489. return true;
  490. }
  491. }
  492. }
  493. foreach (SupportingTokenParameters supportingParameters in OptionalOperationSupportingTokenParameters.Values)
  494. {
  495. foreach (SecurityTokenParameters parameters in supportingParameters.Endorsing)
  496. {
  497. if (RequiresChannelDemuxer(parameters))
  498. {
  499. return true;
  500. }
  501. }
  502. foreach (SecurityTokenParameters parameters in supportingParameters.SignedEndorsing)
  503. {
  504. if (RequiresChannelDemuxer(parameters))
  505. {
  506. return true;
  507. }
  508. }
  509. }
  510. return false;
  511. }
  512. internal bool IsUnderlyingListenerDuplex<TChannel>(BindingContext context)
  513. {
  514. return ((typeof(TChannel) == typeof(IDuplexSessionChannel)) && context.CanBuildInnerChannelListener<IDuplexChannel>()
  515. && !context.CanBuildInnerChannelListener<IDuplexSessionChannel>());
  516. }
  517. void SetPrivacyNoticeUriIfRequired(SecurityProtocolFactory factory, Binding binding)
  518. {
  519. PrivacyNoticeBindingElement privacyElement = binding.CreateBindingElements().Find<PrivacyNoticeBindingElement>();
  520. if (privacyElement != null)
  521. {
  522. factory.PrivacyNoticeUri = privacyElement.Url;
  523. factory.PrivacyNoticeVersion = privacyElement.Version;
  524. }
  525. }
  526. internal void ConfigureProtocolFactory(SecurityProtocolFactory factory, SecurityCredentialsManager credentialsManager, bool isForService, BindingContext issuerBindingContext, Binding binding)
  527. {
  528. if (factory == null)
  529. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("factory"));
  530. if (credentialsManager == null)
  531. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("credentialsManager"));
  532. factory.AddTimestamp = this.IncludeTimestamp;
  533. factory.IncomingAlgorithmSuite = this.DefaultAlgorithmSuite;
  534. factory.OutgoingAlgorithmSuite = this.DefaultAlgorithmSuite;
  535. factory.SecurityHeaderLayout = this.SecurityHeaderLayout;
  536. if (!isForService)
  537. {
  538. factory.TimestampValidityDuration = this.LocalClientSettings.TimestampValidityDuration;
  539. factory.DetectReplays = this.LocalClientSettings.DetectReplays;
  540. factory.MaxCachedNonces = this.LocalClientSettings.ReplayCacheSize;
  541. factory.MaxClockSkew = this.LocalClientSettings.MaxClockSkew;
  542. factory.ReplayWindow = this.LocalClientSettings.ReplayWindow;
  543. if (this.LocalClientSettings.DetectReplays)
  544. {
  545. factory.NonceCache = this.LocalClientSettings.NonceCache;
  546. }
  547. }
  548. else
  549. {
  550. factory.TimestampValidityDuration = this.LocalServiceSettings.TimestampValidityDuration;
  551. factory.DetectReplays = this.LocalServiceSettings.DetectReplays;
  552. factory.MaxCachedNonces = this.LocalServiceSettings.ReplayCacheSize;
  553. factory.MaxClockSkew = this.LocalServiceSettings.MaxClockSkew;
  554. factory.ReplayWindow = this.LocalServiceSettings.ReplayWindow;
  555. if (this.LocalServiceSettings.DetectReplays)
  556. {
  557. factory.NonceCache = this.LocalServiceSettings.NonceCache;
  558. }
  559. }
  560. factory.SecurityBindingElement = (SecurityBindingElement) this.Clone();
  561. factory.SecurityBindingElement.SetIssuerBindingContextIfRequired(issuerBindingContext);
  562. factory.SecurityTokenManager = credentialsManager.CreateSecurityTokenManager();
  563. SecurityTokenSerializer tokenSerializer = factory.SecurityTokenManager.CreateSecurityTokenSerializer(this.messageSecurityVersion.SecurityTokenVersion);
  564. factory.StandardsManager = new SecurityStandardsManager(this.messageSecurityVersion, tokenSerializer);
  565. if (!isForService)
  566. {
  567. SetPrivacyNoticeUriIfRequired(factory, binding);
  568. }
  569. }
  570. internal abstract SecurityProtocolFactory CreateSecurityProtocolFactory<TChannel>(BindingContext context, SecurityCredentialsManager credentialsManager,
  571. bool isForService, BindingContext issuanceBindingContext);
  572. public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
  573. {
  574. if (context == null)
  575. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
  576. if (!this.CanBuildChannelFactory<TChannel>(context))
  577. {
  578. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)), "TChannel"));
  579. }
  580. this.readerQuotas = context.GetInnerProperty<XmlDictionaryReaderQuotas>();
  581. if (readerQuotas == null)
  582. {
  583. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.EncodingBindingElementDoesNotHandleReaderQuotas)));
  584. }
  585. TransportBindingElement transportBindingElement = null;
  586. if (context.RemainingBindingElements != null)
  587. transportBindingElement = context.RemainingBindingElements.Find<TransportBindingElement>();
  588. if (transportBindingElement != null)
  589. this.maxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize;
  590. IChannelFactory<TChannel> result = this.BuildChannelFactoryCore<TChannel>(context);
  591. // attach the ExtendedProtectionPolicy to the securityProtcolFactory so it will be
  592. // available when building the channel.
  593. if (transportBindingElement != null)
  594. {
  595. SecurityChannelFactory<TChannel> scf = result as SecurityChannelFactory<TChannel>;
  596. if (scf != null && scf.SecurityProtocolFactory != null)
  597. {
  598. scf.SecurityProtocolFactory.ExtendedProtectionPolicy = transportBindingElement.GetProperty<ExtendedProtectionPolicy>(context);
  599. }
  600. }
  601. return result;
  602. }
  603. protected abstract IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(BindingContext context);
  604. public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
  605. {
  606. if (context == null)
  607. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
  608. InternalDuplexBindingElement.AddDuplexFactorySupport(context, ref this.internalDuplexBindingElement);
  609. if (this.SessionMode)
  610. {
  611. return this.CanBuildSessionChannelFactory<TChannel>(context);
  612. }
  613. if (!context.CanBuildInnerChannelFactory<TChannel>())
  614. {
  615. return false;
  616. }
  617. return typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IOutputSessionChannel) ||
  618. (this.SupportsDuplex && (typeof(TChannel) == typeof(IDuplexChannel) || typeof(TChannel) == typeof(IDuplexSessionChannel))) ||
  619. (this.SupportsRequestReply && (typeof(TChannel) == typeof(IRequestChannel) || typeof(TChannel) == typeof(IRequestSessionChannel)));
  620. }
  621. bool CanBuildSessionChannelFactory<TChannel>(BindingContext context)
  622. {
  623. if (!(context.CanBuildInnerChannelFactory<IRequestChannel>()
  624. || context.CanBuildInnerChannelFactory<IRequestSessionChannel>()
  625. || context.CanBuildInnerChannelFactory<IDuplexChannel>()
  626. || context.CanBuildInnerChannelFactory<IDuplexSessionChannel>()))
  627. {
  628. return false;
  629. }
  630. if (typeof(TChannel) == typeof(IRequestSessionChannel))
  631. {
  632. return (context.CanBuildInnerChannelFactory<IRequestChannel>() || context.CanBuildInnerChannelFactory<IRequestSessionChannel>());
  633. }
  634. else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
  635. {
  636. return (context.CanBuildInnerChannelFactory<IDuplexChannel>() || context.CanBuildInnerChannelFactory<IDuplexSessionChannel>());
  637. }
  638. else
  639. {
  640. return false;
  641. }
  642. }
  643. public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
  644. {
  645. if (context == null)
  646. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
  647. if (!this.CanBuildChannelListener<TChannel>(context))
  648. {
  649. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)), "TChannel"));
  650. }
  651. this.readerQuotas = context.GetInnerProperty<XmlDictionaryReaderQuotas>();
  652. if (readerQuotas == null)
  653. {
  654. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.EncodingBindingElementDoesNotHandleReaderQuotas)));
  655. }
  656. TransportBindingElement transportBindingElement = null;
  657. if (context.RemainingBindingElements != null)
  658. transportBindingElement = context.RemainingBindingElements.Find<TransportBindingElement>();
  659. if (transportBindingElement != null)
  660. this.maxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize;
  661. return this.BuildChannelListenerCore<TChannel>(context);
  662. }
  663. protected abstract IChannelListener<TChannel> BuildChannelListenerCore<TChannel>(BindingContext context)
  664. where TChannel : class, IChannel;
  665. public override bool CanBuildChannelListener<TChannel>(BindingContext context)
  666. {
  667. if (context == null)
  668. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
  669. InternalDuplexBindingElement.AddDuplexListenerSupport(context, ref this.internalDuplexBindingElement);
  670. if (this.SessionMode)
  671. {
  672. return this.CanBuildSessionChannelListener<TChannel>(context);
  673. }
  674. if (!context.CanBuildInnerChannelListener<TChannel>())
  675. {
  676. return false;
  677. }
  678. return typeof(TChannel) == typeof(IInputChannel) || typeof(TChannel) == typeof(IInputSessionChannel) ||
  679. (this.SupportsDuplex && (typeof(TChannel) == typeof(IDuplexChannel) || typeof(TChannel) == typeof(IDuplexSessionChannel))) ||
  680. (this.SupportsRequestReply && (typeof(TChannel) == typeof(IReplyChannel) || typeof(TChannel) == typeof(IReplySessionChannel)));
  681. }
  682. bool CanBuildSessionChannelListener<TChannel>(BindingContext context)
  683. where TChannel : class, IChannel
  684. {
  685. if (!(context.CanBuildInnerChannelListener<IReplyChannel>()
  686. || context.CanBuildInnerChannelListener<IReplySessionChannel>()
  687. || context.CanBuildInnerChannelListener<IDuplexChannel>()
  688. || context.CanBuildInnerChannelListener<IDuplexSessionChannel>()))
  689. {
  690. return false;
  691. }
  692. if (typeof(TChannel) == typeof(IReplySessionChannel))
  693. {
  694. return (context.CanBuildInnerChannelListener<IReplyChannel>() || context.CanBuildInnerChannelListener<IReplySessionChannel>());
  695. }
  696. else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
  697. {
  698. return (context.CanBuildInnerChannelListener<IDuplexChannel>() || context.CanBuildInnerChannelListener<IDuplexSessionChannel>());
  699. }
  700. else
  701. {
  702. return false;
  703. }
  704. }
  705. public virtual void SetKeyDerivation(bool requireDerivedKeys)
  706. {
  707. this.EndpointSupportingTokenParameters.SetKeyDerivation(requireDerivedKeys);
  708. this.OptionalEndpointSupportingTokenParameters.SetKeyDerivation(requireDerivedKeys);
  709. foreach (SupportingTokenParameters t in this.OperationSupportingTokenParameters.Values)
  710. t.SetKeyDerivation(requireDerivedKeys);
  711. foreach (SupportingTokenParameters t in this.OptionalOperationSupportingTokenParameters.Values)
  712. {
  713. t.SetKeyDerivation(requireDerivedKeys);
  714. }
  715. }
  716. internal virtual bool IsSetKeyDerivation(bool requireDerivedKeys)
  717. {
  718. if (!this.EndpointSupportingTokenParameters.IsSetKeyDerivation(requireDerivedKeys))
  719. return false;
  720. if (!this.OptionalEndpointSupportingTokenParameters.IsSetKeyDerivation(requireDerivedKeys))
  721. return false;
  722. foreach (SupportingTokenParameters t in this.OperationSupportingTokenParameters.Values)
  723. {
  724. if (!t.IsSetKeyDerivation(requireDerivedKeys))
  725. return false;
  726. }
  727. foreach (SupportingTokenParameters t in this.OptionalOperationSupportingTokenParameters.Values)
  728. {
  729. if (!t.IsSetKeyDerivation(requireDerivedKeys))
  730. return false;
  731. }
  732. return true;
  733. }
  734. internal ChannelProtectionRequirements GetProtectionRequirements(AddressingVersion addressing, ProtectionLevel defaultProtectionLevel)
  735. {
  736. if (addressing == null)
  737. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressing");
  738. ChannelProtectionRequirements result = new ChannelProtectionRequirements();
  739. ProtectionLevel supportedRequestProtectionLevel = this.GetIndividualProperty<ISecurityCapabilities>().SupportedRequestProtectionLevel;
  740. ProtectionLevel supportedResponseProtectionLevel = this.GetIndividualProperty<ISecurityCapabilities>().SupportedResponseProtectionLevel;
  741. bool canSupportMoreThanTheDefault =
  742. (ProtectionLevelHelper.IsStrongerOrEqual(supportedRequestProtectionLevel, defaultProtectionLevel)
  743. && ProtectionLevelHelper.IsStrongerOrEqual(supportedResponseProtectionLevel, defaultProtectionLevel));
  744. if (canSupportMoreThanTheDefault)
  745. {
  746. MessagePartSpecification signedParts = new MessagePartSpecification();
  747. MessagePartSpecification encryptedParts = new MessagePartSpecification();
  748. if (defaultProtectionLevel != ProtectionLevel.None)
  749. {
  750. signedParts.IsBodyIncluded = true;
  751. if (defaultProtectionLevel == ProtectionLevel.EncryptAndSign)
  752. {
  753. encryptedParts.IsBodyIncluded = true;
  754. }
  755. }
  756. signedParts.MakeReadOnly();
  757. encryptedParts.MakeReadOnly();
  758. if (addressing.FaultAction != null)
  759. {
  760. // Addressing faults
  761. result.IncomingSignatureParts.AddParts(signedParts, addressing.FaultAction);
  762. result.OutgoingSignatureParts.AddParts(signedParts, addressing.FaultAction);
  763. result.IncomingEncryptionParts.AddParts(encryptedParts, addressing.FaultAction);
  764. result.OutgoingEncryptionParts.AddParts(encryptedParts, addressing.FaultAction);
  765. }
  766. if (addressing.DefaultFaultAction != null)
  767. {
  768. // Faults that do not specify a particular action
  769. result.IncomingSignatureParts.AddParts(signedParts, addressing.DefaultFaultAction);
  770. result.OutgoingSignatureParts.AddParts(signedParts, addressing.DefaultFaultAction);
  771. result.IncomingEncryptionParts.AddParts(encryptedParts, addressing.DefaultFaultAction);
  772. result.OutgoingEncryptionParts.AddParts(encryptedParts, addressing.DefaultFaultAction);
  773. }
  774. // Infrastructure faults
  775. result.IncomingSignatureParts.AddParts(signedParts, FaultCodeConstants.Actions.NetDispatcher);
  776. result.OutgoingSignatureParts.AddParts(signedParts, FaultCodeConstants.Actions.NetDispatcher);
  777. result.IncomingEncryptionParts.AddParts(encryptedParts, FaultCodeConstants.Actions.NetDispatcher);
  778. result.OutgoingEncryptionParts.AddParts(encryptedParts, FaultCodeConstants.Actions.NetDispatcher);
  779. }
  780. return result;
  781. }
  782. public override T GetProperty<T>(BindingContext context)
  783. {
  784. if (context == null)
  785. {
  786. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
  787. }
  788. if (typeof(T) == typeof(ISecurityCapabilities))
  789. {
  790. return (T)(object)GetSecurityCapabilities(context);
  791. }
  792. else if (typeof(T) == typeof(IdentityVerifier))
  793. {
  794. return (T)(object)this.localClientSettings.IdentityVerifier;
  795. }
  796. else
  797. {
  798. return context.GetInnerProperty<T>();
  799. }
  800. }
  801. internal abstract ISecurityCapabilities GetIndividualISecurityCapabilities();
  802. ISecurityCapabilities GetSecurityCapabilities(BindingContext context)
  803. {
  804. ISecurityCapabilities thisSecurityCapability = this.GetIndividualISecurityCapabilities();
  805. ISecurityCapabilities lowerSecurityCapability = context.GetInnerProperty<ISecurityCapabilities>();
  806. if (lowerSecurityCapability == null)
  807. {
  808. return thisSecurityCapability;
  809. }
  810. else
  811. {
  812. bool supportsClientAuth = thisSecurityCapability.SupportsClientAuthentication;
  813. bool supportsClientWindowsIdentity = thisSecurityCapability.SupportsClientWindowsIdentity;
  814. bool supportsServerAuth = thisSecurityCapability.SupportsServerAuthentication || lowerSecurityCapability.SupportsServerAuthentication;
  815. ProtectionLevel requestProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedRequestProtectionLevel, lowerSecurityCapability.SupportedRequestProtectionLevel);
  816. ProtectionLevel responseProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedResponseProtectionLevel, lowerSecurityCapability.SupportedResponseProtectionLevel);
  817. return new SecurityCapabilities(supportsClientAuth, supportsServerAuth, supportsClientWindowsIdentity, requestProtectionLevel, responseProtectionLevel);
  818. }
  819. }
  820. // If any changes are made to this method, please make sure that they are
  821. // reflected in the corresponding IsMutualCertificateBinding() method.
  822. static public SecurityBindingElement CreateMutualCertificateBindingElement()
  823. {
  824. return CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11);
  825. }
  826. // this method reverses CreateMutualCertificateBindingElement() logic
  827. internal static bool IsMutualCertificateBinding(SecurityBindingElement sbe)
  828. {
  829. return IsMutualCertificateBinding(sbe, false);
  830. }
  831. static public AsymmetricSecurityBindingElement CreateCertificateSignatureBindingElement()
  832. {
  833. AsymmetricSecurityBindingElement result;
  834. result = new AsymmetricSecurityBindingElement(
  835. new X509SecurityTokenParameters( // recipient
  836. X509KeyIdentifierClauseType.Any,
  837. SecurityTokenInclusionMode.Never, false),
  838. new X509SecurityTokenParameters( // initiator
  839. X509KeyIdentifierClauseType.Any,
  840. SecurityTokenInclusionMode.AlwaysToRecipient, false));
  841. // this is a one way binding so the client cannot detect replays
  842. result.IsCertificateSignatureBinding = true;
  843. result.LocalClientSettings.DetectReplays = false;
  844. result.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
  845. return result;
  846. }
  847. // If any changes are made to this method, please make sure that they are
  848. // reflected in the corresponding IsMutualCertificateBinding() method.
  849. static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version)
  850. {
  851. return CreateMutualCertificateBindingElement(version, false);
  852. }
  853. // If any changes are made to this method, please make sure that they are
  854. // reflected in the corresponding IsMutualCertificateBinding() method.
  855. static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version, bool allowSerializedSigningTokenOnReply)
  856. {
  857. if (version == null)
  858. {
  859. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
  860. }
  861. SecurityBindingElement result;
  862. if (version.SecurityVersion == SecurityVersion.WSSecurity10)
  863. {
  864. result = new AsymmetricSecurityBindingElement(
  865. new X509SecurityTokenParameters( // recipient
  866. X509KeyIdentifierClauseType.Any,
  867. SecurityTokenInclusionMode.Never,
  868. false),
  869. new X509SecurityTokenParameters( // initiator
  870. X509KeyIdentifierClauseType.Any,
  871. SecurityTokenInclusionMode.AlwaysToRecipient, false),
  872. allowSerializedSigningTokenOnReply);
  873. }
  874. else
  875. {
  876. result = new SymmetricSecurityBindingElement(
  877. new X509SecurityTokenParameters( // protection
  878. X509KeyIdentifierClauseType.Thumbprint,
  879. SecurityTokenInclusionMode.Never));
  880. result.EndpointSupportingTokenParameters.Endorsing.Add(
  881. new X509SecurityTokenParameters(
  882. X509KeyIdentifierClauseType.Thumbprint,
  883. SecurityTokenInclusionMode.AlwaysToRecipient,
  884. false));
  885. ((SymmetricSecurityBindingElement)result).RequireSignatureConfirmation = true;
  886. }
  887. result.MessageSecurityVersion = version;
  888. return result;
  889. }
  890. // this method reverses CreateMutualCertificateDuplexBindingElement() logic
  891. internal static bool IsMutualCertificateDuplexBinding(SecurityBindingElement sbe)
  892. {
  893. // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
  894. AsymmetricSecurityBindingElement asbe = sbe as AsymmetricSecurityBindingElement;
  895. if (asbe != null)
  896. {
  897. X509SecurityTokenParameters recipient = asbe.RecipientTokenParameters as X509SecurityTokenParameters;
  898. if (recipient == null || (recipient.X509ReferenceStyle != X509KeyIdentifierClauseType.Any && recipient.X509ReferenceStyle != X509KeyIdentifierClauseType.Thumbprint) || recipient.InclusionMode != SecurityTokenInclusionMode.AlwaysToInitiator)
  899. return false;
  900. X509SecurityTokenParameters initiator = asbe.InitiatorTokenParameters as X509SecurityTokenParameters;
  901. if (initiator == null || (initiator.X509ReferenceStyle != X509KeyIdentifierClauseType.Any && initiator.X509ReferenceStyle != X509KeyIdentifierClauseType.Thumbprint) || initiator.InclusionMode != SecurityTokenInclusionMode.AlwaysToRecipient)
  902. return false;
  903. if (!sbe.EndpointSupportingTokenParameters.IsEmpty())
  904. return false;
  905. return true;
  906. }
  907. else
  908. {
  909. return false;
  910. }
  911. }
  912. // this method reverses CreateMutualCertificateBindingElement() logic
  913. internal static bool IsMutualCertificateBinding(SecurityBindingElement sbe, bool allowSerializedSigningTokenOnReply)
  914. {
  915. // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
  916. AsymmetricSecurityBindingElement asbe = sbe as AsymmetricSecurityBindingElement;
  917. if (asbe != null)
  918. {
  919. X509SecurityTokenParameters recipient = asbe.RecipientTokenParameters as X509SecurityTokenParameters;
  920. if (recipient == null || recipient.X509ReferenceStyle != X509KeyIdentifierClauseType.Any || recipient.InclusionMode != SecurityTokenInclusionMode.Never)
  921. return false;
  922. X509SecurityTokenParameters initiator = asbe.InitiatorTokenParameters as X509SecurityTokenParameters;
  923. if (initiator == null || initiator.X509ReferenceStyle != X509KeyIdentifierClauseType.Any || initiator.InclusionMode != SecurityTokenInclusionMode.AlwaysToRecipient)
  924. return false;
  925. if (!sbe.EndpointSupportingTokenParameters.IsEmpty())
  926. return false;
  927. }
  928. else
  929. {
  930. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  931. if (ssbe == null)
  932. return false;
  933. X509SecurityTokenParameters x509Parameters = ssbe.ProtectionTokenParameters as X509SecurityTokenParameters;
  934. if (x509Parameters == null || x509Parameters.X509ReferenceStyle != X509KeyIdentifierClauseType.Thumbprint || x509Parameters.InclusionMode != SecurityTokenInclusionMode.Never)
  935. return false;
  936. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  937. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 0 || parameters.Endorsing.Count != 1 || parameters.SignedEndorsing.Count != 0)
  938. return false;
  939. x509Parameters = parameters.Endorsing[0] as X509SecurityTokenParameters;
  940. if (x509Parameters == null || x509Parameters.X509ReferenceStyle != X509KeyIdentifierClauseType.Thumbprint || x509Parameters.InclusionMode != SecurityTokenInclusionMode.AlwaysToRecipient)
  941. return false;
  942. if (!ssbe.RequireSignatureConfirmation)
  943. return false;
  944. }
  945. return true;
  946. }
  947. // If any changes are made to this method, please make sure that they are
  948. // reflected in the corresponding IsAnonymousForCertificateBinding() method.
  949. static public SymmetricSecurityBindingElement CreateAnonymousForCertificateBindingElement()
  950. {
  951. SymmetricSecurityBindingElement result;
  952. result = new SymmetricSecurityBindingElement(
  953. new X509SecurityTokenParameters( // protection
  954. X509KeyIdentifierClauseType.Thumbprint,
  955. SecurityTokenInclusionMode.Never));
  956. result.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
  957. result.RequireSignatureConfirmation = true;
  958. return result;
  959. }
  960. // this method reverses CreateAnonymousForCertificateBindingElement() logic
  961. internal static bool IsAnonymousForCertificateBinding(SecurityBindingElement sbe)
  962. {
  963. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  964. if (ssbe == null)
  965. return false;
  966. if (!ssbe.RequireSignatureConfirmation)
  967. return false;
  968. // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
  969. X509SecurityTokenParameters x509Parameters = ssbe.ProtectionTokenParameters as X509SecurityTokenParameters;
  970. if (x509Parameters == null || x509Parameters.X509ReferenceStyle != X509KeyIdentifierClauseType.Thumbprint || x509Parameters.InclusionMode != SecurityTokenInclusionMode.Never)
  971. return false;
  972. if (!sbe.EndpointSupportingTokenParameters.IsEmpty())
  973. return false;
  974. return true;
  975. }
  976. static public AsymmetricSecurityBindingElement CreateMutualCertificateDuplexBindingElement()
  977. {
  978. return CreateMutualCertificateDuplexBindingElement(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11);
  979. }
  980. static public AsymmetricSecurityBindingElement CreateMutualCertificateDuplexBindingElement(MessageSecurityVersion version)
  981. {
  982. if (version == null)
  983. {
  984. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
  985. }
  986. AsymmetricSecurityBindingElement result;
  987. if (version.SecurityVersion == SecurityVersion.WSSecurity10)
  988. {
  989. result = new AsymmetricSecurityBindingElement(
  990. new X509SecurityTokenParameters( // recipient
  991. X509KeyIdentifierClauseType.Any,
  992. SecurityTokenInclusionMode.AlwaysToInitiator,
  993. false),
  994. new X509SecurityTokenParameters( // initiator
  995. X509KeyIdentifierClauseType.Any,
  996. SecurityTokenInclusionMode.AlwaysToRecipient,
  997. false));
  998. }
  999. else
  1000. {
  1001. result = new AsymmetricSecurityBindingElement(
  1002. new X509SecurityTokenParameters( // recipient
  1003. X509KeyIdentifierClauseType.Thumbprint,
  1004. SecurityTokenInclusionMode.AlwaysToInitiator,
  1005. false),
  1006. new X509SecurityTokenParameters( // initiator
  1007. X509KeyIdentifierClauseType.Thumbprint,
  1008. SecurityTokenInclusionMode.AlwaysToRecipient,
  1009. false));
  1010. }
  1011. result.MessageSecurityVersion = version;
  1012. return result;
  1013. }
  1014. // If any changes are made to this method, please make sure that they are
  1015. // reflected in the corresponding IsUserNameForCertificateBinding() method.
  1016. static public SymmetricSecurityBindingElement CreateUserNameForCertificateBindingElement()
  1017. {
  1018. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(
  1019. new X509SecurityTokenParameters(
  1020. X509KeyIdentifierClauseType.Thumbprint,
  1021. SecurityTokenInclusionMode.Never));
  1022. result.EndpointSupportingTokenParameters.SignedEncrypted.Add(
  1023. new UserNameSecurityTokenParameters());
  1024. result.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
  1025. return result;
  1026. }
  1027. // this method reverses CreateMutualCertificateBindingElement() logic
  1028. internal static bool IsUserNameForCertificateBinding(SecurityBindingElement sbe)
  1029. {
  1030. // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
  1031. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1032. if (ssbe == null)
  1033. return false;
  1034. X509SecurityTokenParameters x509Parameters = ssbe.ProtectionTokenParameters as X509SecurityTokenParameters;
  1035. if (x509Parameters == null || x509Parameters.X509ReferenceStyle != X509KeyIdentifierClauseType.Thumbprint || x509Parameters.InclusionMode != SecurityTokenInclusionMode.Never)
  1036. return false;
  1037. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1038. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 1 || parameters.Endorsing.Count != 0 || parameters.SignedEndorsing.Count != 0)
  1039. return false;
  1040. UserNameSecurityTokenParameters userNameParameters = parameters.SignedEncrypted[0] as UserNameSecurityTokenParameters;
  1041. if (userNameParameters == null)
  1042. return false;
  1043. return true;
  1044. }
  1045. // If any changes are made to this method, please make sure that they are
  1046. // reflected in the corresponding IsKerberosBinding() method.
  1047. static public SymmetricSecurityBindingElement CreateKerberosBindingElement()
  1048. {
  1049. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(
  1050. new KerberosSecurityTokenParameters());
  1051. result.DefaultAlgorithmSuite = SecurityAlgorithmSuite.KerberosDefault;
  1052. return result;
  1053. }
  1054. // this method reverses CreateMutualCertificateBindingElement() logic
  1055. internal static bool IsKerberosBinding(SecurityBindingElement sbe)
  1056. {
  1057. // do not check DefaultAlgorithmSuite match: it is often changed by the caller of CreateKerberosBindingElement
  1058. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1059. if (ssbe == null)
  1060. return false;
  1061. KerberosSecurityTokenParameters parameters = ssbe.ProtectionTokenParameters as KerberosSecurityTokenParameters;
  1062. if (parameters == null)
  1063. return false;
  1064. if (!sbe.EndpointSupportingTokenParameters.IsEmpty())
  1065. return false;
  1066. return true;
  1067. }
  1068. static public SymmetricSecurityBindingElement CreateSspiNegotiationBindingElement()
  1069. {
  1070. return CreateSspiNegotiationBindingElement(SspiSecurityTokenParameters.defaultRequireCancellation);
  1071. }
  1072. // If any changes are made to this method, please make sure that they are
  1073. // reflected in the corresponding IsSspiNegotiationBinding() method.
  1074. static public SymmetricSecurityBindingElement CreateSspiNegotiationBindingElement(bool requireCancellation)
  1075. {
  1076. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(
  1077. new SspiSecurityTokenParameters(requireCancellation));
  1078. return result;
  1079. }
  1080. // this method reverses CreateMutualCertificateBindingElement() logic
  1081. internal static bool IsSspiNegotiationBinding(SecurityBindingElement sbe, bool requireCancellation)
  1082. {
  1083. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1084. if (ssbe == null)
  1085. return false;
  1086. if (!sbe.EndpointSupportingTokenParameters.IsEmpty())
  1087. return false;
  1088. SspiSecurityTokenParameters sspiParameters = ssbe.ProtectionTokenParameters as SspiSecurityTokenParameters;
  1089. if (sspiParameters == null)
  1090. return false;
  1091. return sspiParameters.RequireCancellation == requireCancellation;
  1092. }
  1093. static public SymmetricSecurityBindingElement CreateSslNegotiationBindingElement(bool requireClientCertificate)
  1094. {
  1095. return CreateSslNegotiationBindingElement(requireClientCertificate, SslSecurityTokenParameters.defaultRequireCancellation);
  1096. }
  1097. // If any changes are made to this method, please make sure that they are
  1098. // reflected in the corresponding IsSslNegotiationBinding() method.
  1099. static public SymmetricSecurityBindingElement CreateSslNegotiationBindingElement(bool requireClientCertificate, bool requireCancellation)
  1100. {
  1101. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(
  1102. new SslSecurityTokenParameters(requireClientCertificate, requireCancellation));
  1103. return result;
  1104. }
  1105. // this method reverses CreateMutualCertificateBindingElement() logic
  1106. internal static bool IsSslNegotiationBinding(SecurityBindingElement sbe, bool requireClientCertificate, bool requireCancellation)
  1107. {
  1108. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1109. if (ssbe == null)
  1110. return false;
  1111. if (!sbe.EndpointSupportingTokenParameters.IsEmpty())
  1112. return false;
  1113. SslSecurityTokenParameters sslParameters = ssbe.ProtectionTokenParameters as SslSecurityTokenParameters;
  1114. if (sslParameters == null)
  1115. return false;
  1116. return sslParameters.RequireClientCertificate == requireClientCertificate && sslParameters.RequireCancellation == requireCancellation;
  1117. }
  1118. static public SymmetricSecurityBindingElement CreateIssuedTokenBindingElement(IssuedSecurityTokenParameters issuedTokenParameters)
  1119. {
  1120. if (issuedTokenParameters == null)
  1121. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuedTokenParameters");
  1122. if (issuedTokenParameters.KeyType != SecurityKeyType.SymmetricKey)
  1123. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.IssuedTokenAuthenticationModeRequiresSymmetricIssuedKey));
  1124. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(issuedTokenParameters);
  1125. return result;
  1126. }
  1127. // If any changes are made to this method, please make sure that they are
  1128. // reflected in the corresponding IsIssuedTokenForCertificateBinding() method.
  1129. static public SymmetricSecurityBindingElement CreateIssuedTokenForCertificateBindingElement(IssuedSecurityTokenParameters issuedTokenParameters)
  1130. {
  1131. if (issuedTokenParameters == null)
  1132. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuedTokenParameters");
  1133. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(
  1134. new X509SecurityTokenParameters(
  1135. X509KeyIdentifierClauseType.Thumbprint,
  1136. SecurityTokenInclusionMode.Never));
  1137. if (issuedTokenParameters.KeyType == SecurityKeyType.BearerKey)
  1138. {
  1139. result.EndpointSupportingTokenParameters.SignedEncrypted.Add(issuedTokenParameters);
  1140. result.MessageSecurityVersion = MessageSecurityVersion.WSSXDefault;
  1141. }
  1142. else
  1143. {
  1144. result.EndpointSupportingTokenParameters.Endorsing.Add(issuedTokenParameters);
  1145. result.MessageSecurityVersion = MessageSecurityVersion.Default;
  1146. }
  1147. result.RequireSignatureConfirmation = true;
  1148. return result;
  1149. }
  1150. // this method reverses CreateMutualCertificateBindingElement() logic
  1151. internal static bool IsIssuedTokenForCertificateBinding(SecurityBindingElement sbe, out IssuedSecurityTokenParameters issuedTokenParameters)
  1152. {
  1153. issuedTokenParameters = null;
  1154. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1155. if (ssbe == null)
  1156. return false;
  1157. if (!ssbe.RequireSignatureConfirmation)
  1158. return false;
  1159. // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
  1160. X509SecurityTokenParameters x509Parameters = ssbe.ProtectionTokenParameters as X509SecurityTokenParameters;
  1161. if (x509Parameters == null || x509Parameters.X509ReferenceStyle != X509KeyIdentifierClauseType.Thumbprint || x509Parameters.InclusionMode != SecurityTokenInclusionMode.Never)
  1162. return false;
  1163. SupportingTokenParameters parameters = ssbe.EndpointSupportingTokenParameters;
  1164. if (parameters.Signed.Count != 0 || (parameters.SignedEncrypted.Count == 0 && parameters.Endorsing.Count == 0) || parameters.SignedEndorsing.Count != 0)
  1165. return false;
  1166. if ((parameters.SignedEncrypted.Count == 1) && (parameters.Endorsing.Count == 0))
  1167. {
  1168. issuedTokenParameters = parameters.SignedEncrypted[0] as IssuedSecurityTokenParameters;
  1169. if (issuedTokenParameters != null && issuedTokenParameters.KeyType != SecurityKeyType.BearerKey)
  1170. return false;
  1171. }
  1172. else if ((parameters.Endorsing.Count == 1) && (parameters.SignedEncrypted.Count == 0))
  1173. {
  1174. issuedTokenParameters = parameters.Endorsing[0] as IssuedSecurityTokenParameters;
  1175. if (issuedTokenParameters != null && (issuedTokenParameters.KeyType != SecurityKeyType.SymmetricKey && issuedTokenParameters.KeyType != SecurityKeyType.AsymmetricKey))
  1176. return false;
  1177. }
  1178. return (issuedTokenParameters != null);
  1179. }
  1180. // If any changes are made to this method, please make sure that they are
  1181. // reflected in the corresponding IsIssuedTokenForSslBinding() method.
  1182. static public SymmetricSecurityBindingElement CreateIssuedTokenForSslBindingElement(IssuedSecurityTokenParameters issuedTokenParameters)
  1183. {
  1184. return CreateIssuedTokenForSslBindingElement(issuedTokenParameters, SslSecurityTokenParameters.defaultRequireCancellation);
  1185. }
  1186. // this method reverses CreateMutualCertificateBindingElement() logic
  1187. internal static bool IsIssuedTokenForSslBinding(SecurityBindingElement sbe, out IssuedSecurityTokenParameters issuedTokenParameters)
  1188. {
  1189. return IsIssuedTokenForSslBinding(sbe, SslSecurityTokenParameters.defaultRequireCancellation, out issuedTokenParameters);
  1190. }
  1191. // If any changes are made to this method, please make sure that they are
  1192. // reflected in the corresponding IsIssuedTokenForSslBinding() method.
  1193. static public SymmetricSecurityBindingElement CreateIssuedTokenForSslBindingElement(IssuedSecurityTokenParameters issuedTokenParameters, bool requireCancellation)
  1194. {
  1195. if (issuedTokenParameters == null)
  1196. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuedTokenParameters");
  1197. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(
  1198. new SslSecurityTokenParameters(false, requireCancellation));
  1199. if (issuedTokenParameters.KeyType == SecurityKeyType.BearerKey)
  1200. {
  1201. result.EndpointSupportingTokenParameters.SignedEncrypted.Add(issuedTokenParameters);
  1202. result.MessageSecurityVersion = MessageSecurityVersion.WSSXDefault;
  1203. }
  1204. else
  1205. {
  1206. result.EndpointSupportingTokenParameters.Endorsing.Add(issuedTokenParameters);
  1207. result.MessageSecurityVersion = MessageSecurityVersion.Default;
  1208. }
  1209. result.RequireSignatureConfirmation = true;
  1210. return result;
  1211. }
  1212. // this method reverses CreateMutualCertificateBindingElement() logic
  1213. internal static bool IsIssuedTokenForSslBinding(SecurityBindingElement sbe, bool requireCancellation, out IssuedSecurityTokenParameters issuedTokenParameters)
  1214. {
  1215. issuedTokenParameters = null;
  1216. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1217. if (ssbe == null)
  1218. return false;
  1219. if (!ssbe.RequireSignatureConfirmation)
  1220. return false;
  1221. // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
  1222. SslSecurityTokenParameters sslParameters = ssbe.ProtectionTokenParameters as SslSecurityTokenParameters;
  1223. if (sslParameters == null)
  1224. return false;
  1225. if (sslParameters.RequireClientCertificate || sslParameters.RequireCancellation != requireCancellation)
  1226. return false;
  1227. SupportingTokenParameters parameters = ssbe.EndpointSupportingTokenParameters;
  1228. if (parameters.Signed.Count != 0 || (parameters.SignedEncrypted.Count == 0 && parameters.Endorsing.Count == 0) || parameters.SignedEndorsing.Count != 0)
  1229. return false;
  1230. if ((parameters.SignedEncrypted.Count == 1) && (parameters.Endorsing.Count == 0))
  1231. {
  1232. issuedTokenParameters = parameters.SignedEncrypted[0] as IssuedSecurityTokenParameters;
  1233. if (issuedTokenParameters != null && issuedTokenParameters.KeyType != SecurityKeyType.BearerKey)
  1234. return false;
  1235. }
  1236. else if ((parameters.Endorsing.Count == 1) && (parameters.SignedEncrypted.Count == 0))
  1237. {
  1238. issuedTokenParameters = parameters.Endorsing[0] as IssuedSecurityTokenParameters;
  1239. if (issuedTokenParameters != null && (issuedTokenParameters.KeyType != SecurityKeyType.SymmetricKey && issuedTokenParameters.KeyType != SecurityKeyType.AsymmetricKey))
  1240. return false;
  1241. }
  1242. return (issuedTokenParameters != null);
  1243. }
  1244. static public SymmetricSecurityBindingElement CreateUserNameForSslBindingElement()
  1245. {
  1246. return CreateUserNameForSslBindingElement(SslSecurityTokenParameters.defaultRequireCancellation);
  1247. }
  1248. // If any changes are made to this method, please make sure that they are
  1249. // reflected in the corresponding IsUserNameForSslBinding() method.
  1250. static public SymmetricSecurityBindingElement CreateUserNameForSslBindingElement(bool requireCancellation)
  1251. {
  1252. SymmetricSecurityBindingElement result = new SymmetricSecurityBindingElement(
  1253. new SslSecurityTokenParameters(false, requireCancellation));
  1254. result.EndpointSupportingTokenParameters.SignedEncrypted.Add(
  1255. new UserNameSecurityTokenParameters());
  1256. result.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
  1257. return result;
  1258. }
  1259. // this method reverses CreateMutualCertificateBindingElement() logic
  1260. internal static bool IsUserNameForSslBinding(SecurityBindingElement sbe, bool requireCancellation)
  1261. {
  1262. // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
  1263. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1264. if (ssbe == null)
  1265. return false;
  1266. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1267. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 1 || parameters.Endorsing.Count != 0 || parameters.SignedEndorsing.Count != 0)
  1268. return false;
  1269. if (!(parameters.SignedEncrypted[0] is UserNameSecurityTokenParameters))
  1270. return false;
  1271. SslSecurityTokenParameters sslParameters = ssbe.ProtectionTokenParameters as SslSecurityTokenParameters;
  1272. if (sslParameters == null)
  1273. return false;
  1274. return sslParameters.RequireCancellation == requireCancellation && !sslParameters.RequireClientCertificate;
  1275. }
  1276. // If any changes are made to this method, please make sure that they are
  1277. // reflected in the corresponding IsUserNameOverTransportBinding() method.
  1278. static public TransportSecurityBindingElement CreateUserNameOverTransportBindingElement()
  1279. {
  1280. TransportSecurityBindingElement result = new TransportSecurityBindingElement();
  1281. result.EndpointSupportingTokenParameters.SignedEncrypted.Add(
  1282. new UserNameSecurityTokenParameters());
  1283. result.IncludeTimestamp = true;
  1284. result.LocalClientSettings.DetectReplays = false;
  1285. result.LocalServiceSettings.DetectReplays = false;
  1286. return result;
  1287. }
  1288. // this method reverses CreateMutualCertificateBindingElement() logic
  1289. internal static bool IsUserNameOverTransportBinding(SecurityBindingElement sbe)
  1290. {
  1291. // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
  1292. if (!sbe.IncludeTimestamp)
  1293. return false;
  1294. if (!(sbe is TransportSecurityBindingElement))
  1295. return false;
  1296. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1297. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 1 || parameters.Endorsing.Count != 0 || parameters.SignedEndorsing.Count != 0)
  1298. return false;
  1299. UserNameSecurityTokenParameters userNameParameters = parameters.SignedEncrypted[0] as UserNameSecurityTokenParameters;
  1300. if (userNameParameters == null)
  1301. return false;
  1302. return true;
  1303. }
  1304. // If any changes are made to this method, please make sure that they are
  1305. // reflected in the corresponding IsCertificateOverTransportBinding() method.
  1306. static public TransportSecurityBindingElement CreateCertificateOverTransportBindingElement()
  1307. {
  1308. return CreateCertificateOverTransportBindingElement(MessageSecurityVersion.Default);
  1309. }
  1310. // If any changes are made to this method, please make sure that they are
  1311. // reflected in the corresponding IsCertificateOverTransportBinding() method.
  1312. static public TransportSecurityBindingElement CreateCertificateOverTransportBindingElement(MessageSecurityVersion version)
  1313. {
  1314. if (version == null)
  1315. {
  1316. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
  1317. }
  1318. X509KeyIdentifierClauseType x509ReferenceType;
  1319. if (version.SecurityVersion == SecurityVersion.WSSecurity10)
  1320. {
  1321. x509ReferenceType = X509KeyIdentifierClauseType.Any;
  1322. }
  1323. else
  1324. {
  1325. x509ReferenceType = X509KeyIdentifierClauseType.Thumbprint;
  1326. }
  1327. TransportSecurityBindingElement result = new TransportSecurityBindingElement();
  1328. X509SecurityTokenParameters x509Parameters = new X509SecurityTokenParameters(
  1329. x509ReferenceType,
  1330. SecurityTokenInclusionMode.AlwaysToRecipient,
  1331. false);
  1332. result.EndpointSupportingTokenParameters.Endorsing.Add(
  1333. x509Parameters
  1334. );
  1335. result.IncludeTimestamp = true;
  1336. result.LocalClientSettings.DetectReplays = false;
  1337. result.LocalServiceSettings.DetectReplays = false;
  1338. result.MessageSecurityVersion = version;
  1339. return result;
  1340. }
  1341. // this method reverses CreateMutualCertificateBindingElement() logic
  1342. internal static bool IsCertificateOverTransportBinding(SecurityBindingElement sbe)
  1343. {
  1344. // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
  1345. if (!sbe.IncludeTimestamp)
  1346. return false;
  1347. if (!(sbe is TransportSecurityBindingElement))
  1348. return false;
  1349. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1350. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 0 || parameters.Endorsing.Count != 1 || parameters.SignedEndorsing.Count != 0)
  1351. return false;
  1352. X509SecurityTokenParameters x509Parameters = parameters.Endorsing[0] as X509SecurityTokenParameters;
  1353. if (x509Parameters == null)
  1354. return false;
  1355. if (x509Parameters.InclusionMode != SecurityTokenInclusionMode.AlwaysToRecipient)
  1356. return false;
  1357. return x509Parameters.X509ReferenceStyle == X509KeyIdentifierClauseType.Any || x509Parameters.X509ReferenceStyle == X509KeyIdentifierClauseType.Thumbprint;
  1358. }
  1359. static public TransportSecurityBindingElement CreateKerberosOverTransportBindingElement()
  1360. {
  1361. TransportSecurityBindingElement result = new TransportSecurityBindingElement();
  1362. KerberosSecurityTokenParameters kerberosParameters = new KerberosSecurityTokenParameters();
  1363. kerberosParameters.RequireDerivedKeys = false;
  1364. result.EndpointSupportingTokenParameters.Endorsing.Add(
  1365. kerberosParameters);
  1366. result.IncludeTimestamp = true;
  1367. result.LocalClientSettings.DetectReplays = false;
  1368. result.LocalServiceSettings.DetectReplays = false;
  1369. result.DefaultAlgorithmSuite = SecurityAlgorithmSuite.KerberosDefault;
  1370. result.SupportsExtendedProtectionPolicy = true;
  1371. return result;
  1372. }
  1373. #if NO
  1374. // this is reversing of the CreateKerberosOverTransportBindingElement() logic
  1375. static bool IsKerberosOverTransportBinding(SecurityBindingElement sbe)
  1376. {
  1377. if (sbe.DefaultAlgorithmSuite != SecurityAlgorithmSuite.KerberosDefault)
  1378. return false;
  1379. // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
  1380. if (!sbe.IncludeTimestamp)
  1381. return false;
  1382. if (!(sbe is TransportSecurityBindingElement))
  1383. return false;
  1384. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1385. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 0 || parameters.Endorsing.Count != 1 || parameters.SignedEndorsing.Count != 0)
  1386. return false;
  1387. KerberosSecurityTokenParameters kerberosParameters = parameters.Endorsing[0] as KerberosSecurityTokenParameters;
  1388. if (kerberosParameters == null)
  1389. return false;
  1390. if (kerberosParameters.RequireDerivedKeys)
  1391. return false;
  1392. return true;
  1393. }
  1394. #endif
  1395. static public TransportSecurityBindingElement CreateSspiNegotiationOverTransportBindingElement()
  1396. {
  1397. return CreateSspiNegotiationOverTransportBindingElement(true);
  1398. }
  1399. // If any changes are made to this method, please make sure that they are
  1400. // reflected in the corresponding IsSspiNegotiationOverTransportBinding() method.
  1401. static public TransportSecurityBindingElement CreateSspiNegotiationOverTransportBindingElement(bool requireCancellation)
  1402. {
  1403. TransportSecurityBindingElement result = new TransportSecurityBindingElement();
  1404. SspiSecurityTokenParameters sspiParameters = new SspiSecurityTokenParameters(requireCancellation);
  1405. sspiParameters.RequireDerivedKeys = false;
  1406. result.EndpointSupportingTokenParameters.Endorsing.Add(
  1407. sspiParameters);
  1408. result.IncludeTimestamp = true;
  1409. result.LocalClientSettings.DetectReplays = false;
  1410. result.LocalServiceSettings.DetectReplays = false;
  1411. result.SupportsExtendedProtectionPolicy = true;
  1412. return result;
  1413. }
  1414. // this method reverses CreateSspiNegotiationOverTransportBindingElement() logic
  1415. internal static bool IsSspiNegotiationOverTransportBinding(SecurityBindingElement sbe, bool requireCancellation)
  1416. {
  1417. // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
  1418. if (!sbe.IncludeTimestamp)
  1419. return false;
  1420. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1421. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 0 || parameters.Endorsing.Count != 1 || parameters.SignedEndorsing.Count != 0)
  1422. return false;
  1423. SspiSecurityTokenParameters sspiParameters = parameters.Endorsing[0] as SspiSecurityTokenParameters;
  1424. if (sspiParameters == null)
  1425. return false;
  1426. if (sspiParameters.RequireDerivedKeys)
  1427. return false;
  1428. if (sspiParameters.RequireCancellation != requireCancellation)
  1429. return false;
  1430. if (!(sbe is TransportSecurityBindingElement))
  1431. return false;
  1432. return true;
  1433. }
  1434. // If any changes are made to this method, please make sure that they are
  1435. // reflected in the corresponding IsIssuedTokenOverTransportBinding() method.
  1436. static public TransportSecurityBindingElement CreateIssuedTokenOverTransportBindingElement(IssuedSecurityTokenParameters issuedTokenParameters)
  1437. {
  1438. if (issuedTokenParameters == null)
  1439. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuedTokenParameters");
  1440. issuedTokenParameters.RequireDerivedKeys = false;
  1441. TransportSecurityBindingElement result = new TransportSecurityBindingElement();
  1442. if (issuedTokenParameters.KeyType == SecurityKeyType.BearerKey)
  1443. {
  1444. result.EndpointSupportingTokenParameters.Signed.Add(issuedTokenParameters);
  1445. result.MessageSecurityVersion = MessageSecurityVersion.WSSXDefault;
  1446. }
  1447. else
  1448. {
  1449. result.EndpointSupportingTokenParameters.Endorsing.Add(issuedTokenParameters);
  1450. result.MessageSecurityVersion = MessageSecurityVersion.Default;
  1451. }
  1452. result.LocalClientSettings.DetectReplays = false;
  1453. result.LocalServiceSettings.DetectReplays = false;
  1454. result.IncludeTimestamp = true;
  1455. return result;
  1456. }
  1457. // this method reverses CreateIssuedTokenOverTransportBindingElement() logic
  1458. internal static bool IsIssuedTokenOverTransportBinding(SecurityBindingElement sbe, out IssuedSecurityTokenParameters issuedTokenParameters)
  1459. {
  1460. issuedTokenParameters = null;
  1461. if (!(sbe is TransportSecurityBindingElement))
  1462. return false;
  1463. if (!sbe.IncludeTimestamp)
  1464. return false;
  1465. // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
  1466. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1467. if (parameters.SignedEncrypted.Count != 0 || (parameters.Signed.Count == 0 && parameters.Endorsing.Count == 0) || parameters.SignedEndorsing.Count != 0)
  1468. return false;
  1469. if ((parameters.Signed.Count == 1) && (parameters.Endorsing.Count == 0))
  1470. {
  1471. issuedTokenParameters = parameters.Signed[0] as IssuedSecurityTokenParameters;
  1472. if (issuedTokenParameters != null && issuedTokenParameters.KeyType != SecurityKeyType.BearerKey)
  1473. return false;
  1474. }
  1475. else if ((parameters.Endorsing.Count == 1) && (parameters.Signed.Count == 0))
  1476. {
  1477. issuedTokenParameters = parameters.Endorsing[0] as IssuedSecurityTokenParameters;
  1478. if (issuedTokenParameters != null && (issuedTokenParameters.KeyType != SecurityKeyType.SymmetricKey && issuedTokenParameters.KeyType != SecurityKeyType.AsymmetricKey))
  1479. return false;
  1480. }
  1481. if (issuedTokenParameters == null)
  1482. return false;
  1483. if (issuedTokenParameters.RequireDerivedKeys)
  1484. return false;
  1485. return true;
  1486. }
  1487. // If any changes are made to this method, please make sure that they are
  1488. // reflected in the corresponding IsSecureConversationBinding() method.
  1489. static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity)
  1490. {
  1491. return CreateSecureConversationBindingElement(bootstrapSecurity, SecureConversationSecurityTokenParameters.defaultRequireCancellation, null);
  1492. }
  1493. // this method reverses CreateSecureConversationBindingElement() logic
  1494. internal static bool IsSecureConversationBinding(SecurityBindingElement sbe, out SecurityBindingElement bootstrapSecurity)
  1495. {
  1496. return IsSecureConversationBinding(sbe, SecureConversationSecurityTokenParameters.defaultRequireCancellation, out bootstrapSecurity);
  1497. }
  1498. static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity, bool requireCancellation)
  1499. {
  1500. return CreateSecureConversationBindingElement(bootstrapSecurity, requireCancellation, null);
  1501. }
  1502. // If any changes are made to this method, please make sure that they are
  1503. // reflected in the corresponding IsSecureConversationBinding() method.
  1504. static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity, bool requireCancellation, ChannelProtectionRequirements bootstrapProtectionRequirements)
  1505. {
  1506. if (bootstrapSecurity == null)
  1507. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bootstrapBinding");
  1508. SecurityBindingElement result;
  1509. if (bootstrapSecurity is TransportSecurityBindingElement)
  1510. {
  1511. // there is no need to do replay detection or key derivation for transport bindings
  1512. TransportSecurityBindingElement primary = new TransportSecurityBindingElement();
  1513. SecureConversationSecurityTokenParameters scParameters = new SecureConversationSecurityTokenParameters(
  1514. bootstrapSecurity,
  1515. requireCancellation,
  1516. bootstrapProtectionRequirements);
  1517. scParameters.RequireDerivedKeys = false;
  1518. primary.EndpointSupportingTokenParameters.Endorsing.Add(
  1519. scParameters);
  1520. primary.LocalClientSettings.DetectReplays = false;
  1521. primary.LocalServiceSettings.DetectReplays = false;
  1522. primary.IncludeTimestamp = true;
  1523. result = primary;
  1524. }
  1525. else // Symmetric- or AsymmetricSecurityBindingElement
  1526. {
  1527. SymmetricSecurityBindingElement primary = new SymmetricSecurityBindingElement(
  1528. new SecureConversationSecurityTokenParameters(
  1529. bootstrapSecurity,
  1530. requireCancellation,
  1531. bootstrapProtectionRequirements));
  1532. // there is no need for signature confirmation on the steady state binding
  1533. primary.RequireSignatureConfirmation = false;
  1534. result = primary;
  1535. }
  1536. return result;
  1537. }
  1538. // this method reverses CreateSecureConversationBindingElement() logic
  1539. internal static bool IsSecureConversationBinding(SecurityBindingElement sbe, bool requireCancellation, out SecurityBindingElement bootstrapSecurity)
  1540. {
  1541. bootstrapSecurity = null;
  1542. SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
  1543. if (ssbe != null)
  1544. {
  1545. if (ssbe.RequireSignatureConfirmation)
  1546. return false;
  1547. SecureConversationSecurityTokenParameters parameters = ssbe.ProtectionTokenParameters as SecureConversationSecurityTokenParameters;
  1548. if (parameters == null)
  1549. return false;
  1550. if (parameters.RequireCancellation != requireCancellation)
  1551. return false;
  1552. bootstrapSecurity = parameters.BootstrapSecurityBindingElement;
  1553. }
  1554. else
  1555. {
  1556. if (!sbe.IncludeTimestamp)
  1557. return false;
  1558. // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
  1559. if (!(sbe is TransportSecurityBindingElement))
  1560. return false;
  1561. SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
  1562. if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 0 || parameters.Endorsing.Count != 1 || parameters.SignedEndorsing.Count != 0)
  1563. return false;
  1564. SecureConversationSecurityTokenParameters scParameters = parameters.Endorsing[0] as SecureConversationSecurityTokenParameters;
  1565. if (scParameters == null)
  1566. return false;
  1567. if (scParameters.RequireCancellation != requireCancellation)
  1568. return false;
  1569. bootstrapSecurity = scParameters.BootstrapSecurityBindingElement;
  1570. }
  1571. if (bootstrapSecurity != null && bootstrapSecurity.SecurityHeaderLayout != SecurityProtocolFactory.defaultSecurityHeaderLayout)
  1572. return false;
  1573. return bootstrapSecurity != null;
  1574. }
  1575. public override string ToString()
  1576. {
  1577. StringBuilder sb = new StringBuilder();
  1578. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "{0}:", this.GetType().ToString()));
  1579. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "DefaultAlgorithmSuite: {0}", this.defaultAlgorithmSuite.ToString()));
  1580. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "IncludeTimestamp: {0}", this.includeTimestamp.ToString()));
  1581. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "KeyEntropyMode: {0}", this.keyEntropyMode.ToString()));
  1582. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "MessageSecurityVersion: {0}", this.MessageSecurityVersion.ToString()));
  1583. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "SecurityHeaderLayout: {0}", this.securityHeaderLayout.ToString()));
  1584. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "ProtectTokens: {0}", this.protectTokens.ToString()));
  1585. sb.AppendLine("EndpointSupportingTokenParameters:");
  1586. sb.AppendLine(" " + this.EndpointSupportingTokenParameters.ToString().Trim().Replace("\n", "\n "));
  1587. sb.AppendLine("OptionalEndpointSupportingTokenParameters:");
  1588. sb.AppendLine(" " + this.OptionalEndpointSupportingTokenParameters.ToString().Trim().Replace("\n", "\n "));
  1589. if (this.operationSupportingTokenParameters.Count == 0)
  1590. {
  1591. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "OperationSupportingTokenParameters: none"));
  1592. }
  1593. else
  1594. {
  1595. foreach (string requestAction in this.OperationSupportingTokenParameters.Keys)
  1596. {
  1597. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "OperationSupportingTokenParameters[\"{0}\"]:", requestAction));
  1598. sb.AppendLine(" " + this.OperationSupportingTokenParameters[requestAction].ToString().Trim().Replace("\n", "\n "));
  1599. }
  1600. }
  1601. if (this.optionalOperationSupportingTokenParameters.Count == 0)
  1602. {
  1603. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "OptionalOperationSupportingTokenParameters: none"));
  1604. }
  1605. else
  1606. {
  1607. foreach (string requestAction in this.OptionalOperationSupportingTokenParameters.Keys)
  1608. {
  1609. sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "OptionalOperationSupportingTokenParameters[\"{0}\"]:", requestAction));
  1610. sb.AppendLine(" " + this.OptionalOperationSupportingTokenParameters[requestAction].ToString().Trim().Replace("\n", "\n "));
  1611. }
  1612. }
  1613. return sb.ToString().Trim();
  1614. }
  1615. internal static ChannelProtectionRequirements ComputeProtectionRequirements(SecurityBindingElement security, BindingParameterCollection parameterCollection, BindingElementCollection bindingElements, bool isForService)
  1616. {
  1617. if (parameterCollection == null)
  1618. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameterCollection");
  1619. if (bindingElements == null)
  1620. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bindingElements");
  1621. if (security == null)
  1622. {
  1623. return null;
  1624. }
  1625. ChannelProtectionRequirements result = null;
  1626. if ((security is SymmetricSecurityBindingElement) || (security is AsymmetricSecurityBindingElement))
  1627. {
  1628. result = new ChannelProtectionRequirements();
  1629. ChannelProtectionRequirements contractRequirements = parameterCollection.Find<ChannelProtectionRequirements>();
  1630. if (contractRequirements != null)
  1631. result.Add(contractRequirements);
  1632. AddBindingProtectionRequirements(result, bindingElements, !isForService);
  1633. }
  1634. return result;
  1635. }
  1636. static void AddBindingProtectionRequirements(ChannelProtectionRequirements requirements, BindingElementCollection bindingElements, bool isForChannel)
  1637. {
  1638. // Gather custom requirements from bindingElements
  1639. CustomBinding binding = new CustomBinding(bindingElements);
  1640. BindingContext context = new BindingContext(binding, new BindingParameterCollection());
  1641. // In theory, we can just do
  1642. // context.GetInnerProperty<ChannelProtectionRequirements>()
  1643. // but that relies on each binding element to correctly union-up its own requirements with
  1644. // those of the rest of the stack. So instead, we ask each BE individually, and we do the
  1645. // work of combining the results. This protects us against this scenario: someone authors "FooBE"
  1646. // with a a GetProperty implementation that always returns null (oops), and puts FooBE on the
  1647. // top of the stack, and so FooBE "hides" important protection requirements that inner BEs
  1648. // require, resulting in an insecure binding.
  1649. foreach (BindingElement bindingElement in bindingElements)
  1650. {
  1651. if (bindingElement != null)
  1652. {
  1653. // ask each element individually for its requirements
  1654. context.RemainingBindingElements.Clear();
  1655. context.RemainingBindingElements.Add(bindingElement);
  1656. ChannelProtectionRequirements s = context.GetInnerProperty<ChannelProtectionRequirements>();
  1657. if (s != null)
  1658. {
  1659. //if (isForChannel)
  1660. //{
  1661. // requirements.Add(s.CreateInverse());
  1662. //}
  1663. //else
  1664. //{
  1665. requirements.Add(s);
  1666. //}
  1667. }
  1668. }
  1669. }
  1670. }
  1671. internal void ApplyAuditBehaviorSettings(BindingContext context, SecurityProtocolFactory factory)
  1672. {
  1673. ServiceSecurityAuditBehavior auditBehavior = context.BindingParameters.Find<ServiceSecurityAuditBehavior>();
  1674. if (auditBehavior != null)
  1675. {
  1676. factory.AuditLogLocation = auditBehavior.AuditLogLocation;
  1677. factory.SuppressAuditFailure = auditBehavior.SuppressAuditFailure;
  1678. factory.ServiceAuthorizationAuditLevel = auditBehavior.ServiceAuthorizationAuditLevel;
  1679. factory.MessageAuthenticationAuditLevel = auditBehavior.MessageAuthenticationAuditLevel;
  1680. }
  1681. else
  1682. {
  1683. factory.AuditLogLocation = ServiceSecurityAuditBehavior.defaultAuditLogLocation;
  1684. factory.SuppressAuditFailure = ServiceSecurityAuditBehavior.defaultSuppressAuditFailure;
  1685. factory.ServiceAuthorizationAuditLevel = ServiceSecurityAuditBehavior.defaultServiceAuthorizationAuditLevel;
  1686. factory.MessageAuthenticationAuditLevel = ServiceSecurityAuditBehavior.defaultMessageAuthenticationAuditLevel;
  1687. }
  1688. }
  1689. internal override bool IsMatch(BindingElement b)
  1690. {
  1691. if (b == null)
  1692. return false;
  1693. SecurityBindingElement security = b as SecurityBindingElement;
  1694. if (security == null)
  1695. return false;
  1696. return SecurityElement.AreBindingsMatching(this, security);
  1697. }
  1698. static void AddAssertionIfNotNull(PolicyConversionContext policyContext, XmlElement assertion)
  1699. {
  1700. if (policyContext != null && assertion != null)
  1701. {
  1702. policyContext.GetBindingAssertions().Add(assertion);
  1703. }
  1704. }
  1705. static void AddAssertionIfNotNull(PolicyConversionContext policyContext, Collection<XmlElement> assertions)
  1706. {
  1707. if (policyContext != null && assertions != null)
  1708. {
  1709. PolicyAssertionCollection existingAssertions = policyContext.GetBindingAssertions();
  1710. for (int i = 0; i < assertions.Count; ++i)
  1711. existingAssertions.Add(assertions[i]);
  1712. }
  1713. }
  1714. static void AddAssertionIfNotNull(PolicyConversionContext policyContext, OperationDescription operation, XmlElement assertion)
  1715. {
  1716. if (policyContext != null && assertion != null)
  1717. {
  1718. policyContext.GetOperationBindingAssertions(operation).Add(assertion);
  1719. }
  1720. }
  1721. static void AddAssertionIfNotNull(PolicyConversionContext policyContext, OperationDescription operation, Collection<XmlElement> assertions)
  1722. {
  1723. if (policyContext != null && assertions != null)
  1724. {
  1725. PolicyAssertionCollection existingAssertions = policyContext.GetOperationBindingAssertions(operation);
  1726. for (int i = 0; i < assertions.Count; ++i)
  1727. existingAssertions.Add(assertions[i]);
  1728. }
  1729. }
  1730. static void AddAssertionIfNotNull(PolicyConversionContext policyContext, MessageDescription message, XmlElement assertion)
  1731. {
  1732. if (policyContext != null && assertion != null)
  1733. {
  1734. policyContext.GetMessageBindingAssertions(message).Add(assertion);
  1735. }
  1736. }
  1737. static void AddAssertionIfNotNull(PolicyConversionContext policyContext, FaultDescription message, XmlElement assertion)
  1738. {
  1739. if (policyContext != null && assertion != null)
  1740. {
  1741. policyContext.GetFaultBindingAssertions(message).Add(assertion);
  1742. }
  1743. }
  1744. internal static void ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
  1745. {
  1746. if (exporter == null)
  1747. {
  1748. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
  1749. }
  1750. if (context == null)
  1751. {
  1752. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
  1753. }
  1754. SecurityTraceRecordHelper.TraceExportChannelBindingEntry();
  1755. SecurityBindingElement binding = null;
  1756. ITransportTokenAssertionProvider transportTokenAssertionProvider = null;
  1757. BindingElementCollection bindingElementsBelowSecurity = new BindingElementCollection();
  1758. if ((context != null) && (context.BindingElements != null))
  1759. {
  1760. foreach (BindingElement be in context.BindingElements)
  1761. {
  1762. if (be is SecurityBindingElement)
  1763. {
  1764. binding = (SecurityBindingElement)be;
  1765. }
  1766. else
  1767. {
  1768. if (binding != null || be is MessageEncodingBindingElement || be is ITransportTokenAssertionProvider)
  1769. {
  1770. bindingElementsBelowSecurity.Add(be);
  1771. }
  1772. if (be is ITransportTokenAssertionProvider)
  1773. {
  1774. transportTokenAssertionProvider = (ITransportTokenAssertionProvider)be;
  1775. }
  1776. }
  1777. }
  1778. }
  1779. // this is used when exporting bootstrap policy for secure conversation in SecurityPolicy11.CreateWsspBootstrapPolicyAssertion
  1780. exporter.State[SecurityPolicyStrings.SecureConversationBootstrapBindingElementsBelowSecurityKey] = bindingElementsBelowSecurity;
  1781. bool hasCompletedSuccessfully = false;
  1782. try
  1783. {
  1784. if (binding is SymmetricSecurityBindingElement)
  1785. {
  1786. ExportSymmetricSecurityBindingElement((SymmetricSecurityBindingElement)binding, exporter, context);
  1787. ExportOperationScopeSupportingTokensPolicy(binding, exporter, context);
  1788. ExportMessageScopeProtectionPolicy(binding, exporter, context);
  1789. }
  1790. else if (binding is AsymmetricSecurityBindingElement)
  1791. {
  1792. ExportAsymmetricSecurityBindingElement((AsymmetricSecurityBindingElement)binding, exporter, context);
  1793. ExportOperationScopeSupportingTokensPolicy(binding, exporter, context);
  1794. ExportMessageScopeProtectionPolicy(binding, exporter, context);
  1795. }
  1796. hasCompletedSuccessfully = true;
  1797. }
  1798. finally
  1799. {
  1800. try
  1801. {
  1802. exporter.State.Remove(SecurityPolicyStrings.SecureConversationBootstrapBindingElementsBelowSecurityKey);
  1803. }
  1804. catch (Exception e)
  1805. {
  1806. // Always immediately rethrow fatal exceptions.
  1807. if (hasCompletedSuccessfully || Fx.IsFatal(e)) throw;
  1808. }
  1809. }
  1810. }
  1811. internal static void ExportPolicyForTransportTokenAssertionProviders(MetadataExporter exporter, PolicyConversionContext context)
  1812. {
  1813. if (exporter == null)
  1814. {
  1815. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
  1816. }
  1817. if (context == null)
  1818. {
  1819. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
  1820. }
  1821. SecurityTraceRecordHelper.TraceExportChannelBindingEntry();
  1822. SecurityBindingElement binding = null;
  1823. ITransportTokenAssertionProvider transportTokenAssertionProvider = null;
  1824. BindingElementCollection bindingElementsBelowSecurity = new BindingElementCollection();
  1825. if ((context != null) && (context.BindingElements != null))
  1826. {
  1827. foreach (BindingElement be in context.BindingElements)
  1828. {
  1829. if (be is SecurityBindingElement)
  1830. {
  1831. binding = (SecurityBindingElement)be;
  1832. }
  1833. else
  1834. {
  1835. if (binding != null || be is MessageEncodingBindingElement || be is ITransportTokenAssertionProvider)
  1836. {
  1837. bindingElementsBelowSecurity.Add(be);
  1838. }
  1839. if (be is ITransportTokenAssertionProvider)
  1840. {
  1841. transportTokenAssertionProvider = (ITransportTokenAssertionProvider)be;
  1842. }
  1843. }
  1844. }
  1845. }
  1846. // this is used when exporting bootstrap policy for secure conversation in SecurityPolicy11.CreateWsspBootstrapPolicyAssertion
  1847. exporter.State[SecurityPolicyStrings.SecureConversationBootstrapBindingElementsBelowSecurityKey] = bindingElementsBelowSecurity;
  1848. bool hasCompletedSuccessfully = false;
  1849. try
  1850. {
  1851. if (binding is TransportSecurityBindingElement)
  1852. {
  1853. if (transportTokenAssertionProvider == null && !binding.AllowInsecureTransport)
  1854. {
  1855. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ExportOfBindingWithTransportSecurityBindingElementAndNoTransportSecurityNotSupported)));
  1856. }
  1857. ExportTransportSecurityBindingElement((TransportSecurityBindingElement)binding, transportTokenAssertionProvider, exporter, context);
  1858. ExportOperationScopeSupportingTokensPolicy(binding, exporter, context);
  1859. }
  1860. else if (transportTokenAssertionProvider != null)
  1861. {
  1862. TransportSecurityBindingElement dummyTransportBindingElement = new TransportSecurityBindingElement();
  1863. if (binding == null)
  1864. {
  1865. dummyTransportBindingElement.IncludeTimestamp = false;
  1866. }
  1867. // In order to generate the right sp assertion without SBE.
  1868. // scenario: WSxHttpBinding with SecurityMode.Transport.
  1869. // See CSD 3105 for detail
  1870. HttpsTransportBindingElement httpsBinding = transportTokenAssertionProvider as HttpsTransportBindingElement;
  1871. if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
  1872. {
  1873. dummyTransportBindingElement.MessageSecurityVersion = httpsBinding.MessageSecurityVersion;
  1874. }
  1875. ExportTransportSecurityBindingElement(dummyTransportBindingElement, transportTokenAssertionProvider, exporter, context);
  1876. }
  1877. hasCompletedSuccessfully = true;
  1878. }
  1879. finally
  1880. {
  1881. try
  1882. {
  1883. exporter.State.Remove(SecurityPolicyStrings.SecureConversationBootstrapBindingElementsBelowSecurityKey);
  1884. }
  1885. catch (Exception e)
  1886. {
  1887. // Always immediately rethrow fatal exceptions.
  1888. if (hasCompletedSuccessfully || Fx.IsFatal(e)) throw;
  1889. }
  1890. }
  1891. }
  1892. //
  1893. // We will emit the wssp trust 10 assertion for all the case except for the basic http binding
  1894. // created through the BasicHttpBinding class. The reason for this exception is to allow better
  1895. // interop with third party when the third party doesn't understand the trust ----erion
  1896. //
  1897. static bool RequiresWsspTrust(SecurityBindingElement sbe)
  1898. {
  1899. if (sbe == null)
  1900. return false;
  1901. return !(sbe.doNotEmitTrust);
  1902. }
  1903. static void ExportAsymmetricSecurityBindingElement(AsymmetricSecurityBindingElement binding, MetadataExporter exporter, PolicyConversionContext policyContext)
  1904. {
  1905. WSSecurityPolicy sp = WSSecurityPolicy.GetSecurityPolicyDriver(binding.MessageSecurityVersion);
  1906. AddAssertionIfNotNull(policyContext, sp.CreateWsspAsymmetricBindingAssertion(exporter, policyContext, binding));
  1907. AddAssertionIfNotNull(policyContext, sp.CreateWsspSupportingTokensAssertion(
  1908. exporter,
  1909. binding.EndpointSupportingTokenParameters.Signed,
  1910. binding.EndpointSupportingTokenParameters.SignedEncrypted,
  1911. binding.EndpointSupportingTokenParameters.Endorsing,
  1912. binding.EndpointSupportingTokenParameters.SignedEndorsing,
  1913. binding.OptionalEndpointSupportingTokenParameters.Signed,
  1914. binding.OptionalEndpointSupportingTokenParameters.SignedEncrypted,
  1915. binding.OptionalEndpointSupportingTokenParameters.Endorsing,
  1916. binding.OptionalEndpointSupportingTokenParameters.SignedEndorsing));
  1917. AddAssertionIfNotNull(policyContext, sp.CreateWsspWssAssertion(exporter, binding));
  1918. if (RequiresWsspTrust(binding))
  1919. {
  1920. AddAssertionIfNotNull(policyContext, sp.CreateWsspTrustAssertion(exporter, binding.KeyEntropyMode));
  1921. }
  1922. }
  1923. static void ExportTransportSecurityBindingElement(TransportSecurityBindingElement binding, ITransportTokenAssertionProvider transportTokenAssertionProvider, MetadataExporter exporter, PolicyConversionContext policyContext)
  1924. {
  1925. WSSecurityPolicy sp = WSSecurityPolicy.GetSecurityPolicyDriver(binding.MessageSecurityVersion);
  1926. if (transportTokenAssertionProvider == null && binding.AllowInsecureTransport)
  1927. {
  1928. if ((policyContext != null) && (policyContext.BindingElements != null))
  1929. {
  1930. foreach (BindingElement be in policyContext.BindingElements)
  1931. {
  1932. if (be is HttpTransportBindingElement)
  1933. {
  1934. transportTokenAssertionProvider = new HttpsTransportBindingElement();
  1935. break;
  1936. }
  1937. if (be is TcpTransportBindingElement)
  1938. {
  1939. transportTokenAssertionProvider = new SslStreamSecurityBindingElement();
  1940. break;
  1941. }
  1942. }
  1943. }
  1944. }
  1945. XmlElement transportTokenAssertion = transportTokenAssertionProvider.GetTransportTokenAssertion();
  1946. if (transportTokenAssertion == null)
  1947. {
  1948. if (transportTokenAssertionProvider is HttpsTransportBindingElement)
  1949. {
  1950. transportTokenAssertion = sp.CreateWsspHttpsTokenAssertion(exporter, (HttpsTransportBindingElement)transportTokenAssertionProvider);
  1951. }
  1952. if (transportTokenAssertion == null)
  1953. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoTransportTokenAssertionProvided, transportTokenAssertionProvider.GetType().ToString())));
  1954. }
  1955. AddressingVersion addressingVersion = AddressingVersion.WSAddressing10;
  1956. MessageEncodingBindingElement messageEncoderBindingElement = policyContext.BindingElements.Find<MessageEncodingBindingElement>();
  1957. if (messageEncoderBindingElement != null)
  1958. {
  1959. addressingVersion = messageEncoderBindingElement.MessageVersion.Addressing;
  1960. }
  1961. AddAssertionIfNotNull(policyContext, sp.CreateWsspTransportBindingAssertion(exporter, binding, transportTokenAssertion));
  1962. Collection<XmlElement> supportingTokenAssertions = sp.CreateWsspSupportingTokensAssertion(
  1963. exporter,
  1964. binding.EndpointSupportingTokenParameters.Signed,
  1965. binding.EndpointSupportingTokenParameters.SignedEncrypted,
  1966. binding.EndpointSupportingTokenParameters.Endorsing,
  1967. binding.EndpointSupportingTokenParameters.SignedEndorsing,
  1968. binding.OptionalEndpointSupportingTokenParameters.Signed,
  1969. binding.OptionalEndpointSupportingTokenParameters.SignedEncrypted,
  1970. binding.OptionalEndpointSupportingTokenParameters.Endorsing,
  1971. binding.OptionalEndpointSupportingTokenParameters.SignedEndorsing,
  1972. addressingVersion);
  1973. AddAssertionIfNotNull(policyContext, supportingTokenAssertions);
  1974. if (supportingTokenAssertions.Count > 0
  1975. || HasEndorsingSupportingTokensAtOperationScope(binding))
  1976. {
  1977. AddAssertionIfNotNull(policyContext, sp.CreateWsspWssAssertion(exporter, binding));
  1978. if (RequiresWsspTrust(binding))
  1979. {
  1980. AddAssertionIfNotNull(policyContext, sp.CreateWsspTrustAssertion(exporter, binding.KeyEntropyMode));
  1981. }
  1982. }
  1983. }
  1984. static bool HasEndorsingSupportingTokensAtOperationScope(SecurityBindingElement binding)
  1985. {
  1986. foreach (SupportingTokenParameters r in binding.OperationSupportingTokenParameters.Values)
  1987. {
  1988. if (r.Endorsing.Count > 0 || r.SignedEndorsing.Count > 0)
  1989. {
  1990. return true;
  1991. }
  1992. }
  1993. return false;
  1994. }
  1995. static void ExportSymmetricSecurityBindingElement(SymmetricSecurityBindingElement binding, MetadataExporter exporter, PolicyConversionContext policyContext)
  1996. {
  1997. WSSecurityPolicy sp = WSSecurityPolicy.GetSecurityPolicyDriver(binding.MessageSecurityVersion);
  1998. AddAssertionIfNotNull(policyContext, sp.CreateWsspSymmetricBindingAssertion(exporter, policyContext, binding));
  1999. AddAssertionIfNotNull(policyContext, sp.CreateWsspSupportingTokensAssertion(
  2000. exporter,
  2001. binding.EndpointSupportingTokenParameters.Signed,
  2002. binding.EndpointSupportingTokenParameters.SignedEncrypted,
  2003. binding.EndpointSupportingTokenParameters.Endorsing,
  2004. binding.EndpointSupportingTokenParameters.SignedEndorsing,
  2005. binding.OptionalEndpointSupportingTokenParameters.Signed,
  2006. binding.OptionalEndpointSupportingTokenParameters.SignedEncrypted,
  2007. binding.OptionalEndpointSupportingTokenParameters.Endorsing,
  2008. binding.OptionalEndpointSupportingTokenParameters.SignedEndorsing));
  2009. AddAssertionIfNotNull(policyContext, sp.CreateWsspWssAssertion(exporter, binding));
  2010. if (RequiresWsspTrust(binding))
  2011. {
  2012. AddAssertionIfNotNull(policyContext, sp.CreateWsspTrustAssertion(exporter, binding.KeyEntropyMode));
  2013. }
  2014. }
  2015. static void ExportMessageScopeProtectionPolicy(SecurityBindingElement security, MetadataExporter exporter, PolicyConversionContext policyContext)
  2016. {
  2017. BindingParameterCollection bindingParameters = new BindingParameterCollection();
  2018. bindingParameters.Add(ChannelProtectionRequirements.CreateFromContract(policyContext.Contract, policyContext.BindingElements.Find<SecurityBindingElement>().GetIndividualProperty<ISecurityCapabilities>(), false));
  2019. ChannelProtectionRequirements protectionRequirements = SecurityBindingElement.ComputeProtectionRequirements(security, bindingParameters, policyContext.BindingElements, true);
  2020. protectionRequirements.MakeReadOnly();
  2021. WSSecurityPolicy sp = WSSecurityPolicy.GetSecurityPolicyDriver(security.MessageSecurityVersion);
  2022. foreach (OperationDescription operation in policyContext.Contract.Operations)
  2023. {
  2024. // export policy for application messages
  2025. foreach (MessageDescription message in operation.Messages)
  2026. {
  2027. MessagePartSpecification parts;
  2028. ScopedMessagePartSpecification scopedParts;
  2029. // integrity
  2030. if (message.Direction == MessageDirection.Input)
  2031. {
  2032. scopedParts = protectionRequirements.IncomingSignatureParts;
  2033. }
  2034. else
  2035. {
  2036. scopedParts = protectionRequirements.OutgoingSignatureParts;
  2037. }
  2038. if (scopedParts.TryGetParts(message.Action, out parts))
  2039. {
  2040. AddAssertionIfNotNull(policyContext, message, sp.CreateWsspSignedPartsAssertion(parts));
  2041. }
  2042. // confidentiality
  2043. if (message.Direction == MessageDirection.Input)
  2044. {
  2045. scopedParts = protectionRequirements.IncomingEncryptionParts;
  2046. }
  2047. else
  2048. {
  2049. scopedParts = protectionRequirements.OutgoingEncryptionParts;
  2050. }
  2051. if (scopedParts.TryGetParts(message.Action, out parts))
  2052. {
  2053. AddAssertionIfNotNull(policyContext, message, sp.CreateWsspEncryptedPartsAssertion(parts));
  2054. }
  2055. }
  2056. // export policy for faults
  2057. foreach (FaultDescription fault in operation.Faults)
  2058. {
  2059. MessagePartSpecification parts;
  2060. // integrity
  2061. if (protectionRequirements.OutgoingSignatureParts.TryGetParts(fault.Action, out parts))
  2062. {
  2063. AddAssertionIfNotNull(policyContext, fault, sp.CreateWsspSignedPartsAssertion(parts));
  2064. }
  2065. // confidentiality
  2066. if (protectionRequirements.OutgoingEncryptionParts.TryGetParts(fault.Action, out parts))
  2067. {
  2068. AddAssertionIfNotNull(policyContext, fault, sp.CreateWsspEncryptedPartsAssertion(parts));
  2069. }
  2070. }
  2071. }
  2072. }
  2073. static void ExportOperationScopeSupportingTokensPolicy(SecurityBindingElement binding, MetadataExporter exporter, PolicyConversionContext policyContext)
  2074. {
  2075. WSSecurityPolicy sp = WSSecurityPolicy.GetSecurityPolicyDriver(binding.MessageSecurityVersion);
  2076. if (binding.OperationSupportingTokenParameters.Count == 0 && binding.OptionalOperationSupportingTokenParameters.Count == 0)
  2077. {
  2078. return;
  2079. }
  2080. foreach (OperationDescription operation in policyContext.Contract.Operations)
  2081. {
  2082. foreach (MessageDescription message in operation.Messages)
  2083. {
  2084. if (message.Direction == MessageDirection.Input)
  2085. {
  2086. SupportingTokenParameters requirements = null;
  2087. SupportingTokenParameters optionalRequirements = null;
  2088. if (binding.OperationSupportingTokenParameters.ContainsKey(message.Action))
  2089. {
  2090. requirements = binding.OperationSupportingTokenParameters[message.Action];
  2091. }
  2092. if (binding.OptionalOperationSupportingTokenParameters.ContainsKey(message.Action))
  2093. {
  2094. optionalRequirements = binding.OptionalOperationSupportingTokenParameters[message.Action];
  2095. }
  2096. if (requirements == null && optionalRequirements == null)
  2097. {
  2098. continue;
  2099. }
  2100. AddAssertionIfNotNull(policyContext, operation, sp.CreateWsspSupportingTokensAssertion(
  2101. exporter,
  2102. requirements == null ? null : requirements.Signed,
  2103. requirements == null ? null : requirements.SignedEncrypted,
  2104. requirements == null ? null : requirements.Endorsing,
  2105. requirements == null ? null : requirements.SignedEndorsing,
  2106. optionalRequirements == null ? null : optionalRequirements.Signed,
  2107. optionalRequirements == null ? null : optionalRequirements.SignedEncrypted,
  2108. optionalRequirements == null ? null : optionalRequirements.Endorsing,
  2109. optionalRequirements == null ? null : optionalRequirements.SignedEndorsing));
  2110. }
  2111. }
  2112. }
  2113. }
  2114. }
  2115. }