WSSecurityOneDotZeroSendSecurityHeader.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. //----------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Security
  5. {
  6. using System.IdentityModel.Tokens;
  7. using System.IO;
  8. using System.Runtime;
  9. using System.Security.Cryptography;
  10. using System.ServiceModel;
  11. using System.ServiceModel.Channels;
  12. using System.ServiceModel.Description;
  13. using System.ServiceModel.Diagnostics;
  14. using System.Xml;
  15. using ExclusiveCanonicalizationTransform = System.IdentityModel.ExclusiveCanonicalizationTransform;
  16. using HashStream = System.IdentityModel.HashStream;
  17. using IPrefixGenerator = System.IdentityModel.IPrefixGenerator;
  18. using ISecurityElement = System.IdentityModel.ISecurityElement;
  19. using ISignatureValueSecurityElement = System.IdentityModel.ISignatureValueSecurityElement;
  20. using PreDigestedSignedInfo = System.IdentityModel.PreDigestedSignedInfo;
  21. using Reference = System.IdentityModel.Reference;
  22. using SignedInfo = System.IdentityModel.SignedInfo;
  23. using SignedXml = System.IdentityModel.SignedXml;
  24. using StandardSignedInfo = System.IdentityModel.StandardSignedInfo;
  25. using System.ServiceModel.Security.Tokens;
  26. class WSSecurityOneDotZeroSendSecurityHeader : SendSecurityHeader
  27. {
  28. HashStream hashStream;
  29. PreDigestedSignedInfo signedInfo;
  30. SignedXml signedXml;
  31. SecurityKey signatureKey;
  32. MessagePartSpecification effectiveSignatureParts;
  33. SymmetricAlgorithm encryptingSymmetricAlgorithm;
  34. ReferenceList referenceList;
  35. SecurityKeyIdentifier encryptionKeyIdentifier;
  36. bool hasSignedEncryptedMessagePart;
  37. // For Transport Secrity we have to sign the 'To' header with the
  38. // supporting tokens.
  39. byte[] toHeaderHash = null;
  40. string toHeaderId = null;
  41. public WSSecurityOneDotZeroSendSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay,
  42. SecurityStandardsManager standardsManager,
  43. SecurityAlgorithmSuite algorithmSuite,
  44. MessageDirection direction)
  45. : base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, direction)
  46. {
  47. }
  48. protected string EncryptionAlgorithm
  49. {
  50. get { return this.AlgorithmSuite.DefaultEncryptionAlgorithm; }
  51. }
  52. protected XmlDictionaryString EncryptionAlgorithmDictionaryString
  53. {
  54. get { return this.AlgorithmSuite.DefaultEncryptionAlgorithmDictionaryString; }
  55. }
  56. protected override bool HasSignedEncryptedMessagePart
  57. {
  58. get
  59. {
  60. return this.hasSignedEncryptedMessagePart;
  61. }
  62. }
  63. void AddEncryptionReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, bool sign,
  64. out MemoryStream plainTextStream, out string encryptedDataId)
  65. {
  66. plainTextStream = new MemoryStream();
  67. XmlDictionaryWriter encryptingWriter = XmlDictionaryWriter.CreateTextWriter(plainTextStream);
  68. if (sign)
  69. {
  70. AddSignatureReference(header, headerId, prefixGenerator, encryptingWriter);
  71. }
  72. else
  73. {
  74. header.WriteHeader(encryptingWriter, this.Version);
  75. encryptingWriter.Flush();
  76. }
  77. encryptedDataId = this.GenerateId();
  78. referenceList.AddReferredId(encryptedDataId);
  79. }
  80. void AddSignatureReference(SecurityToken token, int position, SecurityTokenAttachmentMode mode)
  81. {
  82. SecurityKeyIdentifierClause keyIdentifierClause = null;
  83. bool strTransformEnabled = this.ShouldUseStrTransformForToken(token, position, mode, out keyIdentifierClause);
  84. AddTokenSignatureReference(token, keyIdentifierClause, strTransformEnabled);
  85. }
  86. void AddPrimaryTokenSignatureReference(SecurityToken token, SecurityTokenParameters securityTokenParameters)
  87. {
  88. // Currently we only support signing the primary token if the primary token is an issued token and protectTokens knob is set to true.
  89. // We will get rid of the below check when we support all token types.
  90. IssuedSecurityTokenParameters istp = securityTokenParameters as IssuedSecurityTokenParameters;
  91. if (istp == null)
  92. {
  93. return;
  94. }
  95. bool strTransformEnabled = istp != null && istp.UseStrTransform;
  96. SecurityKeyIdentifierClause keyIdentifierClause = null;
  97. // Only if the primary token is included in the message that we sign it because WCF at present does not resolve externally referenced tokens.
  98. // This means in the server's response
  99. if (ShouldSerializeToken(securityTokenParameters, this.MessageDirection))
  100. {
  101. if (strTransformEnabled)
  102. {
  103. keyIdentifierClause = securityTokenParameters.CreateKeyIdentifierClause(token, GetTokenReferenceStyle(securityTokenParameters));
  104. }
  105. AddTokenSignatureReference(token, keyIdentifierClause, strTransformEnabled);
  106. }
  107. }
  108. // Given a token and useStarTransform value this method adds apporopriate reference accordingly.
  109. // 1. If strTransform is disabled, it adds a reference to the token's id.
  110. // 2. Else if strtransform is enabled it adds a reference the security token's keyIdentifier's id.
  111. void AddTokenSignatureReference(SecurityToken token, SecurityKeyIdentifierClause keyIdentifierClause, bool strTransformEnabled)
  112. {
  113. if (!strTransformEnabled && token.Id == null)
  114. {
  115. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ElementToSignMustHaveId)), this.Message);
  116. }
  117. HashStream hashStream = TakeHashStream();
  118. XmlDictionaryWriter utf8Writer = TakeUtf8Writer();
  119. utf8Writer.StartCanonicalization(hashStream, false, null);
  120. this.StandardsManager.SecurityTokenSerializer.WriteToken(utf8Writer, token);
  121. utf8Writer.EndCanonicalization();
  122. if (strTransformEnabled)
  123. {
  124. if (keyIdentifierClause != null)
  125. {
  126. if (String.IsNullOrEmpty(keyIdentifierClause.Id))
  127. keyIdentifierClause.Id = SecurityUniqueId.Create().Value;
  128. this.ElementContainer.MapSecurityTokenToStrClause(token, keyIdentifierClause);
  129. this.signedInfo.AddReference(keyIdentifierClause.Id, hashStream.FlushHashAndGetValue(), true);
  130. }
  131. else
  132. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message);
  133. }
  134. else
  135. this.signedInfo.AddReference(token.Id, hashStream.FlushHashAndGetValue());
  136. }
  137. void AddSignatureReference(SendSecurityHeaderElement[] elements)
  138. {
  139. if (elements != null)
  140. {
  141. for (int i = 0; i < elements.Length; ++i)
  142. {
  143. SecurityKeyIdentifierClause keyIdentifierClause = null;
  144. TokenElement signedEncryptedTokenElement = elements[i].Item as TokenElement;
  145. // signedEncryptedTokenElement can either be a TokenElement ( in SignThenEncrypt case) or EncryptedData ( in !SignThenEncryptCase)
  146. // STR-Transform does not make sense in !SignThenEncrypt case .
  147. // note: signedEncryptedTokenElement can also be SignatureConfirmation but we do not care about it here.
  148. bool useStrTransform = signedEncryptedTokenElement != null
  149. && SignThenEncrypt
  150. && this.ShouldUseStrTransformForToken(signedEncryptedTokenElement.Token,
  151. i,
  152. SecurityTokenAttachmentMode.SignedEncrypted,
  153. out keyIdentifierClause);
  154. if (!useStrTransform && elements[i].Id == null)
  155. {
  156. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ElementToSignMustHaveId)), this.Message);
  157. }
  158. HashStream hashStream = TakeHashStream();
  159. XmlDictionaryWriter utf8Writer = TakeUtf8Writer();
  160. utf8Writer.StartCanonicalization(hashStream, false, null);
  161. elements[i].Item.WriteTo(utf8Writer, ServiceModelDictionaryManager.Instance);
  162. utf8Writer.EndCanonicalization();
  163. if (useStrTransform)
  164. {
  165. if (keyIdentifierClause != null)
  166. {
  167. if (String.IsNullOrEmpty(keyIdentifierClause.Id))
  168. keyIdentifierClause.Id = SecurityUniqueId.Create().Value;
  169. this.ElementContainer.MapSecurityTokenToStrClause(signedEncryptedTokenElement.Token, keyIdentifierClause);
  170. this.signedInfo.AddReference(keyIdentifierClause.Id, hashStream.FlushHashAndGetValue(), true);
  171. }
  172. else
  173. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message);
  174. }
  175. else
  176. this.signedInfo.AddReference(elements[i].Id, hashStream.FlushHashAndGetValue());
  177. }
  178. }
  179. }
  180. void AddSignatureReference(SecurityToken[] tokens, SecurityTokenAttachmentMode mode)
  181. {
  182. if (tokens != null)
  183. {
  184. for (int i = 0; i < tokens.Length; ++i)
  185. {
  186. AddSignatureReference(tokens[i], i, mode);
  187. }
  188. }
  189. }
  190. string GetSignatureHash(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, XmlDictionaryWriter writer, out byte[] hash)
  191. {
  192. HashStream hashStream = TakeHashStream();
  193. XmlDictionaryWriter effectiveWriter;
  194. XmlBuffer canonicalBuffer = null;
  195. if (writer.CanCanonicalize)
  196. {
  197. effectiveWriter = writer;
  198. }
  199. else
  200. {
  201. canonicalBuffer = new XmlBuffer(int.MaxValue);
  202. effectiveWriter = canonicalBuffer.OpenSection(XmlDictionaryReaderQuotas.Max);
  203. }
  204. effectiveWriter.StartCanonicalization(hashStream, false, null);
  205. header.WriteStartHeader(effectiveWriter, this.Version);
  206. if (headerId == null)
  207. {
  208. headerId = GenerateId();
  209. this.StandardsManager.IdManager.WriteIdAttribute(effectiveWriter, headerId);
  210. }
  211. header.WriteHeaderContents(effectiveWriter, this.Version);
  212. effectiveWriter.WriteEndElement();
  213. effectiveWriter.EndCanonicalization();
  214. effectiveWriter.Flush();
  215. if (!ReferenceEquals(effectiveWriter, writer))
  216. {
  217. Fx.Assert(canonicalBuffer != null, "Canonical buffer cannot be null.");
  218. canonicalBuffer.CloseSection();
  219. canonicalBuffer.Close();
  220. XmlDictionaryReader dicReader = canonicalBuffer.GetReader(0);
  221. writer.WriteNode(dicReader, false);
  222. dicReader.Close();
  223. }
  224. hash = hashStream.FlushHashAndGetValue();
  225. return headerId;
  226. }
  227. void AddSignatureReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, XmlDictionaryWriter writer)
  228. {
  229. byte[] hashValue;
  230. headerId = GetSignatureHash(header, headerId, prefixGenerator, writer, out hashValue);
  231. this.signedInfo.AddReference(headerId, hashValue);
  232. }
  233. void ApplySecurityAndWriteHeader(MessageHeader header, string headerId, XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
  234. {
  235. if (!this.RequireMessageProtection && this.ShouldSignToHeader)
  236. {
  237. if ((header.Name == XD.AddressingDictionary.To.Value) &&
  238. (header.Namespace == this.Message.Version.Addressing.Namespace))
  239. {
  240. if (this.toHeaderHash == null)
  241. {
  242. byte[] headerHash;
  243. headerId = GetSignatureHash(header, headerId, prefixGenerator, writer, out headerHash);
  244. this.toHeaderHash = headerHash;
  245. this.toHeaderId = headerId;
  246. }
  247. else
  248. // More than one 'To' header is specified in the message.
  249. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TransportSecuredMessageHasMoreThanOneToHeader)));
  250. return;
  251. }
  252. }
  253. MessagePartProtectionMode protectionMode = GetProtectionMode(header);
  254. MemoryStream plainTextStream;
  255. string encryptedDataId;
  256. switch (protectionMode)
  257. {
  258. case MessagePartProtectionMode.None:
  259. header.WriteHeader(writer, this.Version);
  260. return;
  261. case MessagePartProtectionMode.Sign:
  262. AddSignatureReference(header, headerId, prefixGenerator, writer);
  263. return;
  264. case MessagePartProtectionMode.SignThenEncrypt:
  265. AddEncryptionReference(header, headerId, prefixGenerator, true, out plainTextStream, out encryptedDataId);
  266. EncryptAndWriteHeader(header, encryptedDataId, plainTextStream, writer);
  267. this.hasSignedEncryptedMessagePart = true;
  268. return;
  269. case MessagePartProtectionMode.Encrypt:
  270. AddEncryptionReference(header, headerId, prefixGenerator, false, out plainTextStream, out encryptedDataId);
  271. EncryptAndWriteHeader(header, encryptedDataId, plainTextStream, writer);
  272. return;
  273. case MessagePartProtectionMode.EncryptThenSign:
  274. AddEncryptionReference(header, headerId, prefixGenerator, false, out plainTextStream, out encryptedDataId);
  275. EncryptedHeader encryptedHeader = EncryptHeader(
  276. header, this.encryptingSymmetricAlgorithm, this.encryptionKeyIdentifier, this.Version, encryptedDataId, plainTextStream);
  277. AddSignatureReference(encryptedHeader, encryptedDataId, prefixGenerator, writer);
  278. return;
  279. default:
  280. Fx.Assert("Invalid MessagePartProtectionMode");
  281. return;
  282. }
  283. }
  284. public override void ApplySecurityAndWriteHeaders(MessageHeaders headers, XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
  285. {
  286. string[] headerIds;
  287. if (this.RequireMessageProtection || this.ShouldSignToHeader)
  288. {
  289. headerIds = headers.GetHeaderAttributes(UtilityStrings.IdAttribute,
  290. this.StandardsManager.IdManager.DefaultIdNamespaceUri);
  291. }
  292. else
  293. {
  294. headerIds = null;
  295. }
  296. for (int i = 0; i < headers.Count; i++)
  297. {
  298. MessageHeader header = headers.GetMessageHeader(i);
  299. if (this.Version.Addressing == AddressingVersion.None && header.Namespace == AddressingVersion.None.Namespace)
  300. {
  301. continue;
  302. }
  303. if (header != this)
  304. {
  305. ApplySecurityAndWriteHeader(header, headerIds == null ? null : headerIds[i], writer, prefixGenerator);
  306. }
  307. }
  308. }
  309. static bool CanCanonicalizeAndFragment(XmlDictionaryWriter writer)
  310. {
  311. if (!writer.CanCanonicalize)
  312. {
  313. return false;
  314. }
  315. IFragmentCapableXmlDictionaryWriter fragmentingWriter = writer as IFragmentCapableXmlDictionaryWriter;
  316. return fragmentingWriter != null && fragmentingWriter.CanFragment;
  317. }
  318. public override void ApplyBodySecurity(XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
  319. {
  320. SecurityAppliedMessage message = this.SecurityAppliedMessage;
  321. EncryptedData encryptedData;
  322. HashStream hashStream;
  323. switch (message.BodyProtectionMode)
  324. {
  325. case MessagePartProtectionMode.None:
  326. return;
  327. case MessagePartProtectionMode.Sign:
  328. hashStream = TakeHashStream();
  329. if (CanCanonicalizeAndFragment(writer))
  330. {
  331. message.WriteBodyToSignWithFragments(hashStream, false, null, writer);
  332. }
  333. else
  334. {
  335. message.WriteBodyToSign(hashStream);
  336. }
  337. this.signedInfo.AddReference(message.BodyId, hashStream.FlushHashAndGetValue());
  338. return;
  339. case MessagePartProtectionMode.SignThenEncrypt:
  340. hashStream = TakeHashStream();
  341. encryptedData = CreateEncryptedDataForBody();
  342. if (CanCanonicalizeAndFragment(writer))
  343. {
  344. message.WriteBodyToSignThenEncryptWithFragments(hashStream, false, null, encryptedData, this.encryptingSymmetricAlgorithm, writer);
  345. }
  346. else
  347. {
  348. message.WriteBodyToSignThenEncrypt(hashStream, encryptedData, this.encryptingSymmetricAlgorithm);
  349. }
  350. this.signedInfo.AddReference(message.BodyId, hashStream.FlushHashAndGetValue());
  351. this.referenceList.AddReferredId(encryptedData.Id);
  352. this.hasSignedEncryptedMessagePart = true;
  353. return;
  354. case MessagePartProtectionMode.Encrypt:
  355. encryptedData = CreateEncryptedDataForBody();
  356. message.WriteBodyToEncrypt(encryptedData, this.encryptingSymmetricAlgorithm);
  357. this.referenceList.AddReferredId(encryptedData.Id);
  358. return;
  359. case MessagePartProtectionMode.EncryptThenSign:
  360. hashStream = TakeHashStream();
  361. encryptedData = CreateEncryptedDataForBody();
  362. message.WriteBodyToEncryptThenSign(hashStream, encryptedData, this.encryptingSymmetricAlgorithm);
  363. this.signedInfo.AddReference(message.BodyId, hashStream.FlushHashAndGetValue());
  364. this.referenceList.AddReferredId(encryptedData.Id);
  365. return;
  366. default:
  367. Fx.Assert("Invalid MessagePartProtectionMode");
  368. return;
  369. }
  370. }
  371. protected static MemoryStream CaptureToken(SecurityToken token, SecurityStandardsManager serializer)
  372. {
  373. MemoryStream stream = new MemoryStream();
  374. XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
  375. serializer.SecurityTokenSerializer.WriteToken(writer, token);
  376. writer.Flush();
  377. stream.Seek(0, SeekOrigin.Begin);
  378. return stream;
  379. }
  380. protected static MemoryStream CaptureSecurityElement(ISecurityElement element)
  381. {
  382. MemoryStream stream = new MemoryStream();
  383. XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
  384. element.WriteTo(writer, ServiceModelDictionaryManager.Instance);
  385. writer.Flush();
  386. stream.Seek(0, SeekOrigin.Begin);
  387. return stream;
  388. }
  389. protected override ISecurityElement CompleteEncryptionCore(
  390. SendSecurityHeaderElement primarySignature,
  391. SendSecurityHeaderElement[] basicTokens,
  392. SendSecurityHeaderElement[] signatureConfirmations,
  393. SendSecurityHeaderElement[] endorsingSignatures)
  394. {
  395. if (this.referenceList == null)
  396. {
  397. return null;
  398. }
  399. if (primarySignature != null && primarySignature.Item != null && primarySignature.MarkedForEncryption)
  400. {
  401. EncryptElement(primarySignature);
  402. }
  403. if (basicTokens != null)
  404. {
  405. for (int i = 0; i < basicTokens.Length; ++i)
  406. {
  407. if (basicTokens[i].MarkedForEncryption)
  408. EncryptElement(basicTokens[i]);
  409. }
  410. }
  411. if (signatureConfirmations != null)
  412. {
  413. for (int i = 0; i < signatureConfirmations.Length; ++i)
  414. {
  415. if (signatureConfirmations[i].MarkedForEncryption)
  416. EncryptElement(signatureConfirmations[i]);
  417. }
  418. }
  419. if (endorsingSignatures != null)
  420. {
  421. for (int i = 0; i < endorsingSignatures.Length; ++i)
  422. {
  423. if (endorsingSignatures[i].MarkedForEncryption)
  424. EncryptElement(endorsingSignatures[i]);
  425. }
  426. }
  427. try
  428. {
  429. return this.referenceList.DataReferenceCount > 0 ? this.referenceList : null;
  430. }
  431. finally
  432. {
  433. this.referenceList = null;
  434. this.encryptingSymmetricAlgorithm = null;
  435. this.encryptionKeyIdentifier = null;
  436. }
  437. }
  438. protected override ISignatureValueSecurityElement CompletePrimarySignatureCore(
  439. SendSecurityHeaderElement[] signatureConfirmations,
  440. SecurityToken[] signedEndorsingTokens,
  441. SecurityToken[] signedTokens,
  442. SendSecurityHeaderElement[] basicTokens, bool isPrimarySignature)
  443. {
  444. if (this.signedXml == null)
  445. {
  446. return null;
  447. }
  448. SecurityTimestamp timestamp = this.Timestamp;
  449. if (timestamp != null)
  450. {
  451. if (timestamp.Id == null)
  452. {
  453. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TimestampToSignHasNoId)));
  454. }
  455. HashStream hashStream = TakeHashStream();
  456. this.StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm(
  457. hashStream, timestamp, this.signedInfo.ResourcePool.TakeEncodingBuffer());
  458. signedInfo.AddReference(timestamp.Id, hashStream.FlushHashAndGetValue());
  459. }
  460. if ((this.ShouldSignToHeader) && (this.signatureKey is AsymmetricSecurityKey) && (this.Version.Addressing != AddressingVersion.None))
  461. {
  462. if (this.toHeaderHash != null)
  463. signedInfo.AddReference(this.toHeaderId, this.toHeaderHash);
  464. else
  465. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TransportSecurityRequireToHeader)));
  466. }
  467. AddSignatureReference(signatureConfirmations);
  468. if (isPrimarySignature && this.ShouldProtectTokens)
  469. {
  470. AddPrimaryTokenSignatureReference(this.ElementContainer.SourceSigningToken, this.SigningTokenParameters);
  471. }
  472. if (this.RequireMessageProtection)
  473. {
  474. AddSignatureReference(signedEndorsingTokens, SecurityTokenAttachmentMode.SignedEndorsing);
  475. AddSignatureReference(signedTokens, SecurityTokenAttachmentMode.Signed);
  476. AddSignatureReference(basicTokens);
  477. }
  478. if (this.signedInfo.ReferenceCount == 0)
  479. {
  480. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoPartsOfMessageMatchedPartsToSign)), this.Message);
  481. }
  482. try
  483. {
  484. this.signedXml.ComputeSignature(this.signatureKey);
  485. return this.signedXml;
  486. }
  487. finally
  488. {
  489. this.hashStream = null;
  490. this.signedInfo = null;
  491. this.signedXml = null;
  492. this.signatureKey = null;
  493. this.effectiveSignatureParts = null;
  494. }
  495. }
  496. EncryptedData CreateEncryptedData()
  497. {
  498. EncryptedData encryptedData = new EncryptedData();
  499. encryptedData.SecurityTokenSerializer = this.StandardsManager.SecurityTokenSerializer;
  500. encryptedData.KeyIdentifier = this.encryptionKeyIdentifier;
  501. encryptedData.EncryptionMethod = this.EncryptionAlgorithm;
  502. encryptedData.EncryptionMethodDictionaryString = this.EncryptionAlgorithmDictionaryString;
  503. return encryptedData;
  504. }
  505. EncryptedData CreateEncryptedData(MemoryStream stream, string id, bool typeElement)
  506. {
  507. EncryptedData encryptedData = CreateEncryptedData();
  508. encryptedData.Id = id;
  509. encryptedData.SetUpEncryption(this.encryptingSymmetricAlgorithm, new ArraySegment<byte>(stream.GetBuffer(), 0, (int) stream.Length));
  510. if (typeElement)
  511. {
  512. encryptedData.Type = EncryptedData.ElementType;
  513. }
  514. return encryptedData;
  515. }
  516. EncryptedData CreateEncryptedDataForBody()
  517. {
  518. EncryptedData encryptedData = CreateEncryptedData();
  519. encryptedData.Type = EncryptedData.ContentType;
  520. return encryptedData;
  521. }
  522. void EncryptAndWriteHeader(MessageHeader plainTextHeader, string id, MemoryStream stream, XmlDictionaryWriter writer)
  523. {
  524. EncryptedHeader encryptedHeader = EncryptHeader(
  525. plainTextHeader,
  526. this.encryptingSymmetricAlgorithm, this.encryptionKeyIdentifier, this.Version,
  527. id, stream);
  528. encryptedHeader.WriteHeader(writer, this.Version);
  529. }
  530. void EncryptElement(SendSecurityHeaderElement element)
  531. {
  532. string id = GenerateId();
  533. ISecurityElement encryptedElement = CreateEncryptedData(CaptureSecurityElement(element.Item), id, true);
  534. this.referenceList.AddReferredId(id);
  535. element.Replace(id, encryptedElement);
  536. }
  537. protected virtual EncryptedHeader EncryptHeader(MessageHeader plainTextHeader, SymmetricAlgorithm algorithm,
  538. SecurityKeyIdentifier keyIdentifier, MessageVersion version, string id, MemoryStream stream)
  539. {
  540. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  541. SR.GetString(SR.HeaderEncryptionNotSupportedInWsSecurityJan2004, plainTextHeader.Name, plainTextHeader.Namespace)));
  542. }
  543. HashStream TakeHashStream()
  544. {
  545. HashStream hashStream = null;
  546. if (this.hashStream == null)
  547. {
  548. this.hashStream = hashStream = new HashStream(CryptoHelper.CreateHashAlgorithm(this.AlgorithmSuite.DefaultDigestAlgorithm));
  549. }
  550. else
  551. {
  552. hashStream = this.hashStream;;
  553. hashStream.Reset();
  554. }
  555. return hashStream;
  556. }
  557. XmlDictionaryWriter TakeUtf8Writer()
  558. {
  559. return this.signedInfo.ResourcePool.TakeUtf8Writer();
  560. }
  561. MessagePartProtectionMode GetProtectionMode(MessageHeader header)
  562. {
  563. if (!this.RequireMessageProtection)
  564. {
  565. return MessagePartProtectionMode.None;
  566. }
  567. bool sign = this.signedInfo != null && this.effectiveSignatureParts.IsHeaderIncluded(header);
  568. bool encrypt = this.referenceList != null && this.EncryptionParts.IsHeaderIncluded(header);
  569. return MessagePartProtectionModeHelper.GetProtectionMode(sign, encrypt, this.SignThenEncrypt);
  570. }
  571. protected override void StartEncryptionCore(SecurityToken token, SecurityKeyIdentifier keyIdentifier)
  572. {
  573. this.encryptingSymmetricAlgorithm = SecurityUtils.GetSymmetricAlgorithm(this.EncryptionAlgorithm, token);
  574. if (this.encryptingSymmetricAlgorithm == null)
  575. {
  576. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
  577. SR.GetString(SR.UnableToCreateSymmetricAlgorithmFromToken, this.EncryptionAlgorithm)));
  578. }
  579. this.encryptionKeyIdentifier = keyIdentifier;
  580. this.referenceList = new ReferenceList();
  581. }
  582. protected override void StartPrimarySignatureCore(SecurityToken token,
  583. SecurityKeyIdentifier keyIdentifier,
  584. MessagePartSpecification signatureParts,
  585. bool generateTargettableSignature)
  586. {
  587. SecurityAlgorithmSuite suite = this.AlgorithmSuite;
  588. string canonicalizationAlgorithm = suite.DefaultCanonicalizationAlgorithm;
  589. XmlDictionaryString canonicalizationAlgorithmDictionaryString = suite.DefaultCanonicalizationAlgorithmDictionaryString;
  590. if (canonicalizationAlgorithm != SecurityAlgorithms.ExclusiveC14n)
  591. {
  592. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  593. new MessageSecurityException(SR.GetString(SR.UnsupportedCanonicalizationAlgorithm, suite.DefaultCanonicalizationAlgorithm)));
  594. }
  595. string signatureAlgorithm;
  596. XmlDictionaryString signatureAlgorithmDictionaryString;
  597. suite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out this.signatureKey, out signatureAlgorithmDictionaryString);
  598. string digestAlgorithm = suite.DefaultDigestAlgorithm;
  599. XmlDictionaryString digestAlgorithmDictionaryString = suite.DefaultDigestAlgorithmDictionaryString;
  600. this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, canonicalizationAlgorithm, canonicalizationAlgorithmDictionaryString, digestAlgorithm, digestAlgorithmDictionaryString, signatureAlgorithm, signatureAlgorithmDictionaryString);
  601. this.signedXml = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
  602. if (keyIdentifier != null)
  603. {
  604. this.signedXml.Signature.KeyIdentifier = keyIdentifier;
  605. }
  606. if (generateTargettableSignature)
  607. {
  608. this.signedXml.Id = GenerateId();
  609. }
  610. this.effectiveSignatureParts = signatureParts;
  611. this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(digestAlgorithm);
  612. }
  613. protected override ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier)
  614. {
  615. StartPrimarySignatureCore(token, identifier, MessagePartSpecification.NoParts, false);
  616. return CompletePrimarySignatureCore(null, null, null, null, false);
  617. }
  618. protected override ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier, ISecurityElement elementToSign)
  619. {
  620. SecurityAlgorithmSuite algorithmSuite = this.AlgorithmSuite;
  621. string signatureAlgorithm;
  622. XmlDictionaryString signatureAlgorithmDictionaryString;
  623. SecurityKey signatureKey;
  624. algorithmSuite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out signatureKey, out signatureAlgorithmDictionaryString);
  625. SignedXml signedXml = new SignedXml(ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
  626. SignedInfo signedInfo = signedXml.Signature.SignedInfo;
  627. signedInfo.CanonicalizationMethod = algorithmSuite.DefaultCanonicalizationAlgorithm;
  628. signedInfo.CanonicalizationMethodDictionaryString = algorithmSuite.DefaultCanonicalizationAlgorithmDictionaryString;
  629. signedInfo.SignatureMethod = signatureAlgorithm;
  630. signedInfo.SignatureMethodDictionaryString = signatureAlgorithmDictionaryString;
  631. if (elementToSign.Id == null)
  632. {
  633. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ElementToSignMustHaveId)));
  634. }
  635. Reference reference = new Reference(ServiceModelDictionaryManager.Instance, "#" + elementToSign.Id, elementToSign);
  636. reference.DigestMethod = algorithmSuite.DefaultDigestAlgorithm;
  637. reference.DigestMethodDictionaryString = algorithmSuite.DefaultDigestAlgorithmDictionaryString;
  638. reference.AddTransform(new ExclusiveCanonicalizationTransform());
  639. ((StandardSignedInfo)signedInfo).AddReference(reference);
  640. signedXml.ComputeSignature(signatureKey);
  641. if (identifier != null)
  642. {
  643. signedXml.Signature.KeyIdentifier = identifier;
  644. }
  645. return signedXml;
  646. }
  647. protected override void WriteSecurityTokenReferencyEntry(XmlDictionaryWriter writer, SecurityToken securityToken, SecurityTokenParameters securityTokenParameters)
  648. {
  649. SecurityKeyIdentifierClause keyIdentifierClause = null;
  650. // Given a token this method writes its corresponding security token reference entry in the security header
  651. // 1. If the token parameters is an issuedSecurityTokenParamter
  652. // 2. If UseStrTransform is enabled on it.
  653. IssuedSecurityTokenParameters issuedSecurityTokenParameters = securityTokenParameters as IssuedSecurityTokenParameters;
  654. if (issuedSecurityTokenParameters == null || !issuedSecurityTokenParameters.UseStrTransform)
  655. return;
  656. if (this.ElementContainer.TryGetIdentifierClauseFromSecurityToken(securityToken, out keyIdentifierClause))
  657. {
  658. if (keyIdentifierClause != null && !String.IsNullOrEmpty(keyIdentifierClause.Id))
  659. {
  660. WrappedXmlDictionaryWriter wrappedLocalWriter = new WrappedXmlDictionaryWriter(writer, keyIdentifierClause.Id);
  661. this.StandardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(wrappedLocalWriter, keyIdentifierClause);
  662. }
  663. else
  664. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message);
  665. }
  666. }
  667. }
  668. class WrappedXmlDictionaryWriter : XmlDictionaryWriter
  669. {
  670. XmlDictionaryWriter innerWriter;
  671. int index;
  672. bool insertId;
  673. bool isStrReferenceElement;
  674. string id;
  675. public WrappedXmlDictionaryWriter(XmlDictionaryWriter writer, string id)
  676. {
  677. this.innerWriter = writer;
  678. this.index = 0;
  679. this.insertId = false;
  680. this.isStrReferenceElement = false;
  681. this.id = id;
  682. }
  683. public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
  684. {
  685. if (isStrReferenceElement && this.insertId && localName == XD.UtilityDictionary.IdAttribute.Value)
  686. {
  687. // This means the serializer is already writing the Id out, so we don't write it again.
  688. this.insertId = false;
  689. }
  690. this.innerWriter.WriteStartAttribute(prefix, localName, namespaceUri);
  691. }
  692. public override void WriteStartElement(string prefix, string localName, string namespaceUri)
  693. {
  694. if (isStrReferenceElement && this.insertId)
  695. {
  696. if (id != null)
  697. {
  698. this.innerWriter.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
  699. }
  700. isStrReferenceElement = false;
  701. this.insertId = false;
  702. }
  703. index++;
  704. if (index == 1 && localName == XD.SecurityJan2004Dictionary.SecurityTokenReference.Value)
  705. {
  706. this.insertId = true;
  707. isStrReferenceElement = true;
  708. }
  709. this.innerWriter.WriteStartElement(prefix, localName, namespaceUri);
  710. }
  711. // Below methods simply call into innerWritter
  712. public override void Close()
  713. {
  714. this.innerWriter.Close();
  715. }
  716. public override void Flush()
  717. {
  718. this.innerWriter.Flush();
  719. }
  720. public override string LookupPrefix(string ns)
  721. {
  722. return this.innerWriter.LookupPrefix(ns);
  723. }
  724. public override void WriteBase64(byte[] buffer, int index, int count)
  725. {
  726. this.innerWriter.WriteBase64(buffer, index, count);
  727. }
  728. public override void WriteCData(string text)
  729. {
  730. this.innerWriter.WriteCData(text);
  731. }
  732. public override void WriteCharEntity(char ch)
  733. {
  734. this.innerWriter.WriteCharEntity(ch);
  735. }
  736. public override void WriteChars(char[] buffer, int index, int count)
  737. {
  738. this.innerWriter.WriteChars(buffer, index, count);
  739. }
  740. public override void WriteComment(string text)
  741. {
  742. this.innerWriter.WriteComment(text);
  743. }
  744. public override void WriteDocType(string name, string pubid, string sysid, string subset)
  745. {
  746. this.innerWriter.WriteDocType(name, pubid, sysid, subset);
  747. }
  748. public override void WriteEndAttribute()
  749. {
  750. this.innerWriter.WriteEndAttribute();
  751. }
  752. public override void WriteEndDocument()
  753. {
  754. this.innerWriter.WriteEndDocument();
  755. }
  756. public override void WriteEndElement()
  757. {
  758. this.innerWriter.WriteEndElement();
  759. }
  760. public override void WriteEntityRef(string name)
  761. {
  762. this.innerWriter.WriteEntityRef(name);
  763. }
  764. public override void WriteFullEndElement()
  765. {
  766. this.innerWriter.WriteFullEndElement();
  767. }
  768. public override void WriteProcessingInstruction(string name, string text)
  769. {
  770. this.innerWriter.WriteProcessingInstruction(name, text);
  771. }
  772. public override void WriteRaw(string data)
  773. {
  774. this.innerWriter.WriteRaw(data);
  775. }
  776. public override void WriteRaw(char[] buffer, int index, int count)
  777. {
  778. this.innerWriter.WriteRaw(buffer, index, count);
  779. }
  780. public override void WriteStartDocument(bool standalone)
  781. {
  782. this.innerWriter.WriteStartDocument(standalone);
  783. }
  784. public override void WriteStartDocument()
  785. {
  786. this.innerWriter.WriteStartDocument();
  787. }
  788. public override WriteState WriteState
  789. {
  790. get { return this.innerWriter.WriteState; }
  791. }
  792. public override void WriteString(string text)
  793. {
  794. this.innerWriter.WriteString(text);
  795. }
  796. public override void WriteSurrogateCharEntity(char lowChar, char highChar)
  797. {
  798. this.innerWriter.WriteSurrogateCharEntity(lowChar, highChar);
  799. }
  800. public override void WriteWhitespace(string ws)
  801. {
  802. this.innerWriter.WriteWhitespace(ws);
  803. }
  804. }
  805. }