SecurityVerifiedMessage.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Security
  5. {
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Runtime;
  9. using System.ServiceModel;
  10. using System.ServiceModel.Channels;
  11. using System.ServiceModel.Diagnostics;
  12. using System.Xml;
  13. sealed class SecurityVerifiedMessage : DelegatingMessage
  14. {
  15. byte[] decryptedBuffer;
  16. XmlDictionaryReader cachedDecryptedBodyContentReader;
  17. XmlAttributeHolder[] envelopeAttributes;
  18. XmlAttributeHolder[] headerAttributes;
  19. XmlAttributeHolder[] bodyAttributes;
  20. string envelopePrefix;
  21. bool bodyDecrypted;
  22. BodyState state = BodyState.Created;
  23. string bodyPrefix;
  24. bool isDecryptedBodyStatusDetermined;
  25. bool isDecryptedBodyFault;
  26. bool isDecryptedBodyEmpty;
  27. XmlDictionaryReader cachedReaderAtSecurityHeader;
  28. readonly ReceiveSecurityHeader securityHeader;
  29. XmlBuffer messageBuffer;
  30. bool canDelegateCreateBufferedCopyToInnerMessage;
  31. public SecurityVerifiedMessage(Message messageToProcess, ReceiveSecurityHeader securityHeader)
  32. : base(messageToProcess)
  33. {
  34. this.securityHeader = securityHeader;
  35. if (securityHeader.RequireMessageProtection)
  36. {
  37. XmlDictionaryReader messageReader;
  38. BufferedMessage bufferedMessage = this.InnerMessage as BufferedMessage;
  39. if (bufferedMessage != null && this.Headers.ContainsOnlyBufferedMessageHeaders)
  40. {
  41. messageReader = bufferedMessage.GetMessageReader();
  42. }
  43. else
  44. {
  45. this.messageBuffer = new XmlBuffer(int.MaxValue);
  46. XmlDictionaryWriter writer = this.messageBuffer.OpenSection(this.securityHeader.ReaderQuotas);
  47. this.InnerMessage.WriteMessage(writer);
  48. this.messageBuffer.CloseSection();
  49. this.messageBuffer.Close();
  50. messageReader = this.messageBuffer.GetReader(0);
  51. }
  52. MoveToSecurityHeader(messageReader, securityHeader.HeaderIndex, true);
  53. this.cachedReaderAtSecurityHeader = messageReader;
  54. this.state = BodyState.Buffered;
  55. }
  56. else
  57. {
  58. this.envelopeAttributes = XmlAttributeHolder.emptyArray;
  59. this.headerAttributes = XmlAttributeHolder.emptyArray;
  60. this.bodyAttributes = XmlAttributeHolder.emptyArray;
  61. this.canDelegateCreateBufferedCopyToInnerMessage = true;
  62. }
  63. }
  64. public override bool IsEmpty
  65. {
  66. get
  67. {
  68. if (this.IsDisposed)
  69. {
  70. // PreSharp Bug: Property get methods should not throw exceptions.
  71. #pragma warning suppress 56503
  72. throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
  73. }
  74. if (!this.bodyDecrypted)
  75. {
  76. return this.InnerMessage.IsEmpty;
  77. }
  78. EnsureDecryptedBodyStatusDetermined();
  79. return this.isDecryptedBodyEmpty;
  80. }
  81. }
  82. public override bool IsFault
  83. {
  84. get
  85. {
  86. if (this.IsDisposed)
  87. {
  88. // PreSharp Bug: Property get methods should not throw exceptions.
  89. #pragma warning suppress 56503
  90. throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
  91. }
  92. if (!this.bodyDecrypted)
  93. {
  94. return this.InnerMessage.IsFault;
  95. }
  96. EnsureDecryptedBodyStatusDetermined();
  97. return this.isDecryptedBodyFault;
  98. }
  99. }
  100. internal byte[] PrimarySignatureValue
  101. {
  102. get { return this.securityHeader.PrimarySignatureValue; }
  103. }
  104. internal ReceiveSecurityHeader ReceivedSecurityHeader
  105. {
  106. get { return this.securityHeader; }
  107. }
  108. Exception CreateBadStateException(string operation)
  109. {
  110. return new InvalidOperationException(SR.GetString(SR.MessageBodyOperationNotValidInBodyState,
  111. operation, this.state));
  112. }
  113. public XmlDictionaryReader CreateFullBodyReader()
  114. {
  115. switch (this.state)
  116. {
  117. case BodyState.Buffered:
  118. return CreateFullBodyReaderFromBufferedState();
  119. case BodyState.Decrypted:
  120. return CreateFullBodyReaderFromDecryptedState();
  121. default:
  122. throw TraceUtility.ThrowHelperError(CreateBadStateException("CreateFullBodyReader"), this);
  123. }
  124. }
  125. XmlDictionaryReader CreateFullBodyReaderFromBufferedState()
  126. {
  127. if (this.messageBuffer != null)
  128. {
  129. XmlDictionaryReader reader = this.messageBuffer.GetReader(0);
  130. MoveToBody(reader);
  131. return reader;
  132. }
  133. else
  134. {
  135. return ((BufferedMessage) this.InnerMessage).GetBufferedReaderAtBody();
  136. }
  137. }
  138. XmlDictionaryReader CreateFullBodyReaderFromDecryptedState()
  139. {
  140. XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(this.decryptedBuffer, 0, this.decryptedBuffer.Length, this.securityHeader.ReaderQuotas);
  141. MoveToBody(reader);
  142. return reader;
  143. }
  144. void EnsureDecryptedBodyStatusDetermined()
  145. {
  146. if (!this.isDecryptedBodyStatusDetermined)
  147. {
  148. XmlDictionaryReader reader = CreateFullBodyReader();
  149. if (Message.ReadStartBody(reader, this.InnerMessage.Version.Envelope, out this.isDecryptedBodyFault, out this.isDecryptedBodyEmpty))
  150. {
  151. this.cachedDecryptedBodyContentReader = reader;
  152. }
  153. else
  154. {
  155. reader.Close();
  156. }
  157. this.isDecryptedBodyStatusDetermined = true;
  158. }
  159. }
  160. public XmlAttributeHolder[] GetEnvelopeAttributes()
  161. {
  162. return this.envelopeAttributes;
  163. }
  164. public XmlAttributeHolder[] GetHeaderAttributes()
  165. {
  166. return this.headerAttributes;
  167. }
  168. XmlDictionaryReader GetReaderAtEnvelope()
  169. {
  170. if (this.messageBuffer != null)
  171. {
  172. return this.messageBuffer.GetReader(0);
  173. }
  174. else
  175. {
  176. return ((BufferedMessage) this.InnerMessage).GetMessageReader();
  177. }
  178. }
  179. public XmlDictionaryReader GetReaderAtFirstHeader()
  180. {
  181. XmlDictionaryReader reader = GetReaderAtEnvelope();
  182. MoveToHeaderBlock(reader, false);
  183. reader.ReadStartElement();
  184. return reader;
  185. }
  186. public XmlDictionaryReader GetReaderAtSecurityHeader()
  187. {
  188. if (this.cachedReaderAtSecurityHeader != null)
  189. {
  190. XmlDictionaryReader result = this.cachedReaderAtSecurityHeader;
  191. this.cachedReaderAtSecurityHeader = null;
  192. return result;
  193. }
  194. return this.Headers.GetReaderAtHeader(this.securityHeader.HeaderIndex);
  195. }
  196. void MoveToBody(XmlDictionaryReader reader)
  197. {
  198. if (reader.NodeType != XmlNodeType.Element)
  199. {
  200. reader.MoveToContent();
  201. }
  202. reader.ReadStartElement();
  203. if (reader.IsStartElement(XD.MessageDictionary.Header, this.Version.Envelope.DictionaryNamespace))
  204. {
  205. reader.Skip();
  206. }
  207. if (reader.NodeType != XmlNodeType.Element)
  208. {
  209. reader.MoveToContent();
  210. }
  211. }
  212. void MoveToHeaderBlock(XmlDictionaryReader reader, bool captureAttributes)
  213. {
  214. if (reader.NodeType != XmlNodeType.Element)
  215. {
  216. reader.MoveToContent();
  217. }
  218. if (captureAttributes)
  219. {
  220. this.envelopePrefix = reader.Prefix;
  221. this.envelopeAttributes = XmlAttributeHolder.ReadAttributes(reader);
  222. }
  223. reader.ReadStartElement();
  224. reader.MoveToStartElement(XD.MessageDictionary.Header, this.Version.Envelope.DictionaryNamespace);
  225. if (captureAttributes)
  226. {
  227. this.headerAttributes = XmlAttributeHolder.ReadAttributes(reader);
  228. }
  229. }
  230. void MoveToSecurityHeader(XmlDictionaryReader reader, int headerIndex, bool captureAttributes)
  231. {
  232. MoveToHeaderBlock(reader, captureAttributes);
  233. reader.ReadStartElement();
  234. while (true)
  235. {
  236. if (reader.NodeType != XmlNodeType.Element)
  237. {
  238. reader.MoveToContent();
  239. }
  240. if (headerIndex == 0)
  241. {
  242. break;
  243. }
  244. reader.Skip();
  245. headerIndex--;
  246. }
  247. }
  248. protected override void OnBodyToString(XmlDictionaryWriter writer)
  249. {
  250. if (this.state == BodyState.Created)
  251. {
  252. base.OnBodyToString(writer);
  253. }
  254. else
  255. {
  256. OnWriteBodyContents(writer);
  257. }
  258. }
  259. protected override void OnClose()
  260. {
  261. if (this.cachedDecryptedBodyContentReader != null)
  262. {
  263. try
  264. {
  265. this.cachedDecryptedBodyContentReader.Close();
  266. }
  267. catch (System.IO.IOException exception)
  268. {
  269. //
  270. // We only want to catch and log the I/O exception here
  271. // assuming reader only throw those exceptions
  272. //
  273. DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning);
  274. }
  275. finally
  276. {
  277. this.cachedDecryptedBodyContentReader = null;
  278. }
  279. }
  280. if (this.cachedReaderAtSecurityHeader != null)
  281. {
  282. try
  283. {
  284. this.cachedReaderAtSecurityHeader.Close();
  285. }
  286. catch (System.IO.IOException exception)
  287. {
  288. //
  289. // We only want to catch and log the I/O exception here
  290. // assuming reader only throw those exceptions
  291. //
  292. DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning);
  293. }
  294. finally
  295. {
  296. this.cachedReaderAtSecurityHeader = null;
  297. }
  298. }
  299. this.messageBuffer = null;
  300. this.decryptedBuffer = null;
  301. this.state = BodyState.Disposed;
  302. this.InnerMessage.Close();
  303. }
  304. protected override XmlDictionaryReader OnGetReaderAtBodyContents()
  305. {
  306. if (this.state == BodyState.Created)
  307. {
  308. return this.InnerMessage.GetReaderAtBodyContents();
  309. }
  310. if (this.bodyDecrypted)
  311. {
  312. EnsureDecryptedBodyStatusDetermined();
  313. }
  314. if (this.cachedDecryptedBodyContentReader != null)
  315. {
  316. XmlDictionaryReader result = this.cachedDecryptedBodyContentReader;
  317. this.cachedDecryptedBodyContentReader = null;
  318. return result;
  319. }
  320. else
  321. {
  322. XmlDictionaryReader reader = CreateFullBodyReader();
  323. reader.ReadStartElement();
  324. reader.MoveToContent();
  325. return reader;
  326. }
  327. }
  328. protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
  329. {
  330. if (this.canDelegateCreateBufferedCopyToInnerMessage && this.InnerMessage is BufferedMessage)
  331. {
  332. return this.InnerMessage.CreateBufferedCopy(maxBufferSize);
  333. }
  334. else
  335. {
  336. return base.OnCreateBufferedCopy(maxBufferSize);
  337. }
  338. }
  339. internal void OnMessageProtectionPassComplete(bool atLeastOneHeaderOrBodyEncrypted)
  340. {
  341. this.canDelegateCreateBufferedCopyToInnerMessage = !atLeastOneHeaderOrBodyEncrypted;
  342. }
  343. internal void OnUnencryptedPart(string name, string ns)
  344. {
  345. if (ns == null)
  346. {
  347. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotEncrypted, name)), this);
  348. }
  349. else
  350. {
  351. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotEncryptedNs, name, ns)), this);
  352. }
  353. }
  354. internal void OnUnsignedPart(string name, string ns)
  355. {
  356. if (ns == null)
  357. {
  358. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotSigned, name)), this);
  359. }
  360. else
  361. {
  362. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotSignedNs, name, ns)), this);
  363. }
  364. }
  365. protected override void OnWriteStartBody(XmlDictionaryWriter writer)
  366. {
  367. if (this.state == BodyState.Created)
  368. {
  369. this.InnerMessage.WriteStartBody(writer);
  370. return;
  371. }
  372. XmlDictionaryReader reader = CreateFullBodyReader();
  373. reader.MoveToContent();
  374. writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  375. writer.WriteAttributes(reader, false);
  376. reader.Close();
  377. }
  378. protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
  379. {
  380. if (this.state == BodyState.Created)
  381. {
  382. this.InnerMessage.WriteBodyContents(writer);
  383. return;
  384. }
  385. XmlDictionaryReader reader = CreateFullBodyReader();
  386. reader.ReadStartElement();
  387. while (reader.NodeType != XmlNodeType.EndElement)
  388. writer.WriteNode(reader, false);
  389. reader.ReadEndElement();
  390. reader.Close();
  391. }
  392. public void SetBodyPrefixAndAttributes(XmlDictionaryReader bodyReader)
  393. {
  394. this.bodyPrefix = bodyReader.Prefix;
  395. this.bodyAttributes = XmlAttributeHolder.ReadAttributes(bodyReader);
  396. }
  397. public void SetDecryptedBody(byte[] decryptedBodyContent)
  398. {
  399. if (this.state != BodyState.Buffered)
  400. {
  401. throw TraceUtility.ThrowHelperError(CreateBadStateException("SetDecryptedBody"), this);
  402. }
  403. MemoryStream stream = new MemoryStream();
  404. XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
  405. writer.WriteStartElement(this.envelopePrefix, XD.MessageDictionary.Envelope, this.Version.Envelope.DictionaryNamespace);
  406. XmlAttributeHolder.WriteAttributes(this.envelopeAttributes, writer);
  407. writer.WriteStartElement(this.bodyPrefix, XD.MessageDictionary.Body, this.Version.Envelope.DictionaryNamespace);
  408. XmlAttributeHolder.WriteAttributes(this.bodyAttributes, writer);
  409. writer.WriteString(" "); // ensure non-empty element
  410. writer.WriteEndElement();
  411. writer.WriteEndElement();
  412. writer.Flush();
  413. this.decryptedBuffer = ContextImportHelper.SpliceBuffers(decryptedBodyContent, stream.GetBuffer(), (int) stream.Length, 2);
  414. this.bodyDecrypted = true;
  415. this.state = BodyState.Decrypted;
  416. }
  417. enum BodyState
  418. {
  419. Created,
  420. Buffered,
  421. Decrypted,
  422. Disposed,
  423. }
  424. }
  425. // Adding wrapping tags using a writer is a temporary feature to
  426. // support interop with a partner. Eventually, the serialization
  427. // team will add a feature to XmlUTF8TextReader to directly
  428. // support the addition of outer namespaces before creating a
  429. // Reader. This roundabout way of supporting context-sensitive
  430. // decryption can then be removed.
  431. static class ContextImportHelper
  432. {
  433. internal static XmlDictionaryReader CreateSplicedReader(byte[] decryptedBuffer,
  434. XmlAttributeHolder[] outerContext1, XmlAttributeHolder[] outerContext2, XmlAttributeHolder[] outerContext3, XmlDictionaryReaderQuotas quotas)
  435. {
  436. const string wrapper1 = "x";
  437. const string wrapper2 = "y";
  438. const string wrapper3 = "z";
  439. const int wrappingDepth = 3;
  440. MemoryStream stream = new MemoryStream();
  441. XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
  442. writer.WriteStartElement(wrapper1);
  443. WriteNamespaceDeclarations(outerContext1, writer);
  444. writer.WriteStartElement(wrapper2);
  445. WriteNamespaceDeclarations(outerContext2, writer);
  446. writer.WriteStartElement(wrapper3);
  447. WriteNamespaceDeclarations(outerContext3, writer);
  448. writer.WriteString(" "); // ensure non-empty element
  449. writer.WriteEndElement();
  450. writer.WriteEndElement();
  451. writer.WriteEndElement();
  452. writer.Flush();
  453. byte[] splicedBuffer = SpliceBuffers(decryptedBuffer, stream.GetBuffer(), (int) stream.Length, wrappingDepth);
  454. XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(splicedBuffer, quotas);
  455. reader.ReadStartElement(wrapper1);
  456. reader.ReadStartElement(wrapper2);
  457. reader.ReadStartElement(wrapper3);
  458. if (reader.NodeType != XmlNodeType.Element)
  459. {
  460. reader.MoveToContent();
  461. }
  462. return reader;
  463. }
  464. internal static string GetPrefixIfNamespaceDeclaration(string prefix, string localName)
  465. {
  466. if (prefix == "xmlns")
  467. {
  468. return localName;
  469. }
  470. if (prefix.Length == 0 && localName == "xmlns")
  471. {
  472. return string.Empty;
  473. }
  474. return null;
  475. }
  476. static bool IsNamespaceDeclaration(string prefix, string localName)
  477. {
  478. return GetPrefixIfNamespaceDeclaration(prefix, localName) != null;
  479. }
  480. internal static byte[] SpliceBuffers(byte[] middle, byte[] wrapper, int wrapperLength, int wrappingDepth)
  481. {
  482. const byte openChar = (byte) '<';
  483. int openCharsFound = 0;
  484. int openCharIndex;
  485. for (openCharIndex = wrapperLength - 1; openCharIndex >= 0; openCharIndex--)
  486. {
  487. if (wrapper[openCharIndex] == openChar)
  488. {
  489. openCharsFound++;
  490. if (openCharsFound == wrappingDepth)
  491. {
  492. break;
  493. }
  494. }
  495. }
  496. Fx.Assert(openCharIndex > 0, "");
  497. byte[] splicedBuffer = DiagnosticUtility.Utility.AllocateByteArray(checked(middle.Length + wrapperLength - 1));
  498. int offset = 0;
  499. int count = openCharIndex - 1;
  500. Buffer.BlockCopy(wrapper, 0, splicedBuffer, offset, count);
  501. offset += count;
  502. count = middle.Length;
  503. Buffer.BlockCopy(middle, 0, splicedBuffer, offset, count);
  504. offset += count;
  505. count = wrapperLength - openCharIndex;
  506. Buffer.BlockCopy(wrapper, openCharIndex, splicedBuffer, offset, count);
  507. return splicedBuffer;
  508. }
  509. static void WriteNamespaceDeclarations(XmlAttributeHolder[] attributes, XmlWriter writer)
  510. {
  511. if (attributes != null)
  512. {
  513. for (int i = 0; i < attributes.Length; i++)
  514. {
  515. XmlAttributeHolder a = attributes[i];
  516. if (IsNamespaceDeclaration(a.Prefix, a.LocalName))
  517. {
  518. a.WriteTo(writer);
  519. }
  520. }
  521. }
  522. }
  523. }
  524. }