ReceiveSecurityHeaderElementManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. //----------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Security
  5. {
  6. using System.IdentityModel.Tokens;
  7. using System.Runtime;
  8. using System.ServiceModel;
  9. using System.ServiceModel.Diagnostics;
  10. using System.Xml;
  11. using ISignatureReaderProvider = System.IdentityModel.ISignatureReaderProvider;
  12. using ISignatureValueSecurityElement = System.IdentityModel.ISignatureValueSecurityElement;
  13. using SignedXml = System.IdentityModel.SignedXml;
  14. using System.Collections.Generic;
  15. sealed class ReceiveSecurityHeaderElementManager : ISignatureReaderProvider
  16. {
  17. const int InitialCapacity = 8;
  18. readonly ReceiveSecurityHeader securityHeader;
  19. ReceiveSecurityHeaderEntry[] elements;
  20. int count;
  21. readonly string[] headerIds;
  22. string[] predecryptionHeaderIds;
  23. string bodyId;
  24. string bodyContentId;
  25. bool isPrimaryTokenSigned = false;
  26. public ReceiveSecurityHeaderElementManager(ReceiveSecurityHeader securityHeader)
  27. {
  28. this.securityHeader = securityHeader;
  29. this.elements = new ReceiveSecurityHeaderEntry[InitialCapacity];
  30. if (securityHeader.RequireMessageProtection)
  31. {
  32. this.headerIds = new string[securityHeader.ProcessedMessage.Headers.Count];
  33. }
  34. }
  35. public int Count
  36. {
  37. get { return this.count; }
  38. }
  39. public bool IsPrimaryTokenSigned
  40. {
  41. get { return this.isPrimaryTokenSigned; }
  42. set { this.isPrimaryTokenSigned = value; }
  43. }
  44. public void AppendElement(
  45. ReceiveSecurityHeaderElementCategory elementCategory, object element,
  46. ReceiveSecurityHeaderBindingModes bindingMode, string id, TokenTracker supportingTokenTracker)
  47. {
  48. if (id != null)
  49. {
  50. VerifyIdUniquenessInSecurityHeader(id);
  51. }
  52. EnsureCapacityToAdd();
  53. this.elements[this.count++].SetElement(elementCategory, element, bindingMode, id, false, null, supportingTokenTracker);
  54. }
  55. public void AppendSignature(SignedXml signedXml)
  56. {
  57. AppendElement(ReceiveSecurityHeaderElementCategory.Signature, signedXml,
  58. ReceiveSecurityHeaderBindingModes.Unknown, signedXml.Id, null);
  59. }
  60. public void AppendReferenceList(ReferenceList referenceList)
  61. {
  62. AppendElement(ReceiveSecurityHeaderElementCategory.ReferenceList, referenceList,
  63. ReceiveSecurityHeaderBindingModes.Unknown, null, null);
  64. }
  65. public void AppendEncryptedData(EncryptedData encryptedData)
  66. {
  67. AppendElement(ReceiveSecurityHeaderElementCategory.EncryptedData, encryptedData,
  68. ReceiveSecurityHeaderBindingModes.Unknown, encryptedData.Id, null);
  69. }
  70. public void AppendSignatureConfirmation(ISignatureValueSecurityElement signatureConfirmationElement)
  71. {
  72. AppendElement(ReceiveSecurityHeaderElementCategory.SignatureConfirmation, signatureConfirmationElement,
  73. ReceiveSecurityHeaderBindingModes.Unknown, signatureConfirmationElement.Id, null);
  74. }
  75. public void AppendTimestamp(SecurityTimestamp timestamp)
  76. {
  77. AppendElement(ReceiveSecurityHeaderElementCategory.Timestamp, timestamp,
  78. ReceiveSecurityHeaderBindingModes.Unknown, timestamp.Id, null);
  79. }
  80. public void AppendSecurityTokenReference(SecurityKeyIdentifierClause strClause, string strId)
  81. {
  82. if (!String.IsNullOrEmpty(strId))
  83. {
  84. VerifyIdUniquenessInSecurityHeader(strId);
  85. AppendElement(ReceiveSecurityHeaderElementCategory.SecurityTokenReference, strClause, ReceiveSecurityHeaderBindingModes.Unknown, strId, null);
  86. }
  87. }
  88. public void AppendToken(SecurityToken token, ReceiveSecurityHeaderBindingModes mode, TokenTracker supportingTokenTracker)
  89. {
  90. AppendElement(ReceiveSecurityHeaderElementCategory.Token, token,
  91. mode, token.Id, supportingTokenTracker);
  92. }
  93. public void EnsureAllRequiredSecurityHeaderTargetsWereProtected()
  94. {
  95. Fx.Assert(this.securityHeader.RequireMessageProtection, "security header protection checks should only be done for message security");
  96. ReceiveSecurityHeaderEntry entry;
  97. for (int i = 0; i < this.count; i++)
  98. {
  99. GetElementEntry(i, out entry);
  100. if (!entry.signed)
  101. {
  102. switch (entry.elementCategory)
  103. {
  104. case ReceiveSecurityHeaderElementCategory.Timestamp:
  105. case ReceiveSecurityHeaderElementCategory.SignatureConfirmation:
  106. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  107. new MessageSecurityException(SR.GetString(SR.RequiredSecurityHeaderElementNotSigned, entry.elementCategory, entry.id)));
  108. case ReceiveSecurityHeaderElementCategory.Token:
  109. switch (entry.bindingMode)
  110. {
  111. case ReceiveSecurityHeaderBindingModes.Signed:
  112. case ReceiveSecurityHeaderBindingModes.SignedEndorsing:
  113. case ReceiveSecurityHeaderBindingModes.Basic:
  114. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  115. new MessageSecurityException(SR.GetString(SR.RequiredSecurityTokenNotSigned, entry.element, entry.bindingMode)));
  116. }
  117. break;
  118. }
  119. }
  120. if (!entry.encrypted)
  121. {
  122. if (entry.elementCategory == ReceiveSecurityHeaderElementCategory.Token &&
  123. entry.bindingMode == ReceiveSecurityHeaderBindingModes.Basic)
  124. {
  125. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  126. new MessageSecurityException(SR.GetString(SR.RequiredSecurityTokenNotEncrypted, entry.element, entry.bindingMode)));
  127. }
  128. }
  129. }
  130. }
  131. void EnsureCapacityToAdd()
  132. {
  133. if (this.count == this.elements.Length)
  134. {
  135. ReceiveSecurityHeaderEntry[] newElements = new ReceiveSecurityHeaderEntry[this.elements.Length * 2];
  136. Array.Copy(this.elements, 0, newElements, 0, this.count);
  137. this.elements = newElements;
  138. }
  139. }
  140. public object GetElement(int index)
  141. {
  142. Fx.Assert(0 <= index && index < this.count, "");
  143. return this.elements[index].element;
  144. }
  145. public T GetElement<T>(int index) where T : class
  146. {
  147. Fx.Assert(0 <= index && index < this.count, "");
  148. return (T) this.elements[index].element;
  149. }
  150. public void GetElementEntry(int index, out ReceiveSecurityHeaderEntry element)
  151. {
  152. Fx.Assert(0 <= index && index < this.count, "index out of range");
  153. element = this.elements[index];
  154. }
  155. public ReceiveSecurityHeaderElementCategory GetElementCategory(int index)
  156. {
  157. Fx.Assert(0 <= index && index < this.count, "index out of range");
  158. return this.elements[index].elementCategory;
  159. }
  160. public void GetPrimarySignature(out XmlDictionaryReader reader, out string id)
  161. {
  162. ReceiveSecurityHeaderEntry entry;
  163. for (int i = 0; i < this.count; i++)
  164. {
  165. GetElementEntry(i, out entry);
  166. if (entry.elementCategory == ReceiveSecurityHeaderElementCategory.Signature &&
  167. entry.bindingMode == ReceiveSecurityHeaderBindingModes.Primary)
  168. {
  169. reader = GetReader(i, false);
  170. id = entry.id;
  171. return;
  172. }
  173. }
  174. reader = null;
  175. id = null;
  176. return;
  177. }
  178. internal XmlDictionaryReader GetReader(int index, bool requiresEncryptedFormReader)
  179. {
  180. Fx.Assert(0 <= index && index < this.count, "index out of range");
  181. if (!requiresEncryptedFormReader)
  182. {
  183. byte[] decryptedBuffer = this.elements[index].decryptedBuffer;
  184. if (decryptedBuffer != null)
  185. {
  186. return this.securityHeader.CreateDecryptedReader(decryptedBuffer);
  187. }
  188. }
  189. XmlDictionaryReader securityHeaderReader = this.securityHeader.CreateSecurityHeaderReader();
  190. securityHeaderReader.ReadStartElement();
  191. for (int i = 0; securityHeaderReader.IsStartElement() && i < index; i++)
  192. {
  193. securityHeaderReader.Skip();
  194. }
  195. return securityHeaderReader;
  196. }
  197. public XmlDictionaryReader GetSignatureVerificationReader(string id, bool requiresEncryptedFormReaderIfDecrypted)
  198. {
  199. ReceiveSecurityHeaderEntry entry;
  200. for (int i = 0; i < this.count; i++)
  201. {
  202. GetElementEntry(i, out entry);
  203. bool encryptedForm = entry.encrypted && requiresEncryptedFormReaderIfDecrypted;
  204. bool isSignedToken = (entry.bindingMode == ReceiveSecurityHeaderBindingModes.Signed) || (entry.bindingMode == ReceiveSecurityHeaderBindingModes.SignedEndorsing);
  205. if (entry.MatchesId(id, encryptedForm))
  206. {
  207. SetSigned(i);
  208. if (!this.IsPrimaryTokenSigned)
  209. {
  210. this.IsPrimaryTokenSigned = entry.bindingMode == ReceiveSecurityHeaderBindingModes.Primary && entry.elementCategory == ReceiveSecurityHeaderElementCategory.Token;
  211. }
  212. return GetReader(i, encryptedForm);
  213. }
  214. else if (entry.MatchesId(id, isSignedToken))
  215. {
  216. SetSigned(i);
  217. if (!this.IsPrimaryTokenSigned)
  218. {
  219. this.IsPrimaryTokenSigned = entry.bindingMode == ReceiveSecurityHeaderBindingModes.Primary && entry.elementCategory == ReceiveSecurityHeaderElementCategory.Token;
  220. }
  221. return GetReader(i, isSignedToken);
  222. }
  223. }
  224. return null;
  225. }
  226. void OnDuplicateId(string id)
  227. {
  228. throw TraceUtility.ThrowHelperError(
  229. new MessageSecurityException(SR.GetString(SR.DuplicateIdInMessageToBeVerified, id)), this.securityHeader.SecurityVerifiedMessage);
  230. }
  231. public void SetBindingMode(int index, ReceiveSecurityHeaderBindingModes bindingMode)
  232. {
  233. Fx.Assert(0 <= index && index < this.count, "index out of range");
  234. this.elements[index].bindingMode = bindingMode;
  235. }
  236. public void SetElement(int index, object element)
  237. {
  238. Fx.Assert(0 <= index && index < this.count, "");
  239. this.elements[index].element = element;
  240. }
  241. public void ReplaceHeaderEntry(int index, ReceiveSecurityHeaderEntry element)
  242. {
  243. Fx.Assert(0 <= index && index < this.count, "");
  244. this.elements[index] = element;
  245. }
  246. public void SetElementAfterDecryption(
  247. int index,
  248. ReceiveSecurityHeaderElementCategory elementCategory, object element,
  249. ReceiveSecurityHeaderBindingModes bindingMode, string id, byte[] decryptedBuffer, TokenTracker supportingTokenTracker)
  250. {
  251. Fx.Assert(0 <= index && index < this.count, "index out of range");
  252. Fx.Assert(this.elements[index].elementCategory == ReceiveSecurityHeaderElementCategory.EncryptedData, "Replaced item must be EncryptedData");
  253. if (id != null)
  254. {
  255. VerifyIdUniquenessInSecurityHeader(id);
  256. }
  257. this.elements[index].PreserveIdBeforeDecryption();
  258. this.elements[index].SetElement(elementCategory, element, bindingMode, id, true, decryptedBuffer, supportingTokenTracker);
  259. }
  260. public void SetSignatureAfterDecryption(int index, SignedXml signedXml, byte[] decryptedBuffer)
  261. {
  262. SetElementAfterDecryption(index, ReceiveSecurityHeaderElementCategory.Signature,
  263. signedXml, ReceiveSecurityHeaderBindingModes.Unknown, signedXml.Id, decryptedBuffer, null);
  264. }
  265. public void SetSignatureConfirmationAfterDecryption(int index, ISignatureValueSecurityElement signatureConfirmationElement, byte[] decryptedBuffer)
  266. {
  267. SetElementAfterDecryption(index, ReceiveSecurityHeaderElementCategory.SignatureConfirmation,
  268. signatureConfirmationElement, ReceiveSecurityHeaderBindingModes.Unknown, signatureConfirmationElement.Id, decryptedBuffer, null);
  269. }
  270. internal void SetSigned(int index)
  271. {
  272. Fx.Assert(0 <= index && index < this.count, "");
  273. this.elements[index].signed = true;
  274. if (this.elements[index].supportingTokenTracker != null)
  275. {
  276. this.elements[index].supportingTokenTracker.IsSigned = true;
  277. }
  278. }
  279. public void SetTimestampSigned(string id)
  280. {
  281. for (int i = 0; i < this.count; i++)
  282. {
  283. if (this.elements[i].elementCategory == ReceiveSecurityHeaderElementCategory.Timestamp &&
  284. this.elements[i].id == id)
  285. {
  286. SetSigned(i);
  287. }
  288. }
  289. }
  290. public void SetTokenAfterDecryption(int index, SecurityToken token, ReceiveSecurityHeaderBindingModes mode, byte[] decryptedBuffer, TokenTracker supportingTokenTracker)
  291. {
  292. SetElementAfterDecryption(index, ReceiveSecurityHeaderElementCategory.Token, token, mode, token.Id, decryptedBuffer, supportingTokenTracker);
  293. }
  294. internal bool TryGetTokenElementIndexFromStrId(string strId, out int index)
  295. {
  296. index = -1;
  297. SecurityKeyIdentifierClause strClause = null;
  298. for (int position = 0; position < this.Count; position++)
  299. {
  300. if (this.GetElementCategory(position) == ReceiveSecurityHeaderElementCategory.SecurityTokenReference)
  301. {
  302. strClause = this.GetElement(position) as SecurityKeyIdentifierClause;
  303. if (strClause.Id == strId)
  304. break;
  305. }
  306. }
  307. if (strClause == null)
  308. return false;
  309. for (int position = 0; position < this.Count; position++)
  310. {
  311. if (this.GetElementCategory(position) == ReceiveSecurityHeaderElementCategory.Token)
  312. {
  313. SecurityToken token = this.GetElement(position) as SecurityToken;
  314. if (token.MatchesKeyIdentifierClause(strClause))
  315. {
  316. index = position;
  317. return true;
  318. }
  319. }
  320. }
  321. return false;
  322. }
  323. public void VerifyUniquenessAndSetBodyId(string id)
  324. {
  325. if (id != null)
  326. {
  327. VerifyIdUniquenessInSecurityHeader(id);
  328. VerifyIdUniquenessInMessageHeadersAndBody(id, this.headerIds.Length);
  329. this.bodyId = id;
  330. }
  331. }
  332. public void VerifyUniquenessAndSetBodyContentId(string id)
  333. {
  334. if (id != null)
  335. {
  336. VerifyIdUniquenessInSecurityHeader(id);
  337. VerifyIdUniquenessInMessageHeadersAndBody(id, this.headerIds.Length);
  338. this.bodyContentId = id;
  339. }
  340. }
  341. public void VerifyUniquenessAndSetDecryptedHeaderId(string id, int headerIndex)
  342. {
  343. if (id != null)
  344. {
  345. VerifyIdUniquenessInSecurityHeader(id);
  346. VerifyIdUniquenessInMessageHeadersAndBody(id, headerIndex);
  347. if (this.predecryptionHeaderIds == null)
  348. {
  349. this.predecryptionHeaderIds = new string[headerIds.Length];
  350. }
  351. this.predecryptionHeaderIds[headerIndex] = this.headerIds[headerIndex];
  352. this.headerIds[headerIndex] = id;
  353. }
  354. }
  355. public void VerifyUniquenessAndSetHeaderId(string id, int headerIndex)
  356. {
  357. if (id != null)
  358. {
  359. VerifyIdUniquenessInSecurityHeader(id);
  360. VerifyIdUniquenessInMessageHeadersAndBody(id, headerIndex);
  361. this.headerIds[headerIndex] = id;
  362. }
  363. }
  364. void VerifyIdUniquenessInHeaderIdTable(string id, int headerCount, string[] headerIdTable)
  365. {
  366. for (int i = 0; i < headerCount; i++)
  367. {
  368. if (headerIdTable[i] == id)
  369. {
  370. OnDuplicateId(id);
  371. }
  372. }
  373. }
  374. void VerifyIdUniquenessInSecurityHeader(string id)
  375. {
  376. Fx.Assert(id != null, "Uniqueness should only be tested for non-empty ids");
  377. for (int i = 0; i < this.count; i++)
  378. {
  379. if (this.elements[i].id == id || this.elements[i].encryptedFormId == id)
  380. {
  381. OnDuplicateId(id);
  382. }
  383. }
  384. }
  385. void VerifyIdUniquenessInMessageHeadersAndBody(string id, int headerCount)
  386. {
  387. Fx.Assert(id != null, "Uniqueness should only be tested for non-empty ids");
  388. VerifyIdUniquenessInHeaderIdTable(id, headerCount, this.headerIds);
  389. if (this.predecryptionHeaderIds != null)
  390. {
  391. VerifyIdUniquenessInHeaderIdTable(id, headerCount, this.predecryptionHeaderIds);
  392. }
  393. if (this.bodyId == id || this.bodyContentId == id)
  394. {
  395. OnDuplicateId(id);
  396. }
  397. }
  398. XmlDictionaryReader ISignatureReaderProvider.GetReader(object callbackContext)
  399. {
  400. int index = (int)callbackContext;
  401. Fx.Assert(index < this.Count, "Invalid Context provided.");
  402. return GetReader(index, false);
  403. }
  404. public void VerifySignatureConfirmationWasFound()
  405. {
  406. ReceiveSecurityHeaderEntry entry;
  407. for (int i = 0; i < this.count; i++)
  408. {
  409. GetElementEntry(i, out entry);
  410. if (entry.elementCategory == ReceiveSecurityHeaderElementCategory.SignatureConfirmation)
  411. {
  412. return;
  413. }
  414. }
  415. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SignatureConfirmationWasExpected)));
  416. }
  417. }
  418. }