ReceiveSecurityHeader.cs 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. //----------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Security
  5. {
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.Diagnostics;
  9. using System.IdentityModel.Policy;
  10. using System.IdentityModel.Selectors;
  11. using System.IdentityModel.Tokens;
  12. using System.Security.Authentication.ExtendedProtection;
  13. using System.Security.Cryptography.X509Certificates;
  14. using System.ServiceModel;
  15. using System.ServiceModel.Channels;
  16. using System.ServiceModel.Description;
  17. using System.ServiceModel.Security.Tokens;
  18. using System.ServiceModel.Diagnostics;
  19. using System.Runtime;
  20. using System.Xml;
  21. using ISignatureValueSecurityElement = System.IdentityModel.ISignatureValueSecurityElement;
  22. using SignatureResourcePool = System.IdentityModel.SignatureResourcePool;
  23. using SignedXml = System.IdentityModel.SignedXml;
  24. using System.Runtime.Diagnostics;
  25. using System.ServiceModel.Diagnostics.Application;
  26. abstract class ReceiveSecurityHeader : SecurityHeader
  27. {
  28. // client->server symmetric binding case: only primaryTokenAuthenticator is set
  29. // server->client symmetric binding case: only primary token is set
  30. // asymmetric binding case: primaryTokenAuthenticator and wrapping token is set
  31. SecurityTokenAuthenticator primaryTokenAuthenticator;
  32. bool allowFirstTokenMismatch;
  33. SecurityToken outOfBandPrimaryToken;
  34. IList<SecurityToken> outOfBandPrimaryTokenCollection;
  35. SecurityTokenParameters primaryTokenParameters;
  36. TokenTracker primaryTokenTracker;
  37. SecurityToken wrappingToken;
  38. SecurityTokenParameters wrappingTokenParameters;
  39. SecurityToken expectedEncryptionToken;
  40. SecurityTokenParameters expectedEncryptionTokenParameters;
  41. SecurityTokenAuthenticator derivedTokenAuthenticator;
  42. // assumes that the caller has done the check for uniqueness of types
  43. IList<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators;
  44. ChannelBinding channelBinding;
  45. ExtendedProtectionPolicy extendedProtectionPolicy;
  46. bool expectEncryption = true;
  47. // caller should precompute and set expectations
  48. bool expectBasicTokens;
  49. bool expectSignedTokens;
  50. bool expectEndorsingTokens;
  51. bool expectSignature = true;
  52. bool requireSignedPrimaryToken;
  53. bool expectSignatureConfirmation;
  54. // maps from token to wire form (for basic and signed), and also tracks operations done
  55. // maps from supporting token parameter to the operations done for that token type
  56. List<TokenTracker> supportingTokenTrackers;
  57. SignatureConfirmations receivedSignatureValues;
  58. SignatureConfirmations receivedSignatureConfirmations;
  59. List<SecurityTokenAuthenticator> allowedAuthenticators;
  60. SecurityTokenAuthenticator pendingSupportingTokenAuthenticator;
  61. WrappedKeySecurityToken wrappedKeyToken;
  62. Collection<SecurityToken> basicTokens;
  63. Collection<SecurityToken> signedTokens;
  64. Collection<SecurityToken> endorsingTokens;
  65. Collection<SecurityToken> signedEndorsingTokens;
  66. Dictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>> tokenPoliciesMapping;
  67. List<SecurityTokenAuthenticator> wrappedKeyAuthenticator;
  68. SecurityTimestamp timestamp;
  69. SecurityHeaderTokenResolver universalTokenResolver;
  70. SecurityHeaderTokenResolver primaryTokenResolver;
  71. ReadOnlyCollection<SecurityTokenResolver> outOfBandTokenResolver;
  72. SecurityTokenResolver combinedUniversalTokenResolver;
  73. SecurityTokenResolver combinedPrimaryTokenResolver;
  74. readonly int headerIndex;
  75. XmlAttributeHolder[] securityElementAttributes;
  76. OrderTracker orderTracker = new OrderTracker();
  77. OperationTracker signatureTracker = new OperationTracker();
  78. OperationTracker encryptionTracker = new OperationTracker();
  79. ReceiveSecurityHeaderElementManager elementManager;
  80. int maxDerivedKeys;
  81. int numDerivedKeys;
  82. int maxDerivedKeyLength;
  83. bool enforceDerivedKeyRequirement = true;
  84. NonceCache nonceCache;
  85. TimeSpan replayWindow;
  86. TimeSpan clockSkew;
  87. byte[] primarySignatureValue;
  88. TimeoutHelper timeoutHelper;
  89. SecurityVerifiedMessage securityVerifiedMessage;
  90. long maxReceivedMessageSize = TransportDefaults.MaxReceivedMessageSize;
  91. XmlDictionaryReaderQuotas readerQuotas;
  92. MessageProtectionOrder protectionOrder;
  93. bool hasAtLeastOneSupportingTokenExpectedToBeSigned;
  94. bool hasEndorsingOrSignedEndorsingSupportingTokens;
  95. SignatureResourcePool resourcePool;
  96. bool replayDetectionEnabled = false;
  97. bool hasAtLeastOneItemInsideSecurityHeaderEncrypted = false;
  98. const int AppendPosition = -1;
  99. EventTraceActivity eventTraceActivity;
  100. protected ReceiveSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay,
  101. SecurityStandardsManager standardsManager,
  102. SecurityAlgorithmSuite algorithmSuite,
  103. int headerIndex,
  104. MessageDirection direction)
  105. : base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, direction)
  106. {
  107. this.headerIndex = headerIndex;
  108. this.elementManager = new ReceiveSecurityHeaderElementManager(this);
  109. }
  110. public Collection<SecurityToken> BasicSupportingTokens
  111. {
  112. get
  113. {
  114. return this.basicTokens;
  115. }
  116. }
  117. public Collection<SecurityToken> SignedSupportingTokens
  118. {
  119. get
  120. {
  121. return this.signedTokens;
  122. }
  123. }
  124. public Collection<SecurityToken> EndorsingSupportingTokens
  125. {
  126. get
  127. {
  128. return this.endorsingTokens;
  129. }
  130. }
  131. public ReceiveSecurityHeaderElementManager ElementManager
  132. {
  133. get
  134. {
  135. return this.elementManager;
  136. }
  137. }
  138. public Collection<SecurityToken> SignedEndorsingSupportingTokens
  139. {
  140. get
  141. {
  142. return this.signedEndorsingTokens;
  143. }
  144. }
  145. public SecurityTokenAuthenticator DerivedTokenAuthenticator
  146. {
  147. get
  148. {
  149. return this.derivedTokenAuthenticator;
  150. }
  151. set
  152. {
  153. ThrowIfProcessingStarted();
  154. this.derivedTokenAuthenticator = value;
  155. }
  156. }
  157. public List<SecurityTokenAuthenticator> WrappedKeySecurityTokenAuthenticator
  158. {
  159. get
  160. {
  161. return this.wrappedKeyAuthenticator;
  162. }
  163. set
  164. {
  165. ThrowIfProcessingStarted();
  166. this.wrappedKeyAuthenticator = value;
  167. }
  168. }
  169. public bool EnforceDerivedKeyRequirement
  170. {
  171. get
  172. {
  173. return this.enforceDerivedKeyRequirement;
  174. }
  175. set
  176. {
  177. ThrowIfProcessingStarted();
  178. this.enforceDerivedKeyRequirement = value;
  179. }
  180. }
  181. public byte[] PrimarySignatureValue
  182. {
  183. get { return this.primarySignatureValue; }
  184. }
  185. public bool EncryptBeforeSignMode
  186. {
  187. get { return this.orderTracker.EncryptBeforeSignMode; }
  188. }
  189. public SecurityToken EncryptionToken
  190. {
  191. get { return this.encryptionTracker.Token; }
  192. }
  193. public bool ExpectBasicTokens
  194. {
  195. get { return this.expectBasicTokens; }
  196. set
  197. {
  198. ThrowIfProcessingStarted();
  199. this.expectBasicTokens = value;
  200. }
  201. }
  202. public bool ReplayDetectionEnabled
  203. {
  204. get { return this.replayDetectionEnabled; }
  205. set
  206. {
  207. ThrowIfProcessingStarted();
  208. this.replayDetectionEnabled = value;
  209. }
  210. }
  211. public bool ExpectEncryption
  212. {
  213. get { return this.expectEncryption; }
  214. set
  215. {
  216. ThrowIfProcessingStarted();
  217. this.expectEncryption = value;
  218. }
  219. }
  220. public bool ExpectSignature
  221. {
  222. get { return this.expectSignature; }
  223. set
  224. {
  225. ThrowIfProcessingStarted();
  226. this.expectSignature = value;
  227. }
  228. }
  229. public bool ExpectSignatureConfirmation
  230. {
  231. get { return this.expectSignatureConfirmation; }
  232. set
  233. {
  234. ThrowIfProcessingStarted();
  235. this.expectSignatureConfirmation = value;
  236. }
  237. }
  238. public bool ExpectSignedTokens
  239. {
  240. get { return this.expectSignedTokens; }
  241. set
  242. {
  243. ThrowIfProcessingStarted();
  244. this.expectSignedTokens = value;
  245. }
  246. }
  247. public bool RequireSignedPrimaryToken
  248. {
  249. get { return this.requireSignedPrimaryToken; }
  250. set
  251. {
  252. ThrowIfProcessingStarted();
  253. this.requireSignedPrimaryToken = value;
  254. }
  255. }
  256. public bool ExpectEndorsingTokens
  257. {
  258. get { return this.expectEndorsingTokens; }
  259. set
  260. {
  261. ThrowIfProcessingStarted();
  262. this.expectEndorsingTokens = value;
  263. }
  264. }
  265. public bool HasAtLeastOneItemInsideSecurityHeaderEncrypted
  266. {
  267. get { return this.hasAtLeastOneItemInsideSecurityHeaderEncrypted; }
  268. set { this.hasAtLeastOneItemInsideSecurityHeaderEncrypted = value; }
  269. }
  270. public SecurityHeaderTokenResolver PrimaryTokenResolver
  271. {
  272. get
  273. {
  274. return this.primaryTokenResolver;
  275. }
  276. }
  277. public SecurityTokenResolver CombinedUniversalTokenResolver
  278. {
  279. get { return this.combinedUniversalTokenResolver; }
  280. }
  281. public SecurityTokenResolver CombinedPrimaryTokenResolver
  282. {
  283. get { return this.combinedPrimaryTokenResolver; }
  284. }
  285. protected EventTraceActivity EventTraceActivity
  286. {
  287. get
  288. {
  289. if (this.eventTraceActivity == null && FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
  290. {
  291. this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
  292. }
  293. return this.eventTraceActivity;
  294. }
  295. }
  296. protected void VerifySignatureEncryption()
  297. {
  298. if ((this.protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature) &&
  299. (!this.orderTracker.AllSignaturesEncrypted))
  300. {
  301. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  302. SR.GetString(SR.PrimarySignatureIsRequiredToBeEncrypted)));
  303. }
  304. }
  305. internal int HeaderIndex
  306. {
  307. get { return this.headerIndex; }
  308. }
  309. internal long MaxReceivedMessageSize
  310. {
  311. get
  312. {
  313. return this.maxReceivedMessageSize;
  314. }
  315. set
  316. {
  317. ThrowIfProcessingStarted();
  318. this.maxReceivedMessageSize = value;
  319. }
  320. }
  321. internal XmlDictionaryReaderQuotas ReaderQuotas
  322. {
  323. get { return this.readerQuotas; }
  324. set
  325. {
  326. ThrowIfProcessingStarted();
  327. if (value == null)
  328. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
  329. this.readerQuotas = value;
  330. }
  331. }
  332. public override string Name
  333. {
  334. get { return this.StandardsManager.SecurityVersion.HeaderName.Value; }
  335. }
  336. public override string Namespace
  337. {
  338. get { return this.StandardsManager.SecurityVersion.HeaderNamespace.Value; }
  339. }
  340. public Message ProcessedMessage
  341. {
  342. get { return this.Message; }
  343. }
  344. public MessagePartSpecification RequiredEncryptionParts
  345. {
  346. get { return this.encryptionTracker.Parts; }
  347. set
  348. {
  349. ThrowIfProcessingStarted();
  350. if (value == null)
  351. {
  352. throw TraceUtility.ThrowHelperError(new ArgumentNullException("value"), this.Message);
  353. }
  354. if (!value.IsReadOnly)
  355. {
  356. throw TraceUtility.ThrowHelperError(new InvalidOperationException(
  357. SR.GetString(SR.MessagePartSpecificationMustBeImmutable)), this.Message);
  358. }
  359. this.encryptionTracker.Parts = value;
  360. }
  361. }
  362. public MessagePartSpecification RequiredSignatureParts
  363. {
  364. get { return this.signatureTracker.Parts; }
  365. set
  366. {
  367. ThrowIfProcessingStarted();
  368. if (value == null)
  369. {
  370. throw TraceUtility.ThrowHelperError(new ArgumentNullException("value"), this.Message);
  371. }
  372. if (!value.IsReadOnly)
  373. {
  374. throw TraceUtility.ThrowHelperError(new InvalidOperationException(
  375. SR.GetString(SR.MessagePartSpecificationMustBeImmutable)), this.Message);
  376. }
  377. this.signatureTracker.Parts = value;
  378. }
  379. }
  380. protected SignatureResourcePool ResourcePool
  381. {
  382. get
  383. {
  384. if (this.resourcePool == null)
  385. {
  386. this.resourcePool = new SignatureResourcePool();
  387. }
  388. return this.resourcePool;
  389. }
  390. }
  391. internal SecurityVerifiedMessage SecurityVerifiedMessage
  392. {
  393. get
  394. {
  395. return this.securityVerifiedMessage;
  396. }
  397. }
  398. public SecurityToken SignatureToken
  399. {
  400. get { return this.signatureTracker.Token; }
  401. }
  402. public Dictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>> SecurityTokenAuthorizationPoliciesMapping
  403. {
  404. get
  405. {
  406. if (this.tokenPoliciesMapping == null)
  407. {
  408. this.tokenPoliciesMapping = new Dictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>>();
  409. }
  410. return this.tokenPoliciesMapping;
  411. }
  412. }
  413. public SecurityTimestamp Timestamp
  414. {
  415. get { return this.timestamp; }
  416. }
  417. public int MaxDerivedKeyLength
  418. {
  419. get
  420. {
  421. return this.maxDerivedKeyLength;
  422. }
  423. }
  424. internal XmlDictionaryReader CreateSecurityHeaderReader()
  425. {
  426. return this.securityVerifiedMessage.GetReaderAtSecurityHeader();
  427. }
  428. public SignatureConfirmations GetSentSignatureConfirmations()
  429. {
  430. return this.receivedSignatureConfirmations;
  431. }
  432. public void ConfigureSymmetricBindingServerReceiveHeader(SecurityTokenAuthenticator primaryTokenAuthenticator, SecurityTokenParameters primaryTokenParameters, IList<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators)
  433. {
  434. this.primaryTokenAuthenticator = primaryTokenAuthenticator;
  435. this.primaryTokenParameters = primaryTokenParameters;
  436. this.supportingTokenAuthenticators = supportingTokenAuthenticators;
  437. }
  438. // encrypted key case
  439. public void ConfigureSymmetricBindingServerReceiveHeader(SecurityToken wrappingToken, SecurityTokenParameters wrappingTokenParameters, IList<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators)
  440. {
  441. this.wrappingToken = wrappingToken;
  442. this.wrappingTokenParameters = wrappingTokenParameters;
  443. this.supportingTokenAuthenticators = supportingTokenAuthenticators;
  444. }
  445. public void ConfigureAsymmetricBindingServerReceiveHeader(SecurityTokenAuthenticator primaryTokenAuthenticator, SecurityTokenParameters primaryTokenParameters, SecurityToken wrappingToken, SecurityTokenParameters wrappingTokenParameters, IList<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators)
  446. {
  447. this.primaryTokenAuthenticator = primaryTokenAuthenticator;
  448. this.primaryTokenParameters = primaryTokenParameters;
  449. this.wrappingToken = wrappingToken;
  450. this.wrappingTokenParameters = wrappingTokenParameters;
  451. this.supportingTokenAuthenticators = supportingTokenAuthenticators;
  452. }
  453. public void ConfigureTransportBindingServerReceiveHeader(IList<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators)
  454. {
  455. this.supportingTokenAuthenticators = supportingTokenAuthenticators;
  456. }
  457. public void ConfigureAsymmetricBindingClientReceiveHeader(SecurityToken primaryToken, SecurityTokenParameters primaryTokenParameters, SecurityToken encryptionToken, SecurityTokenParameters encryptionTokenParameters, SecurityTokenAuthenticator primaryTokenAuthenticator)
  458. {
  459. this.outOfBandPrimaryToken = primaryToken;
  460. this.primaryTokenParameters = primaryTokenParameters;
  461. this.primaryTokenAuthenticator = primaryTokenAuthenticator;
  462. this.allowFirstTokenMismatch = primaryTokenAuthenticator != null;
  463. if (encryptionToken != null && !SecurityUtils.HasSymmetricSecurityKey(encryptionToken))
  464. {
  465. this.wrappingToken = encryptionToken;
  466. this.wrappingTokenParameters = encryptionTokenParameters;
  467. }
  468. else
  469. {
  470. this.expectedEncryptionToken = encryptionToken;
  471. this.expectedEncryptionTokenParameters = encryptionTokenParameters;
  472. }
  473. }
  474. public void ConfigureSymmetricBindingClientReceiveHeader(SecurityToken primaryToken, SecurityTokenParameters primaryTokenParameters)
  475. {
  476. this.outOfBandPrimaryToken = primaryToken;
  477. this.primaryTokenParameters = primaryTokenParameters;
  478. }
  479. public void ConfigureSymmetricBindingClientReceiveHeader(IList<SecurityToken> primaryTokens, SecurityTokenParameters primaryTokenParameters)
  480. {
  481. this.outOfBandPrimaryTokenCollection = primaryTokens;
  482. this.primaryTokenParameters = primaryTokenParameters;
  483. }
  484. public void ConfigureOutOfBandTokenResolver(ReadOnlyCollection<SecurityTokenResolver> outOfBandResolvers)
  485. {
  486. if (outOfBandResolvers == null)
  487. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("outOfBandResolvers");
  488. if (outOfBandResolvers.Count == 0)
  489. {
  490. return;
  491. }
  492. this.outOfBandTokenResolver = outOfBandResolvers;
  493. }
  494. protected abstract EncryptedData ReadSecurityHeaderEncryptedItem(XmlDictionaryReader reader, bool readXmlreferenceKeyInfoClause);
  495. protected abstract byte[] DecryptSecurityHeaderElement(EncryptedData encryptedData, WrappedKeySecurityToken wrappedKeyToken, out SecurityToken encryptionToken);
  496. protected abstract WrappedKeySecurityToken DecryptWrappedKey(XmlDictionaryReader reader);
  497. public SignatureConfirmations GetSentSignatureValues()
  498. {
  499. return this.receivedSignatureValues;
  500. }
  501. protected abstract bool IsReaderAtEncryptedKey(XmlDictionaryReader reader);
  502. protected abstract bool IsReaderAtEncryptedData(XmlDictionaryReader reader);
  503. protected abstract bool IsReaderAtReferenceList(XmlDictionaryReader reader);
  504. protected abstract bool IsReaderAtSignature(XmlDictionaryReader reader);
  505. protected abstract bool IsReaderAtSecurityTokenReference(XmlDictionaryReader reader);
  506. protected abstract void OnDecryptionOfSecurityHeaderItemRequiringReferenceListEntry(string id);
  507. void MarkHeaderAsUnderstood()
  508. {
  509. // header decryption does not reorder or delete headers
  510. MessageHeaderInfo header = this.Message.Headers[this.headerIndex];
  511. Fx.Assert(header.Name == this.Name && header.Namespace == this.Namespace && header.Actor == this.Actor, "security header index mismatch");
  512. Message.Headers.UnderstoodHeaders.Add(header);
  513. }
  514. protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
  515. {
  516. this.StandardsManager.SecurityVersion.WriteStartHeader(writer);
  517. XmlAttributeHolder[] attributes = this.securityElementAttributes;
  518. for (int i = 0; i < attributes.Length; ++i)
  519. {
  520. writer.WriteAttributeString(attributes[i].Prefix, attributes[i].LocalName, attributes[i].NamespaceUri, attributes[i].Value);
  521. }
  522. }
  523. protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
  524. {
  525. XmlDictionaryReader securityHeaderReader = GetReaderAtSecurityHeader();
  526. securityHeaderReader.ReadStartElement();
  527. for (int i = 0; i < this.ElementManager.Count; ++i)
  528. {
  529. ReceiveSecurityHeaderEntry entry;
  530. this.ElementManager.GetElementEntry(i, out entry);
  531. XmlDictionaryReader reader = null;
  532. if (entry.encrypted)
  533. {
  534. reader = this.ElementManager.GetReader(i, false);
  535. writer.WriteNode(reader, false);
  536. reader.Close();
  537. securityHeaderReader.Skip();
  538. }
  539. else
  540. {
  541. writer.WriteNode(securityHeaderReader, false);
  542. }
  543. }
  544. securityHeaderReader.Close();
  545. }
  546. XmlDictionaryReader GetReaderAtSecurityHeader()
  547. {
  548. XmlDictionaryReader reader = this.SecurityVerifiedMessage.GetReaderAtFirstHeader();
  549. for (int i = 0; i < this.HeaderIndex; ++i)
  550. {
  551. reader.Skip();
  552. }
  553. return reader;
  554. }
  555. Collection<SecurityToken> EnsureSupportingTokens(ref Collection<SecurityToken> list)
  556. {
  557. if (list == null)
  558. list = new Collection<SecurityToken>();
  559. return list;
  560. }
  561. void VerifySupportingToken(TokenTracker tracker)
  562. {
  563. if (tracker == null)
  564. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tracker");
  565. Fx.Assert(tracker.spec != null, "Supporting token trackers cannot have null specification.");
  566. SupportingTokenAuthenticatorSpecification spec = tracker.spec;
  567. if (tracker.token == null)
  568. {
  569. if (spec.IsTokenOptional)
  570. return;
  571. else
  572. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingTokenNotProvided, spec.TokenParameters, spec.SecurityTokenAttachmentMode)));
  573. }
  574. switch (spec.SecurityTokenAttachmentMode)
  575. {
  576. case SecurityTokenAttachmentMode.Endorsing:
  577. if (!tracker.IsEndorsing)
  578. {
  579. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotEndorsing, spec.TokenParameters)));
  580. }
  581. if (this.EnforceDerivedKeyRequirement && spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey && !tracker.IsDerivedFrom)
  582. {
  583. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingSignatureIsNotDerivedFrom, spec.TokenParameters)));
  584. }
  585. EnsureSupportingTokens(ref endorsingTokens).Add(tracker.token);
  586. break;
  587. case SecurityTokenAttachmentMode.Signed:
  588. if (!tracker.IsSigned && this.RequireMessageProtection)
  589. {
  590. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotSigned, spec.TokenParameters)));
  591. }
  592. EnsureSupportingTokens(ref signedTokens).Add(tracker.token);
  593. break;
  594. case SecurityTokenAttachmentMode.SignedEncrypted:
  595. if (!tracker.IsSigned && this.RequireMessageProtection)
  596. {
  597. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotSigned, spec.TokenParameters)));
  598. }
  599. if (!tracker.IsEncrypted && this.RequireMessageProtection)
  600. {
  601. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotEncrypted, spec.TokenParameters)));
  602. }
  603. EnsureSupportingTokens(ref basicTokens).Add(tracker.token);
  604. break;
  605. case SecurityTokenAttachmentMode.SignedEndorsing:
  606. if (!tracker.IsSigned && this.RequireMessageProtection)
  607. {
  608. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotSigned, spec.TokenParameters)));
  609. }
  610. if (!tracker.IsEndorsing)
  611. {
  612. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotEndorsing, spec.TokenParameters)));
  613. }
  614. if (this.EnforceDerivedKeyRequirement && spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey && !tracker.IsDerivedFrom)
  615. {
  616. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SupportingSignatureIsNotDerivedFrom, spec.TokenParameters)));
  617. }
  618. EnsureSupportingTokens(ref signedEndorsingTokens).Add(tracker.token);
  619. break;
  620. default:
  621. Fx.Assert("Unknown token attachment mode " + spec.SecurityTokenAttachmentMode);
  622. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnknownTokenAttachmentMode, spec.SecurityTokenAttachmentMode)));
  623. }
  624. }
  625. // replay detection done if enableReplayDetection is set to true.
  626. public void SetTimeParameters(NonceCache nonceCache, TimeSpan replayWindow, TimeSpan clockSkew)
  627. {
  628. this.nonceCache = nonceCache;
  629. this.replayWindow = replayWindow;
  630. this.clockSkew = clockSkew;
  631. }
  632. public void Process(TimeSpan timeout, ChannelBinding channelBinding, ExtendedProtectionPolicy extendedProtectionPolicy)
  633. {
  634. Fx.Assert(this.ReaderQuotas != null, "Reader quotas must be set before processing");
  635. MessageProtectionOrder actualProtectionOrder = this.protectionOrder;
  636. bool wasProtectionOrderDowngraded = false;
  637. if (this.protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature)
  638. {
  639. if (this.RequiredEncryptionParts == null || !this.RequiredEncryptionParts.IsBodyIncluded)
  640. {
  641. // Let's downgrade for now. If after signature verification we find a header that
  642. // is signed and encrypted, we will check for signature encryption too.
  643. actualProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
  644. wasProtectionOrderDowngraded = true;
  645. }
  646. }
  647. this.channelBinding = channelBinding;
  648. this.extendedProtectionPolicy = extendedProtectionPolicy;
  649. this.orderTracker.SetRequiredProtectionOrder(actualProtectionOrder);
  650. SetProcessingStarted();
  651. this.timeoutHelper = new TimeoutHelper(timeout);
  652. this.Message = this.securityVerifiedMessage = new SecurityVerifiedMessage(this.Message, this);
  653. XmlDictionaryReader reader = CreateSecurityHeaderReader();
  654. reader.MoveToStartElement();
  655. if (reader.IsEmptyElement)
  656. {
  657. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SecurityHeaderIsEmpty)), this.Message);
  658. }
  659. if (this.RequireMessageProtection)
  660. {
  661. this.securityElementAttributes = XmlAttributeHolder.ReadAttributes(reader);
  662. }
  663. else
  664. {
  665. this.securityElementAttributes = XmlAttributeHolder.emptyArray;
  666. }
  667. reader.ReadStartElement();
  668. if (this.primaryTokenParameters != null)
  669. {
  670. this.primaryTokenTracker = new TokenTracker(null, this.outOfBandPrimaryToken, this.allowFirstTokenMismatch);
  671. }
  672. // universalTokenResolver is used for resolving tokens
  673. universalTokenResolver = new SecurityHeaderTokenResolver(this);
  674. // primary token resolver is used for resolving primary signature and decryption
  675. primaryTokenResolver = new SecurityHeaderTokenResolver(this);
  676. if (this.outOfBandPrimaryToken != null)
  677. {
  678. universalTokenResolver.Add(this.outOfBandPrimaryToken, SecurityTokenReferenceStyle.External, this.primaryTokenParameters);
  679. primaryTokenResolver.Add(this.outOfBandPrimaryToken, SecurityTokenReferenceStyle.External, this.primaryTokenParameters);
  680. }
  681. else if (this.outOfBandPrimaryTokenCollection != null)
  682. {
  683. for (int i = 0; i < this.outOfBandPrimaryTokenCollection.Count; ++i)
  684. {
  685. universalTokenResolver.Add(this.outOfBandPrimaryTokenCollection[i], SecurityTokenReferenceStyle.External, this.primaryTokenParameters);
  686. primaryTokenResolver.Add(this.outOfBandPrimaryTokenCollection[i], SecurityTokenReferenceStyle.External, this.primaryTokenParameters);
  687. }
  688. }
  689. if (this.wrappingToken != null)
  690. {
  691. universalTokenResolver.ExpectedWrapper = this.wrappingToken;
  692. universalTokenResolver.ExpectedWrapperTokenParameters = this.wrappingTokenParameters;
  693. primaryTokenResolver.ExpectedWrapper = this.wrappingToken;
  694. primaryTokenResolver.ExpectedWrapperTokenParameters = this.wrappingTokenParameters;
  695. }
  696. else if (expectedEncryptionToken != null)
  697. {
  698. universalTokenResolver.Add(expectedEncryptionToken, SecurityTokenReferenceStyle.External, expectedEncryptionTokenParameters);
  699. primaryTokenResolver.Add(expectedEncryptionToken, SecurityTokenReferenceStyle.External, expectedEncryptionTokenParameters);
  700. }
  701. if (this.outOfBandTokenResolver == null)
  702. {
  703. this.combinedUniversalTokenResolver = this.universalTokenResolver;
  704. this.combinedPrimaryTokenResolver = this.primaryTokenResolver;
  705. }
  706. else
  707. {
  708. this.combinedUniversalTokenResolver = new AggregateSecurityHeaderTokenResolver(this.universalTokenResolver, this.outOfBandTokenResolver);
  709. this.combinedPrimaryTokenResolver = new AggregateSecurityHeaderTokenResolver(this.primaryTokenResolver, this.outOfBandTokenResolver);
  710. }
  711. allowedAuthenticators = new List<SecurityTokenAuthenticator>();
  712. if (this.primaryTokenAuthenticator != null)
  713. {
  714. allowedAuthenticators.Add(this.primaryTokenAuthenticator);
  715. }
  716. if (this.DerivedTokenAuthenticator != null)
  717. {
  718. allowedAuthenticators.Add(this.DerivedTokenAuthenticator);
  719. }
  720. pendingSupportingTokenAuthenticator = null;
  721. int numSupportingTokensRequiringDerivation = 0;
  722. if (this.supportingTokenAuthenticators != null && this.supportingTokenAuthenticators.Count > 0)
  723. {
  724. this.supportingTokenTrackers = new List<TokenTracker>(this.supportingTokenAuthenticators.Count);
  725. for (int i = 0; i < this.supportingTokenAuthenticators.Count; ++i)
  726. {
  727. SupportingTokenAuthenticatorSpecification spec = this.supportingTokenAuthenticators[i];
  728. switch (spec.SecurityTokenAttachmentMode)
  729. {
  730. case SecurityTokenAttachmentMode.Endorsing:
  731. this.hasEndorsingOrSignedEndorsingSupportingTokens = true;
  732. break;
  733. case SecurityTokenAttachmentMode.Signed:
  734. this.hasAtLeastOneSupportingTokenExpectedToBeSigned = true;
  735. break;
  736. case SecurityTokenAttachmentMode.SignedEndorsing:
  737. this.hasEndorsingOrSignedEndorsingSupportingTokens = true;
  738. this.hasAtLeastOneSupportingTokenExpectedToBeSigned = true;
  739. break;
  740. case SecurityTokenAttachmentMode.SignedEncrypted:
  741. this.hasAtLeastOneSupportingTokenExpectedToBeSigned = true;
  742. break;
  743. }
  744. if ((this.primaryTokenAuthenticator != null) && (this.primaryTokenAuthenticator.GetType().Equals(spec.TokenAuthenticator.GetType())))
  745. {
  746. pendingSupportingTokenAuthenticator = spec.TokenAuthenticator;
  747. }
  748. else
  749. {
  750. allowedAuthenticators.Add(spec.TokenAuthenticator);
  751. }
  752. if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey &&
  753. (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing))
  754. {
  755. ++numSupportingTokensRequiringDerivation;
  756. }
  757. this.supportingTokenTrackers.Add(new TokenTracker(spec));
  758. }
  759. }
  760. if (this.DerivedTokenAuthenticator != null)
  761. {
  762. // we expect key derivation. Compute quotas for derived keys
  763. int maxKeyDerivationLengthInBits = this.AlgorithmSuite.DefaultEncryptionKeyDerivationLength >= this.AlgorithmSuite.DefaultSignatureKeyDerivationLength ?
  764. this.AlgorithmSuite.DefaultEncryptionKeyDerivationLength : this.AlgorithmSuite.DefaultSignatureKeyDerivationLength;
  765. this.maxDerivedKeyLength = maxKeyDerivationLengthInBits / 8;
  766. // the upper bound of derived keys is (1 for primary signature + 1 for encryption + supporting token signatures requiring derivation)*2
  767. // the multiplication by 2 is to take care of interop scenarios that may arise that require more derived keys than the lower bound.
  768. this.maxDerivedKeys = (1 + 1 + numSupportingTokensRequiringDerivation) * 2;
  769. }
  770. SecurityHeaderElementInferenceEngine engine = SecurityHeaderElementInferenceEngine.GetInferenceEngine(this.Layout);
  771. engine.ExecuteProcessingPasses(this, reader);
  772. if (this.RequireMessageProtection)
  773. {
  774. this.ElementManager.EnsureAllRequiredSecurityHeaderTargetsWereProtected();
  775. ExecuteMessageProtectionPass(this.hasAtLeastOneSupportingTokenExpectedToBeSigned);
  776. if (this.RequiredSignatureParts != null && this.SignatureToken == null)
  777. {
  778. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredSignatureMissing)), this.Message);
  779. }
  780. }
  781. EnsureDecryptionComplete();
  782. this.signatureTracker.SetDerivationSourceIfRequired();
  783. this.encryptionTracker.SetDerivationSourceIfRequired();
  784. if (this.EncryptionToken != null)
  785. {
  786. if (wrappingToken != null)
  787. {
  788. if (!(this.EncryptionToken is WrappedKeySecurityToken) || ((WrappedKeySecurityToken)this.EncryptionToken).WrappingToken != this.wrappingToken)
  789. {
  790. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, this.wrappingToken)));
  791. }
  792. }
  793. else if (expectedEncryptionToken != null)
  794. {
  795. if (this.EncryptionToken != expectedEncryptionToken)
  796. {
  797. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.MessageWasNotEncryptedWithTheRequiredEncryptingToken)));
  798. }
  799. }
  800. else if (this.SignatureToken != null && this.EncryptionToken != this.SignatureToken)
  801. {
  802. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SignatureAndEncryptionTokenMismatch, this.SignatureToken, this.EncryptionToken)));
  803. }
  804. }
  805. // ensure that the primary signature was signed with derived keys if required
  806. if (this.EnforceDerivedKeyRequirement)
  807. {
  808. if (this.SignatureToken != null)
  809. {
  810. if (this.primaryTokenParameters != null)
  811. {
  812. if (this.primaryTokenParameters.RequireDerivedKeys && !this.primaryTokenParameters.HasAsymmetricKey && !this.primaryTokenTracker.IsDerivedFrom)
  813. {
  814. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.PrimarySignatureWasNotSignedByDerivedKey, this.primaryTokenParameters)));
  815. }
  816. }
  817. else if (this.wrappingTokenParameters != null && this.wrappingTokenParameters.RequireDerivedKeys)
  818. {
  819. if (!this.signatureTracker.IsDerivedToken)
  820. {
  821. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.PrimarySignatureWasNotSignedByDerivedWrappedKey, this.wrappingTokenParameters)));
  822. }
  823. }
  824. }
  825. // verify that the encryption is using key derivation
  826. if (this.EncryptionToken != null)
  827. {
  828. if (wrappingTokenParameters != null)
  829. {
  830. if (wrappingTokenParameters.RequireDerivedKeys && !this.encryptionTracker.IsDerivedToken)
  831. {
  832. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.MessageWasNotEncryptedByDerivedWrappedKey, this.wrappingTokenParameters)));
  833. }
  834. }
  835. else if (expectedEncryptionTokenParameters != null)
  836. {
  837. if (expectedEncryptionTokenParameters.RequireDerivedKeys && !this.encryptionTracker.IsDerivedToken)
  838. {
  839. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.MessageWasNotEncryptedByDerivedEncryptionToken, this.expectedEncryptionTokenParameters)));
  840. }
  841. }
  842. else if (primaryTokenParameters != null && !primaryTokenParameters.HasAsymmetricKey && primaryTokenParameters.RequireDerivedKeys && !this.encryptionTracker.IsDerivedToken)
  843. {
  844. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.MessageWasNotEncryptedByDerivedEncryptionToken, this.primaryTokenParameters)));
  845. }
  846. }
  847. }
  848. if (wasProtectionOrderDowngraded && (this.BasicSupportingTokens != null) && (this.BasicSupportingTokens.Count > 0))
  849. {
  850. // Basic tokens are always signed and encrypted. So check if Signatures
  851. // are encrypted as well.
  852. this.VerifySignatureEncryption();
  853. }
  854. // verify all supporting token parameters have their requirements met
  855. if (this.supportingTokenTrackers != null)
  856. {
  857. for (int i = 0; i < this.supportingTokenTrackers.Count; ++i)
  858. {
  859. VerifySupportingToken(this.supportingTokenTrackers[i]);
  860. }
  861. }
  862. if (this.replayDetectionEnabled)
  863. {
  864. if (this.timestamp == null)
  865. {
  866. throw TraceUtility.ThrowHelperError(new MessageSecurityException(
  867. SR.GetString(SR.NoTimestampAvailableInSecurityHeaderToDoReplayDetection)), this.Message);
  868. }
  869. if (this.primarySignatureValue == null)
  870. {
  871. throw TraceUtility.ThrowHelperError(new MessageSecurityException(
  872. SR.GetString(SR.NoSignatureAvailableInSecurityHeaderToDoReplayDetection)), this.Message);
  873. }
  874. AddNonce(this.nonceCache, this.primarySignatureValue);
  875. // if replay detection is on, redo creation range checks to ensure full coverage
  876. this.timestamp.ValidateFreshness(this.replayWindow, this.clockSkew);
  877. }
  878. if (this.ExpectSignatureConfirmation)
  879. {
  880. this.ElementManager.VerifySignatureConfirmationWasFound();
  881. }
  882. MarkHeaderAsUnderstood();
  883. }
  884. static void AddNonce(NonceCache cache, byte[] nonce)
  885. {
  886. if (!cache.TryAddNonce(nonce))
  887. {
  888. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.InvalidOrReplayedNonce), true));
  889. }
  890. }
  891. static void CheckNonce(NonceCache cache, byte[] nonce)
  892. {
  893. if (cache.CheckNonce(nonce))
  894. {
  895. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.InvalidOrReplayedNonce), true));
  896. }
  897. }
  898. protected abstract void EnsureDecryptionComplete();
  899. protected abstract void ExecuteMessageProtectionPass(bool hasAtLeastOneSupportingTokenExpectedToBeSigned);
  900. internal void ExecuteSignatureEncryptionProcessingPass()
  901. {
  902. for (int position = 0; position < this.elementManager.Count; position++)
  903. {
  904. ReceiveSecurityHeaderEntry entry;
  905. this.elementManager.GetElementEntry(position, out entry);
  906. switch (entry.elementCategory)
  907. {
  908. case ReceiveSecurityHeaderElementCategory.Signature:
  909. if (entry.bindingMode == ReceiveSecurityHeaderBindingModes.Primary)
  910. {
  911. ProcessPrimarySignature((SignedXml)entry.element, entry.encrypted);
  912. }
  913. else
  914. {
  915. ProcessSupportingSignature((SignedXml)entry.element, entry.encrypted);
  916. }
  917. break;
  918. case ReceiveSecurityHeaderElementCategory.ReferenceList:
  919. ProcessReferenceList((ReferenceList)entry.element);
  920. break;
  921. case ReceiveSecurityHeaderElementCategory.Token:
  922. WrappedKeySecurityToken wrappedKeyToken = entry.element as WrappedKeySecurityToken;
  923. if ((wrappedKeyToken != null) && (wrappedKeyToken.ReferenceList != null))
  924. {
  925. Fx.Assert(this.Layout != SecurityHeaderLayout.Strict, "Invalid Calling sequence. This method assumes it will be called only during Lax mode.");
  926. // ExecuteSignatureEncryptionProcessingPass is called only durng Lax mode. In this
  927. // case when we have a EncryptedKey with a ReferencList inside it, we would not
  928. // have processed the ReferenceList during reading pass. Process this here.
  929. ProcessReferenceList(wrappedKeyToken.ReferenceList, wrappedKeyToken);
  930. }
  931. break;
  932. case ReceiveSecurityHeaderElementCategory.Timestamp:
  933. case ReceiveSecurityHeaderElementCategory.EncryptedKey:
  934. case ReceiveSecurityHeaderElementCategory.EncryptedData:
  935. case ReceiveSecurityHeaderElementCategory.SignatureConfirmation:
  936. case ReceiveSecurityHeaderElementCategory.SecurityTokenReference:
  937. // no op
  938. break;
  939. default:
  940. Fx.Assert("invalid element category");
  941. break;
  942. }
  943. }
  944. }
  945. internal void ExecuteSubheaderDecryptionPass()
  946. {
  947. for (int position = 0; position < this.elementManager.Count; position++)
  948. {
  949. if (this.elementManager.GetElementCategory(position) == ReceiveSecurityHeaderElementCategory.EncryptedData)
  950. {
  951. EncryptedData encryptedData = this.elementManager.GetElement<EncryptedData>(position);
  952. bool dummy = false;
  953. ProcessEncryptedData(encryptedData, this.timeoutHelper.RemainingTime(), position, false, ref dummy);
  954. }
  955. }
  956. }
  957. internal void ExecuteReadingPass(XmlDictionaryReader reader)
  958. {
  959. int position = 0;
  960. while (reader.IsStartElement())
  961. {
  962. if (IsReaderAtSignature(reader))
  963. {
  964. ReadSignature(reader, AppendPosition, null);
  965. }
  966. else if (IsReaderAtReferenceList(reader))
  967. {
  968. ReadReferenceList(reader);
  969. }
  970. else if (this.StandardsManager.WSUtilitySpecificationVersion.IsReaderAtTimestamp(reader))
  971. {
  972. ReadTimestamp(reader);
  973. }
  974. else if (IsReaderAtEncryptedKey(reader))
  975. {
  976. ReadEncryptedKey(reader, false);
  977. }
  978. else if (IsReaderAtEncryptedData(reader))
  979. {
  980. ReadEncryptedData(reader);
  981. }
  982. else if (this.StandardsManager.SecurityVersion.IsReaderAtSignatureConfirmation(reader))
  983. {
  984. ReadSignatureConfirmation(reader, AppendPosition, null);
  985. }
  986. else if (IsReaderAtSecurityTokenReference(reader))
  987. {
  988. ReadSecurityTokenReference(reader);
  989. }
  990. else
  991. {
  992. ReadToken(reader, AppendPosition, null, null, null, this.timeoutHelper.RemainingTime());
  993. }
  994. position++;
  995. }
  996. reader.ReadEndElement(); // wsse:Security
  997. reader.Close();
  998. }
  999. internal void ExecuteFullPass(XmlDictionaryReader reader)
  1000. {
  1001. bool primarySignatureFound = !this.RequireMessageProtection;
  1002. int position = 0;
  1003. while (reader.IsStartElement())
  1004. {
  1005. if (IsReaderAtSignature(reader))
  1006. {
  1007. SignedXml signedXml = ReadSignature(reader, AppendPosition, null);
  1008. if (primarySignatureFound)
  1009. {
  1010. this.elementManager.SetBindingMode(position, ReceiveSecurityHeaderBindingModes.Endorsing);
  1011. ProcessSupportingSignature(signedXml, false);
  1012. }
  1013. else
  1014. {
  1015. primarySignatureFound = true;
  1016. this.elementManager.SetBindingMode(position, ReceiveSecurityHeaderBindingModes.Primary);
  1017. ProcessPrimarySignature(signedXml, false);
  1018. }
  1019. }
  1020. else if (IsReaderAtReferenceList(reader))
  1021. {
  1022. ReferenceList referenceList = ReadReferenceList(reader);
  1023. ProcessReferenceList(referenceList);
  1024. }
  1025. else if (this.StandardsManager.WSUtilitySpecificationVersion.IsReaderAtTimestamp(reader))
  1026. {
  1027. ReadTimestamp(reader);
  1028. }
  1029. else if (IsReaderAtEncryptedKey(reader))
  1030. {
  1031. ReadEncryptedKey(reader, true);
  1032. }
  1033. else if (IsReaderAtEncryptedData(reader))
  1034. {
  1035. EncryptedData encryptedData = ReadEncryptedData(reader);
  1036. ProcessEncryptedData(encryptedData, this.timeoutHelper.RemainingTime(), position, true, ref primarySignatureFound);
  1037. }
  1038. else if (this.StandardsManager.SecurityVersion.IsReaderAtSignatureConfirmation(reader))
  1039. {
  1040. ReadSignatureConfirmation(reader, AppendPosition, null);
  1041. }
  1042. else if (IsReaderAtSecurityTokenReference(reader))
  1043. {
  1044. ReadSecurityTokenReference(reader);
  1045. }
  1046. else
  1047. {
  1048. ReadToken(reader, AppendPosition, null, null, null, this.timeoutHelper.RemainingTime());
  1049. }
  1050. position++;
  1051. }
  1052. reader.ReadEndElement(); // wsse:Security
  1053. reader.Close();
  1054. }
  1055. internal void EnsureDerivedKeyLimitNotReached()
  1056. {
  1057. ++this.numDerivedKeys;
  1058. if (this.numDerivedKeys > this.maxDerivedKeys)
  1059. {
  1060. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.DerivedKeyLimitExceeded, maxDerivedKeys)));
  1061. }
  1062. }
  1063. internal void ExecuteDerivedKeyTokenStubPass(bool isFinalPass)
  1064. {
  1065. for (int position = 0; position < this.elementManager.Count; position++)
  1066. {
  1067. if (this.elementManager.GetElementCategory(position) == ReceiveSecurityHeaderElementCategory.Token)
  1068. {
  1069. DerivedKeySecurityTokenStub stub = this.elementManager.GetElement(position) as DerivedKeySecurityTokenStub;
  1070. if (stub != null)
  1071. {
  1072. SecurityToken sourceToken = null;
  1073. this.universalTokenResolver.TryResolveToken(stub.TokenToDeriveIdentifier, out sourceToken);
  1074. if (sourceToken != null)
  1075. {
  1076. EnsureDerivedKeyLimitNotReached();
  1077. DerivedKeySecurityToken derivedKeyToken = stub.CreateToken(sourceToken, this.maxDerivedKeyLength);
  1078. this.elementManager.SetElement(position, derivedKeyToken);
  1079. AddDerivedKeyTokenToResolvers(derivedKeyToken);
  1080. }
  1081. else if (isFinalPass)
  1082. {
  1083. throw TraceUtility.ThrowHelperError(new MessageSecurityException(
  1084. SR.GetString(SR.UnableToResolveKeyInfoClauseInDerivedKeyToken, stub.TokenToDeriveIdentifier)), this.Message);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. }
  1090. SecurityToken GetRootToken(SecurityToken token)
  1091. {
  1092. if (token is DerivedKeySecurityToken)
  1093. {
  1094. return ((DerivedKeySecurityToken)token).TokenToDerive;
  1095. }
  1096. else
  1097. {
  1098. return token;
  1099. }
  1100. }
  1101. void RecordEncryptionTokenAndRemoveReferenceListEntry(string id, SecurityToken encryptionToken)
  1102. {
  1103. if (id == null)
  1104. {
  1105. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MissingIdInEncryptedElement)), this.Message);
  1106. }
  1107. OnDecryptionOfSecurityHeaderItemRequiringReferenceListEntry(id);
  1108. RecordEncryptionToken(encryptionToken);
  1109. }
  1110. EncryptedData ReadEncryptedData(XmlDictionaryReader reader)
  1111. {
  1112. EncryptedData encryptedData = ReadSecurityHeaderEncryptedItem(reader, this.MessageDirection == MessageDirection.Output);
  1113. this.elementManager.AppendEncryptedData(encryptedData);
  1114. return encryptedData;
  1115. }
  1116. internal XmlDictionaryReader CreateDecryptedReader(byte[] decryptedBuffer)
  1117. {
  1118. return ContextImportHelper.CreateSplicedReader(
  1119. decryptedBuffer,
  1120. this.SecurityVerifiedMessage.GetEnvelopeAttributes(),
  1121. this.SecurityVerifiedMessage.GetHeaderAttributes(),
  1122. this.securityElementAttributes,
  1123. this.ReaderQuotas
  1124. );
  1125. }
  1126. void ProcessEncryptedData(EncryptedData encryptedData, TimeSpan timeout, int position, bool eagerMode, ref bool primarySignatureFound)
  1127. {
  1128. if (TD.EncryptedDataProcessingStartIsEnabled())
  1129. {
  1130. TD.EncryptedDataProcessingStart(this.EventTraceActivity);
  1131. }
  1132. string id = encryptedData.Id;
  1133. SecurityToken encryptionToken;
  1134. byte[] decryptedBuffer = DecryptSecurityHeaderElement(encryptedData, this.wrappedKeyToken, out encryptionToken);
  1135. XmlDictionaryReader decryptedReader = CreateDecryptedReader(decryptedBuffer);
  1136. if (IsReaderAtSignature(decryptedReader))
  1137. {
  1138. RecordEncryptionTokenAndRemoveReferenceListEntry(id, encryptionToken);
  1139. SignedXml signedXml = ReadSignature(decryptedReader, position, decryptedBuffer);
  1140. if (eagerMode)
  1141. {
  1142. if (primarySignatureFound)
  1143. {
  1144. this.elementManager.SetBindingMode(position, ReceiveSecurityHeaderBindingModes.Endorsing);
  1145. ProcessSupportingSignature(signedXml, true);
  1146. }
  1147. else
  1148. {
  1149. primarySignatureFound = true;
  1150. this.elementManager.SetBindingMode(position, ReceiveSecurityHeaderBindingModes.Primary);
  1151. ProcessPrimarySignature(signedXml, true);
  1152. }
  1153. }
  1154. }
  1155. else if (this.StandardsManager.SecurityVersion.IsReaderAtSignatureConfirmation(decryptedReader))
  1156. {
  1157. RecordEncryptionTokenAndRemoveReferenceListEntry(id, encryptionToken);
  1158. ReadSignatureConfirmation(decryptedReader, position, decryptedBuffer);
  1159. }
  1160. else
  1161. {
  1162. if (IsReaderAtEncryptedData(decryptedReader))
  1163. {
  1164. // The purpose of this code is to process a token that arrived at a client as encryptedData.
  1165. // This is a common scenario for supporting tokens.
  1166. // We pass readXmlReferenceKeyIdentifierClause as false here because we do not expect the client
  1167. // to receive an encrypted token for itself from the service. The encrypted token is encrypted for some other service.
  1168. // Hence we assume that the KeyInfoClause entry in it is not an XMLReference entry that the client is supposed to understand.
  1169. // What if the service sends its authentication token as an EncryptedData to the client?
  1170. EncryptedData ed = ReadSecurityHeaderEncryptedItem(decryptedReader, false);
  1171. SecurityToken securityToken;
  1172. byte[] db = DecryptSecurityHeaderElement(ed, this.wrappedKeyToken, out securityToken);
  1173. XmlDictionaryReader dr = CreateDecryptedReader(db);
  1174. // read the actual token and put it into the system
  1175. ReadToken(dr, position, db, encryptionToken, id, timeout);
  1176. ReceiveSecurityHeaderEntry rshe;
  1177. this.ElementManager.GetElementEntry(position, out rshe);
  1178. // In EncryptBeforeSignMode, we have encrypted the outer token, remember the right id.
  1179. // The reason why I have both id's is in that case that one or the other is passed
  1180. // we won't have a problem with which one. SHP accounting should ensure each item has
  1181. // the correct hash.
  1182. if (this.EncryptBeforeSignMode)
  1183. {
  1184. rshe.encryptedFormId = encryptedData.Id;
  1185. rshe.encryptedFormWsuId = encryptedData.WsuId;
  1186. }
  1187. else
  1188. {
  1189. rshe.encryptedFormId = ed.Id;
  1190. rshe.encryptedFormWsuId = ed.WsuId;
  1191. }
  1192. rshe.decryptedBuffer = decryptedBuffer;
  1193. // setting this to true, will allow a different id match in ReceiveSecurityHeaderEntry.Match
  1194. // to one of the ids set above as the token id will not match what the signature reference is looking for.
  1195. rshe.doubleEncrypted = true;
  1196. this.ElementManager.ReplaceHeaderEntry(position, rshe);
  1197. }
  1198. else
  1199. ReadToken(decryptedReader, position, decryptedBuffer, encryptionToken, id, timeout);
  1200. }
  1201. if (TD.EncryptedDataProcessingSuccessIsEnabled())
  1202. {
  1203. TD.EncryptedDataProcessingSuccess(this.EventTraceActivity);
  1204. }
  1205. }
  1206. void ReadEncryptedKey(XmlDictionaryReader reader, bool processReferenceListIfPresent)
  1207. {
  1208. this.orderTracker.OnEncryptedKey();
  1209. WrappedKeySecurityToken wrappedKeyToken = DecryptWrappedKey(reader);
  1210. if (wrappedKeyToken.WrappingToken != this.wrappingToken)
  1211. {
  1212. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, this.wrappingToken)));
  1213. }
  1214. this.universalTokenResolver.Add(wrappedKeyToken);
  1215. this.primaryTokenResolver.Add(wrappedKeyToken);
  1216. if (wrappedKeyToken.ReferenceList != null)
  1217. {
  1218. if (!this.EncryptedKeyContainsReferenceList)
  1219. {
  1220. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptedKeyWithReferenceListNotAllowed)));
  1221. }
  1222. if (!this.ExpectEncryption)
  1223. {
  1224. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptionNotExpected)), this.Message);
  1225. }
  1226. if (processReferenceListIfPresent)
  1227. {
  1228. ProcessReferenceList(wrappedKeyToken.ReferenceList, wrappedKeyToken);
  1229. }
  1230. this.wrappedKeyToken = wrappedKeyToken;
  1231. }
  1232. this.elementManager.AppendToken(wrappedKeyToken, ReceiveSecurityHeaderBindingModes.Primary, null);
  1233. }
  1234. ReferenceList ReadReferenceList(XmlDictionaryReader reader)
  1235. {
  1236. if (!this.ExpectEncryption)
  1237. {
  1238. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptionNotExpected)), this.Message);
  1239. }
  1240. ReferenceList referenceList = ReadReferenceListCore(reader);
  1241. this.elementManager.AppendReferenceList(referenceList);
  1242. return referenceList;
  1243. }
  1244. protected abstract ReferenceList ReadReferenceListCore(XmlDictionaryReader reader);
  1245. void ProcessReferenceList(ReferenceList referenceList)
  1246. {
  1247. ProcessReferenceList(referenceList, null);
  1248. }
  1249. void ProcessReferenceList(ReferenceList referenceList, WrappedKeySecurityToken wrappedKeyToken)
  1250. {
  1251. this.orderTracker.OnProcessReferenceList();
  1252. ProcessReferenceListCore(referenceList, wrappedKeyToken);
  1253. }
  1254. protected abstract void ProcessReferenceListCore(ReferenceList referenceList, WrappedKeySecurityToken wrappedKeyToken);
  1255. SignedXml ReadSignature(XmlDictionaryReader reader, int position, byte[] decryptedBuffer)
  1256. {
  1257. Fx.Assert((position == AppendPosition) == (decryptedBuffer == null), "inconsistent position, decryptedBuffer parameters");
  1258. if (!this.ExpectSignature)
  1259. {
  1260. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SignatureNotExpected)), this.Message);
  1261. }
  1262. SignedXml signedXml = ReadSignatureCore(reader);
  1263. signedXml.Signature.SignedInfo.ReaderProvider = this.ElementManager;
  1264. int readerIndex;
  1265. if (decryptedBuffer == null)
  1266. {
  1267. this.elementManager.AppendSignature(signedXml);
  1268. readerIndex = this.elementManager.Count - 1;
  1269. }
  1270. else
  1271. {
  1272. this.elementManager.SetSignatureAfterDecryption(position, signedXml, decryptedBuffer);
  1273. readerIndex = position;
  1274. }
  1275. signedXml.Signature.SignedInfo.SignatureReaderProviderCallbackContext = (object)(readerIndex);
  1276. return signedXml;
  1277. }
  1278. protected abstract void ReadSecurityTokenReference(XmlDictionaryReader reader);
  1279. void ProcessPrimarySignature(SignedXml signedXml, bool isFromDecryptedSource)
  1280. {
  1281. this.orderTracker.OnProcessSignature(isFromDecryptedSource);
  1282. this.primarySignatureValue = signedXml.GetSignatureValue();
  1283. if (this.replayDetectionEnabled)
  1284. {
  1285. CheckNonce(this.nonceCache, this.primarySignatureValue);
  1286. }
  1287. SecurityToken signingToken = VerifySignature(signedXml, true, this.primaryTokenResolver, null, null);
  1288. // verify that the signing token is the same as the primary token
  1289. SecurityToken rootSigningToken = GetRootToken(signingToken);
  1290. bool isDerivedKeySignature = signingToken is DerivedKeySecurityToken;
  1291. if (this.primaryTokenTracker != null)
  1292. {
  1293. this.primaryTokenTracker.RecordToken(rootSigningToken);
  1294. this.primaryTokenTracker.IsDerivedFrom = isDerivedKeySignature;
  1295. }
  1296. this.AddIncomingSignatureValue(signedXml.GetSignatureValue(), isFromDecryptedSource);
  1297. }
  1298. void ReadSignatureConfirmation(XmlDictionaryReader reader, int position, byte[] decryptedBuffer)
  1299. {
  1300. Fx.Assert((position == AppendPosition) == (decryptedBuffer == null), "inconsistent position, decryptedBuffer parameters");
  1301. if (!this.ExpectSignatureConfirmation)
  1302. {
  1303. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SignatureConfirmationsNotExpected)), this.Message);
  1304. }
  1305. if (this.orderTracker.PrimarySignatureDone)
  1306. {
  1307. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SignatureConfirmationsOccursAfterPrimarySignature)), this.Message);
  1308. }
  1309. ISignatureValueSecurityElement sigConfElement = this.StandardsManager.SecurityVersion.ReadSignatureConfirmation(reader);
  1310. if (decryptedBuffer == null)
  1311. {
  1312. this.AddIncomingSignatureConfirmation(sigConfElement.GetSignatureValue(), false);
  1313. this.elementManager.AppendSignatureConfirmation(sigConfElement);
  1314. }
  1315. else
  1316. {
  1317. this.AddIncomingSignatureConfirmation(sigConfElement.GetSignatureValue(), true);
  1318. this.elementManager.SetSignatureConfirmationAfterDecryption(position, sigConfElement, decryptedBuffer);
  1319. }
  1320. }
  1321. TokenTracker GetSupportingTokenTracker(SecurityToken token)
  1322. {
  1323. if (this.supportingTokenTrackers == null)
  1324. return null;
  1325. for (int i = 0; i < this.supportingTokenTrackers.Count; ++i)
  1326. {
  1327. if (supportingTokenTrackers[i].token == token)
  1328. return supportingTokenTrackers[i];
  1329. }
  1330. return null;
  1331. }
  1332. protected TokenTracker GetSupportingTokenTracker(SecurityTokenAuthenticator tokenAuthenticator, out SupportingTokenAuthenticatorSpecification spec)
  1333. {
  1334. spec = null;
  1335. if (this.supportingTokenAuthenticators == null)
  1336. return null;
  1337. for (int i = 0; i < this.supportingTokenAuthenticators.Count; ++i)
  1338. {
  1339. if (supportingTokenAuthenticators[i].TokenAuthenticator == tokenAuthenticator)
  1340. {
  1341. spec = supportingTokenAuthenticators[i];
  1342. return supportingTokenTrackers[i];
  1343. }
  1344. }
  1345. return null;
  1346. }
  1347. protected TAuthenticator FindAllowedAuthenticator<TAuthenticator>(bool removeIfPresent)
  1348. where TAuthenticator : SecurityTokenAuthenticator
  1349. {
  1350. if (this.allowedAuthenticators == null)
  1351. {
  1352. return null;
  1353. }
  1354. for (int i = 0; i < this.allowedAuthenticators.Count; ++i)
  1355. {
  1356. if (allowedAuthenticators[i] is TAuthenticator)
  1357. {
  1358. TAuthenticator result = (TAuthenticator)allowedAuthenticators[i];
  1359. if (removeIfPresent)
  1360. {
  1361. this.allowedAuthenticators.RemoveAt(i);
  1362. }
  1363. return result;
  1364. }
  1365. }
  1366. return null;
  1367. }
  1368. void ProcessSupportingSignature(SignedXml signedXml, bool isFromDecryptedSource)
  1369. {
  1370. if (!this.ExpectEndorsingTokens)
  1371. {
  1372. throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SupportingTokenSignaturesNotExpected)), this.Message);
  1373. }
  1374. string id;
  1375. XmlDictionaryReader reader;
  1376. object signatureTarget;
  1377. if (!this.RequireMessageProtection)
  1378. {
  1379. if (this.timestamp == null)
  1380. {
  1381. throw TraceUtility.ThrowHelperError(new MessageSecurityException(
  1382. SR.GetString(SR.SigningWithoutPrimarySignatureRequiresTimestamp)), this.Message);
  1383. }
  1384. reader = null;
  1385. id = this.timestamp.Id;
  1386. // We would have pre-computed the timestamp digest, if the transport reader
  1387. // was capable of canonicalization. If we were not able to compute the digest
  1388. // before hand then the signature verification step will get a new reader
  1389. // and will recompute the digest.
  1390. signatureTarget = null;
  1391. }
  1392. else
  1393. {
  1394. this.elementManager.GetPrimarySignature(out reader, out id);
  1395. if (reader == null)
  1396. {
  1397. throw TraceUtility.ThrowHelperError(new MessageSecurityException(
  1398. SR.GetString(SR.NoPrimarySignatureAvailableForSupportingTokenSignatureVerification)), this.Message);
  1399. }
  1400. signatureTarget = reader;
  1401. }
  1402. SecurityToken signingToken = VerifySignature(signedXml, false, this.universalTokenResolver, signatureTarget, id);
  1403. if (reader != null)
  1404. {
  1405. reader.Close();
  1406. }
  1407. if (signingToken == null)
  1408. {
  1409. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SignatureVerificationFailed)), this.Message);
  1410. }
  1411. SecurityToken rootSigningToken = GetRootToken(signingToken);
  1412. TokenTracker tracker = GetSupportingTokenTracker(rootSigningToken);
  1413. if (tracker == null)
  1414. {
  1415. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.UnknownSupportingToken, signingToken)));
  1416. }
  1417. if (tracker.AlreadyReadEndorsingSignature)
  1418. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MoreThanOneSupportingSignature, signingToken)));
  1419. tracker.IsEndorsing = true;
  1420. tracker.AlreadyReadEndorsingSignature = true;
  1421. tracker.IsDerivedFrom = (signingToken is DerivedKeySecurityToken);
  1422. AddIncomingSignatureValue(signedXml.GetSignatureValue(), isFromDecryptedSource);
  1423. }
  1424. void ReadTimestamp(XmlDictionaryReader reader)
  1425. {
  1426. if (this.timestamp != null)
  1427. {
  1428. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.DuplicateTimestampInSecurityHeader)), this.Message);
  1429. }
  1430. bool expectTimestampToBeSigned = this.RequireMessageProtection || this.hasEndorsingOrSignedEndorsingSupportingTokens;
  1431. string expectedDigestAlgorithm = expectTimestampToBeSigned ? this.AlgorithmSuite.DefaultDigestAlgorithm : null;
  1432. SignatureResourcePool resourcePool = expectTimestampToBeSigned ? this.ResourcePool : null;
  1433. this.timestamp = this.StandardsManager.WSUtilitySpecificationVersion.ReadTimestamp(reader, expectedDigestAlgorithm, resourcePool);
  1434. this.timestamp.ValidateRangeAndFreshness(this.replayWindow, this.clockSkew);
  1435. this.elementManager.AppendTimestamp(this.timestamp);
  1436. }
  1437. bool IsPrimaryToken(SecurityToken token)
  1438. {
  1439. bool result = (token == outOfBandPrimaryToken
  1440. || (primaryTokenTracker != null && token == primaryTokenTracker.token)
  1441. || (token == expectedEncryptionToken)
  1442. || ((token is WrappedKeySecurityToken) && ((WrappedKeySecurityToken)token).WrappingToken == this.wrappingToken));
  1443. if (!result && this.outOfBandPrimaryTokenCollection != null)
  1444. {
  1445. for (int i = 0; i < this.outOfBandPrimaryTokenCollection.Count; ++i)
  1446. {
  1447. if (this.outOfBandPrimaryTokenCollection[i] == token)
  1448. {
  1449. result = true;
  1450. break;
  1451. }
  1452. }
  1453. }
  1454. return result;
  1455. }
  1456. void ReadToken(XmlDictionaryReader reader, int position, byte[] decryptedBuffer,
  1457. SecurityToken encryptionToken, string idInEncryptedForm, TimeSpan timeout)
  1458. {
  1459. Fx.Assert((position == AppendPosition) == (decryptedBuffer == null), "inconsistent position, decryptedBuffer parameters");
  1460. Fx.Assert((position == AppendPosition) == (encryptionToken == null), "inconsistent position, encryptionToken parameters");
  1461. string localName = reader.LocalName;
  1462. string namespaceUri = reader.NamespaceURI;
  1463. string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null);
  1464. SecurityTokenAuthenticator usedTokenAuthenticator;
  1465. SecurityToken token = ReadToken(reader, this.CombinedUniversalTokenResolver, allowedAuthenticators, out usedTokenAuthenticator);
  1466. if (token == null)
  1467. {
  1468. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCouldNotReadToken, localName, namespaceUri, valueType)), this.Message);
  1469. }
  1470. DerivedKeySecurityToken derivedKeyToken = token as DerivedKeySecurityToken;
  1471. if (derivedKeyToken != null)
  1472. {
  1473. EnsureDerivedKeyLimitNotReached();
  1474. derivedKeyToken.InitializeDerivedKey(this.maxDerivedKeyLength);
  1475. }
  1476. if ((usedTokenAuthenticator is SspiNegotiationTokenAuthenticator) ||
  1477. (usedTokenAuthenticator == this.primaryTokenAuthenticator))
  1478. {
  1479. this.allowedAuthenticators.Remove(usedTokenAuthenticator);
  1480. }
  1481. ReceiveSecurityHeaderBindingModes mode;
  1482. TokenTracker supportingTokenTracker = null;
  1483. if (usedTokenAuthenticator == this.primaryTokenAuthenticator)
  1484. {
  1485. // this is the primary token. Add to resolver as such
  1486. this.universalTokenResolver.Add(token, SecurityTokenReferenceStyle.Internal, this.primaryTokenParameters);
  1487. this.primaryTokenResolver.Add(token, SecurityTokenReferenceStyle.Internal, this.primaryTokenParameters);
  1488. if (this.pendingSupportingTokenAuthenticator != null)
  1489. {
  1490. this.allowedAuthenticators.Add(this.pendingSupportingTokenAuthenticator);
  1491. this.pendingSupportingTokenAuthenticator = null;
  1492. }
  1493. this.primaryTokenTracker.RecordToken(token);
  1494. mode = ReceiveSecurityHeaderBindingModes.Primary;
  1495. }
  1496. else if (usedTokenAuthenticator == this.DerivedTokenAuthenticator)
  1497. {
  1498. if (token is DerivedKeySecurityTokenStub)
  1499. {
  1500. if (this.Layout == SecurityHeaderLayout.Strict)
  1501. {
  1502. DerivedKeySecurityTokenStub tmpToken = (DerivedKeySecurityTokenStub)token;
  1503. throw TraceUtility.ThrowHelperError(new MessageSecurityException(
  1504. SR.GetString(SR.UnableToResolveKeyInfoClauseInDerivedKeyToken, tmpToken.TokenToDeriveIdentifier)), this.Message);
  1505. }
  1506. }
  1507. else
  1508. {
  1509. AddDerivedKeyTokenToResolvers(token);
  1510. }
  1511. mode = ReceiveSecurityHeaderBindingModes.Unknown;
  1512. }
  1513. else
  1514. {
  1515. SupportingTokenAuthenticatorSpecification supportingTokenSpec;
  1516. supportingTokenTracker = GetSupportingTokenTracker(usedTokenAuthenticator, out supportingTokenSpec);
  1517. if (supportingTokenTracker == null)
  1518. {
  1519. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.UnknownTokenAuthenticatorUsedInTokenProcessing, usedTokenAuthenticator)));
  1520. }
  1521. if (supportingTokenTracker.token != null)
  1522. {
  1523. supportingTokenTracker = new TokenTracker(supportingTokenSpec);
  1524. this.supportingTokenTrackers.Add(supportingTokenTracker);
  1525. }
  1526. supportingTokenTracker.RecordToken(token);
  1527. if (encryptionToken != null)
  1528. {
  1529. supportingTokenTracker.IsEncrypted = true;
  1530. }
  1531. bool isBasic;
  1532. bool isSignedButNotBasic;
  1533. SecurityTokenAttachmentModeHelper.Categorize(supportingTokenSpec.SecurityTokenAttachmentMode,
  1534. out isBasic, out isSignedButNotBasic, out mode);
  1535. if (isBasic)
  1536. {
  1537. if (!this.ExpectBasicTokens)
  1538. {
  1539. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.BasicTokenNotExpected)));
  1540. }
  1541. // only basic tokens have to be part of the reference list. Encrypted Saml tokens dont for example
  1542. if (this.RequireMessageProtection && encryptionToken != null)
  1543. {
  1544. RecordEncryptionTokenAndRemoveReferenceListEntry(idInEncryptedForm, encryptionToken);
  1545. }
  1546. }
  1547. if (isSignedButNotBasic && !this.ExpectSignedTokens)
  1548. {
  1549. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.SignedSupportingTokenNotExpected)));
  1550. }
  1551. this.universalTokenResolver.Add(token, SecurityTokenReferenceStyle.Internal, supportingTokenSpec.TokenParameters);
  1552. }
  1553. if (position == AppendPosition)
  1554. {
  1555. this.elementManager.AppendToken(token, mode, supportingTokenTracker);
  1556. }
  1557. else
  1558. {
  1559. this.elementManager.SetTokenAfterDecryption(position, token, mode, decryptedBuffer, supportingTokenTracker);
  1560. }
  1561. }
  1562. SecurityToken ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver, IList<SecurityTokenAuthenticator> allowedTokenAuthenticators, out SecurityTokenAuthenticator usedTokenAuthenticator)
  1563. {
  1564. SecurityToken token = this.StandardsManager.SecurityTokenSerializer.ReadToken(reader, tokenResolver);
  1565. if (token is DerivedKeySecurityTokenStub)
  1566. {
  1567. if (this.DerivedTokenAuthenticator == null)
  1568. {
  1569. // No Authenticator registered for DerivedKeySecurityToken
  1570. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  1571. SR.GetString(SR.UnableToFindTokenAuthenticator, typeof(DerivedKeySecurityToken))));
  1572. }
  1573. // This is just the stub. Nothing to Validate. Set the usedTokenAuthenticator to
  1574. // DerivedKeySecurityTokenAuthenticator.
  1575. usedTokenAuthenticator = this.DerivedTokenAuthenticator;
  1576. return token;
  1577. }
  1578. for (int i = 0; i < allowedTokenAuthenticators.Count; ++i)
  1579. {
  1580. SecurityTokenAuthenticator tokenAuthenticator = allowedTokenAuthenticators[i];
  1581. if (tokenAuthenticator.CanValidateToken(token))
  1582. {
  1583. ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies;
  1584. ServiceCredentialsSecurityTokenManager.KerberosSecurityTokenAuthenticatorWrapper kerbTokenAuthenticator =
  1585. tokenAuthenticator as ServiceCredentialsSecurityTokenManager.KerberosSecurityTokenAuthenticatorWrapper;
  1586. if (kerbTokenAuthenticator != null)
  1587. {
  1588. authorizationPolicies = kerbTokenAuthenticator.ValidateToken(token, this.channelBinding, this.extendedProtectionPolicy);
  1589. }
  1590. else
  1591. {
  1592. authorizationPolicies = tokenAuthenticator.ValidateToken(token);
  1593. }
  1594. SecurityTokenAuthorizationPoliciesMapping.Add(token, authorizationPolicies);
  1595. usedTokenAuthenticator = tokenAuthenticator;
  1596. return token;
  1597. }
  1598. }
  1599. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  1600. SR.GetString(SR.UnableToFindTokenAuthenticator, token.GetType())));
  1601. }
  1602. void AddDerivedKeyTokenToResolvers(SecurityToken token)
  1603. {
  1604. this.universalTokenResolver.Add(token);
  1605. // add it to the primary token resolver only if its root is primary
  1606. SecurityToken rootToken = GetRootToken(token);
  1607. if (IsPrimaryToken(rootToken))
  1608. {
  1609. primaryTokenResolver.Add(token);
  1610. }
  1611. }
  1612. void AddIncomingSignatureConfirmation(byte[] signatureValue, bool isFromDecryptedSource)
  1613. {
  1614. if (this.MaintainSignatureConfirmationState)
  1615. {
  1616. if (this.receivedSignatureConfirmations == null)
  1617. {
  1618. this.receivedSignatureConfirmations = new SignatureConfirmations();
  1619. }
  1620. this.receivedSignatureConfirmations.AddConfirmation(signatureValue, isFromDecryptedSource);
  1621. }
  1622. }
  1623. void AddIncomingSignatureValue(byte[] signatureValue, bool isFromDecryptedSource)
  1624. {
  1625. // cache incoming signatures only on the server side
  1626. if (this.MaintainSignatureConfirmationState && !this.ExpectSignatureConfirmation)
  1627. {
  1628. if (this.receivedSignatureValues == null)
  1629. {
  1630. this.receivedSignatureValues = new SignatureConfirmations();
  1631. }
  1632. this.receivedSignatureValues.AddConfirmation(signatureValue, isFromDecryptedSource);
  1633. }
  1634. }
  1635. protected void RecordEncryptionToken(SecurityToken token)
  1636. {
  1637. this.encryptionTracker.RecordToken(token);
  1638. }
  1639. protected void RecordSignatureToken(SecurityToken token)
  1640. {
  1641. this.signatureTracker.RecordToken(token);
  1642. }
  1643. public void SetRequiredProtectionOrder(MessageProtectionOrder protectionOrder)
  1644. {
  1645. ThrowIfProcessingStarted();
  1646. this.protectionOrder = protectionOrder;
  1647. }
  1648. protected abstract SignedXml ReadSignatureCore(XmlDictionaryReader signatureReader);
  1649. protected abstract SecurityToken VerifySignature(SignedXml signedXml, bool isPrimarySignature,
  1650. SecurityHeaderTokenResolver resolver, object signatureTarget, string id);
  1651. protected abstract bool TryDeleteReferenceListEntry(string id);
  1652. struct OrderTracker
  1653. {
  1654. static readonly ReceiverProcessingOrder[] stateTransitionTableOnDecrypt = new ReceiverProcessingOrder[]
  1655. {
  1656. ReceiverProcessingOrder.Decrypt, ReceiverProcessingOrder.VerifyDecrypt, ReceiverProcessingOrder.Decrypt,
  1657. ReceiverProcessingOrder.Mixed, ReceiverProcessingOrder.VerifyDecrypt, ReceiverProcessingOrder.Mixed
  1658. };
  1659. static readonly ReceiverProcessingOrder[] stateTransitionTableOnVerify = new ReceiverProcessingOrder[]
  1660. {
  1661. ReceiverProcessingOrder.Verify, ReceiverProcessingOrder.Verify, ReceiverProcessingOrder.DecryptVerify,
  1662. ReceiverProcessingOrder.DecryptVerify, ReceiverProcessingOrder.Mixed, ReceiverProcessingOrder.Mixed
  1663. };
  1664. const int MaxAllowedWrappedKeys = 1;
  1665. int referenceListCount;
  1666. ReceiverProcessingOrder state;
  1667. int signatureCount;
  1668. int unencryptedSignatureCount;
  1669. int numWrappedKeys;
  1670. MessageProtectionOrder protectionOrder;
  1671. bool enforce;
  1672. public bool AllSignaturesEncrypted
  1673. {
  1674. get { return this.unencryptedSignatureCount == 0; }
  1675. }
  1676. public bool EncryptBeforeSignMode
  1677. {
  1678. get { return this.enforce && this.protectionOrder == MessageProtectionOrder.EncryptBeforeSign; }
  1679. }
  1680. public bool EncryptBeforeSignOrderRequirementMet
  1681. {
  1682. get { return this.state != ReceiverProcessingOrder.DecryptVerify && this.state != ReceiverProcessingOrder.Mixed; }
  1683. }
  1684. public bool PrimarySignatureDone
  1685. {
  1686. get { return this.signatureCount > 0; }
  1687. }
  1688. public bool SignBeforeEncryptOrderRequirementMet
  1689. {
  1690. get { return this.state != ReceiverProcessingOrder.VerifyDecrypt && this.state != ReceiverProcessingOrder.Mixed; }
  1691. }
  1692. void EnforceProtectionOrder()
  1693. {
  1694. switch (this.protectionOrder)
  1695. {
  1696. case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature:
  1697. if (!this.AllSignaturesEncrypted)
  1698. {
  1699. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  1700. SR.GetString(SR.PrimarySignatureIsRequiredToBeEncrypted)));
  1701. }
  1702. goto case MessageProtectionOrder.SignBeforeEncrypt;
  1703. case MessageProtectionOrder.SignBeforeEncrypt:
  1704. if (!this.SignBeforeEncryptOrderRequirementMet)
  1705. {
  1706. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  1707. SR.GetString(SR.MessageProtectionOrderMismatch, this.protectionOrder)));
  1708. }
  1709. break;
  1710. case MessageProtectionOrder.EncryptBeforeSign:
  1711. if (!this.EncryptBeforeSignOrderRequirementMet)
  1712. {
  1713. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  1714. SR.GetString(SR.MessageProtectionOrderMismatch, this.protectionOrder)));
  1715. }
  1716. break;
  1717. default:
  1718. Fx.Assert("");
  1719. break;
  1720. }
  1721. }
  1722. public void OnProcessReferenceList()
  1723. {
  1724. Fx.Assert(this.enforce, "OrderTracker should have 'enforce' set to true.");
  1725. if (this.referenceListCount > 0)
  1726. {
  1727. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  1728. SR.GetString(SR.AtMostOneReferenceListIsSupportedWithDefaultPolicyCheck)));
  1729. }
  1730. this.referenceListCount++;
  1731. this.state = stateTransitionTableOnDecrypt[(int)this.state];
  1732. if (this.enforce)
  1733. {
  1734. EnforceProtectionOrder();
  1735. }
  1736. }
  1737. public void OnProcessSignature(bool isEncrypted)
  1738. {
  1739. Fx.Assert(this.enforce, "OrderTracker should have 'enforce' set to true.");
  1740. if (this.signatureCount > 0)
  1741. {
  1742. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.AtMostOneSignatureIsSupportedWithDefaultPolicyCheck)));
  1743. }
  1744. this.signatureCount++;
  1745. if (!isEncrypted)
  1746. {
  1747. this.unencryptedSignatureCount++;
  1748. }
  1749. this.state = stateTransitionTableOnVerify[(int)this.state];
  1750. if (this.enforce)
  1751. {
  1752. EnforceProtectionOrder();
  1753. }
  1754. }
  1755. public void OnEncryptedKey()
  1756. {
  1757. Fx.Assert(this.enforce, "OrderTracker should have 'enforce' set to true.");
  1758. if (this.numWrappedKeys == MaxAllowedWrappedKeys)
  1759. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.WrappedKeyLimitExceeded, this.numWrappedKeys)));
  1760. this.numWrappedKeys++;
  1761. }
  1762. public void SetRequiredProtectionOrder(MessageProtectionOrder protectionOrder)
  1763. {
  1764. this.protectionOrder = protectionOrder;
  1765. this.enforce = true;
  1766. }
  1767. enum ReceiverProcessingOrder : int
  1768. {
  1769. None = 0,
  1770. Verify = 1,
  1771. Decrypt = 2,
  1772. DecryptVerify = 3,
  1773. VerifyDecrypt = 4,
  1774. Mixed = 5
  1775. }
  1776. }
  1777. struct OperationTracker
  1778. {
  1779. MessagePartSpecification parts;
  1780. SecurityToken token;
  1781. bool isDerivedToken;
  1782. public MessagePartSpecification Parts
  1783. {
  1784. get { return this.parts; }
  1785. set { this.parts = value; }
  1786. }
  1787. public SecurityToken Token
  1788. {
  1789. get { return this.token; }
  1790. }
  1791. public bool IsDerivedToken
  1792. {
  1793. get { return this.isDerivedToken; }
  1794. }
  1795. public void RecordToken(SecurityToken token)
  1796. {
  1797. if (this.token == null)
  1798. {
  1799. this.token = token;
  1800. }
  1801. else if (!ReferenceEquals(this.token, token))
  1802. {
  1803. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MismatchInSecurityOperationToken)));
  1804. }
  1805. }
  1806. public void SetDerivationSourceIfRequired()
  1807. {
  1808. DerivedKeySecurityToken derivedKeyToken = this.token as DerivedKeySecurityToken;
  1809. if (derivedKeyToken != null)
  1810. {
  1811. this.token = derivedKeyToken.TokenToDerive;
  1812. this.isDerivedToken = true;
  1813. }
  1814. }
  1815. }
  1816. }
  1817. class TokenTracker
  1818. {
  1819. public SecurityToken token;
  1820. public bool IsDerivedFrom;
  1821. public bool IsSigned;
  1822. public bool IsEncrypted;
  1823. public bool IsEndorsing;
  1824. public bool AlreadyReadEndorsingSignature;
  1825. bool allowFirstTokenMismatch;
  1826. public SupportingTokenAuthenticatorSpecification spec;
  1827. public TokenTracker(SupportingTokenAuthenticatorSpecification spec)
  1828. : this(spec, null, false)
  1829. {
  1830. }
  1831. public TokenTracker(SupportingTokenAuthenticatorSpecification spec, SecurityToken token, bool allowFirstTokenMismatch)
  1832. {
  1833. this.spec = spec;
  1834. this.token = token;
  1835. this.allowFirstTokenMismatch = allowFirstTokenMismatch;
  1836. }
  1837. public void RecordToken(SecurityToken token)
  1838. {
  1839. if (this.token == null)
  1840. {
  1841. this.token = token;
  1842. }
  1843. else if (this.allowFirstTokenMismatch)
  1844. {
  1845. if (!AreTokensEqual(this.token, token))
  1846. {
  1847. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MismatchInSecurityOperationToken)));
  1848. }
  1849. this.token = token;
  1850. this.allowFirstTokenMismatch = false;
  1851. }
  1852. else if (!object.ReferenceEquals(this.token, token))
  1853. {
  1854. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MismatchInSecurityOperationToken)));
  1855. }
  1856. }
  1857. static bool AreTokensEqual(SecurityToken outOfBandToken, SecurityToken replyToken)
  1858. {
  1859. // we support the serialized reply token legacy feature only for X509 certificates.
  1860. // in this case the thumbprint of the reply certificate must match the outofband certificate's thumbprint
  1861. if ((outOfBandToken is X509SecurityToken) && (replyToken is X509SecurityToken))
  1862. {
  1863. byte[] outOfBandCertificateThumbprint = ((X509SecurityToken)outOfBandToken).Certificate.GetCertHash();
  1864. byte[] replyCertificateThumbprint = ((X509SecurityToken)replyToken).Certificate.GetCertHash();
  1865. return (CryptoHelper.IsEqual(outOfBandCertificateThumbprint, replyCertificateThumbprint));
  1866. }
  1867. else
  1868. {
  1869. return false;
  1870. }
  1871. }
  1872. }
  1873. class AggregateSecurityHeaderTokenResolver : System.IdentityModel.Tokens.AggregateTokenResolver
  1874. {
  1875. SecurityHeaderTokenResolver tokenResolver;
  1876. public AggregateSecurityHeaderTokenResolver(SecurityHeaderTokenResolver tokenResolver, ReadOnlyCollection<SecurityTokenResolver> outOfBandTokenResolvers) :
  1877. base(outOfBandTokenResolvers)
  1878. {
  1879. if (tokenResolver == null)
  1880. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenResolver");
  1881. this.tokenResolver = tokenResolver;
  1882. }
  1883. protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
  1884. {
  1885. bool resolved = false;
  1886. key = null;
  1887. resolved = this.tokenResolver.TryResolveSecurityKey(keyIdentifierClause, false, out key);
  1888. if (!resolved)
  1889. {
  1890. resolved = base.TryResolveSecurityKeyCore(keyIdentifierClause, out key);
  1891. }
  1892. if (!resolved)
  1893. {
  1894. resolved = SecurityUtils.TryCreateKeyFromIntrinsicKeyClause(keyIdentifierClause, this, out key);
  1895. }
  1896. return resolved;
  1897. }
  1898. protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
  1899. {
  1900. bool resolved = false;
  1901. token = null;
  1902. resolved = this.tokenResolver.TryResolveToken(keyIdentifier, false, false, out token);
  1903. if (!resolved)
  1904. {
  1905. resolved = base.TryResolveTokenCore(keyIdentifier, out token);
  1906. }
  1907. if (!resolved)
  1908. {
  1909. for (int i = 0; i < keyIdentifier.Count; ++i)
  1910. {
  1911. if (this.TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[i], out token))
  1912. {
  1913. resolved = true;
  1914. break;
  1915. }
  1916. }
  1917. }
  1918. return resolved;
  1919. }
  1920. bool TryResolveTokenFromIntrinsicKeyClause(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token)
  1921. {
  1922. token = null;
  1923. if (keyIdentifierClause is RsaKeyIdentifierClause)
  1924. {
  1925. token = new RsaSecurityToken(((RsaKeyIdentifierClause)keyIdentifierClause).Rsa);
  1926. return true;
  1927. }
  1928. else if (keyIdentifierClause is X509RawDataKeyIdentifierClause)
  1929. {
  1930. token = new X509SecurityToken(new X509Certificate2(((X509RawDataKeyIdentifierClause)keyIdentifierClause).GetX509RawData()), false);
  1931. return true;
  1932. }
  1933. else if (keyIdentifierClause is EncryptedKeyIdentifierClause)
  1934. {
  1935. EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
  1936. SecurityKeyIdentifier wrappingTokenReference = keyClause.EncryptingKeyIdentifier;
  1937. SecurityToken unwrappingToken;
  1938. if (this.TryResolveToken(wrappingTokenReference, out unwrappingToken))
  1939. {
  1940. token = SecurityUtils.CreateTokenFromEncryptedKeyClause(keyClause, unwrappingToken);
  1941. return true;
  1942. }
  1943. }
  1944. return false;
  1945. }
  1946. protected override bool TryResolveTokenCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token)
  1947. {
  1948. bool resolved = false;
  1949. token = null;
  1950. resolved = this.tokenResolver.TryResolveToken(keyIdentifierClause, false, false, out token);
  1951. if (!resolved)
  1952. {
  1953. resolved = base.TryResolveTokenCore(keyIdentifierClause, out token);
  1954. }
  1955. if (!resolved)
  1956. {
  1957. resolved = TryResolveTokenFromIntrinsicKeyClause(keyIdentifierClause, out token);
  1958. }
  1959. return resolved;
  1960. }
  1961. }
  1962. }