IssuedSecurityTokenProviderTest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. //
  2. // IssuedSecurityTokenProviderTest.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2006 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Globalization;
  31. using System.IO;
  32. using System.Security.Cryptography;
  33. using System.Security.Cryptography.X509Certificates;
  34. using System.Security.Cryptography.Xml;
  35. using System.ServiceModel;
  36. using System.ServiceModel.Channels;
  37. using System.ServiceModel.Security;
  38. using System.ServiceModel.Security.Tokens;
  39. using System.IdentityModel.Tokens;
  40. using System.Text;
  41. using System.Xml;
  42. using NUnit.Framework;
  43. using MonoTests.System.ServiceModel.Channels;
  44. namespace MonoTests.System.ServiceModel.Security.Tokens
  45. {
  46. [TestFixture]
  47. public class IssuedSecurityTokenProviderTest
  48. {
  49. [Test]
  50. public void DefaultValues ()
  51. {
  52. IssuedSecurityTokenProvider p =
  53. new IssuedSecurityTokenProvider ();
  54. Assert.AreEqual (true, p.CacheIssuedTokens, "#1");
  55. Assert.AreEqual (TimeSpan.FromMinutes (1), p.DefaultOpenTimeout, "#2");
  56. Assert.AreEqual (TimeSpan.FromMinutes (1), p.DefaultCloseTimeout, "#3");
  57. Assert.IsNotNull (p.IdentityVerifier, "#4");
  58. Assert.AreEqual (60, p.IssuedTokenRenewalThresholdPercentage, "#5");
  59. Assert.IsNull (p.IssuerAddress, "#6");
  60. Assert.AreEqual (0, p.IssuerChannelBehaviors.Count, "#7");
  61. Assert.AreEqual (SecurityKeyEntropyMode.CombinedEntropy, p.KeyEntropyMode, "#8");
  62. Assert.AreEqual (TimeSpan.MaxValue, p.MaxIssuedTokenCachingTime, "#9");
  63. Assert.AreEqual (MessageSecurityVersion.Default,
  64. p.MessageSecurityVersion, "#10");
  65. Assert.IsNull (p.SecurityAlgorithmSuite, "#11");
  66. Assert.IsNull (p.SecurityTokenSerializer, "#12");
  67. Assert.IsNull (p.TargetAddress, "#13");
  68. Assert.AreEqual (true, p.SupportsTokenCancellation, "#14");
  69. Assert.AreEqual (0, p.TokenRequestParameters.Count, "#15");
  70. Assert.IsNull (p.IssuerBinding, "#16");
  71. }
  72. [Test]
  73. [ExpectedException (typeof (InvalidOperationException))]
  74. public void OpenWithoutSerializer ()
  75. {
  76. IssuedSecurityTokenProvider p =
  77. new IssuedSecurityTokenProvider ();
  78. p.Open ();
  79. }
  80. [Test]
  81. [ExpectedException (typeof (InvalidOperationException))]
  82. public void OpenWithoutIssuerAddress ()
  83. {
  84. IssuedSecurityTokenProvider p =
  85. new IssuedSecurityTokenProvider ();
  86. p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
  87. p.Open ();
  88. }
  89. [Test]
  90. [ExpectedException (typeof (InvalidOperationException))]
  91. public void OpenWithoutBinding ()
  92. {
  93. IssuedSecurityTokenProvider p =
  94. new IssuedSecurityTokenProvider ();
  95. p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
  96. p.IssuerAddress = new EndpointAddress ("http://localhost:8080");
  97. p.Open ();
  98. }
  99. [Test]
  100. [ExpectedException (typeof (InvalidOperationException))]
  101. public void OpenWithoutTargetAddress ()
  102. {
  103. IssuedSecurityTokenProvider p =
  104. new IssuedSecurityTokenProvider ();
  105. p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
  106. p.IssuerAddress = new EndpointAddress ("http://localhost:8080");
  107. p.IssuerBinding = new BasicHttpBinding ();
  108. // wiithout it indigo causes NRE
  109. p.SecurityAlgorithmSuite = SecurityAlgorithmSuite.Default;
  110. p.Open ();
  111. }
  112. [Test]
  113. [Category ("NotWorking")]
  114. public void Open ()
  115. {
  116. IssuedSecurityTokenProvider p = SetupProvider (new BasicHttpBinding ());
  117. try {
  118. p.Open ();
  119. } finally {
  120. if (p.State == CommunicationState.Opened)
  121. p.Close ();
  122. }
  123. }
  124. [Test]
  125. [ExpectedException (typeof (InvalidOperationException))]
  126. public void GetTokenWithoutOpen ()
  127. {
  128. IssuedSecurityTokenProvider p =
  129. new IssuedSecurityTokenProvider ();
  130. p.GetToken (TimeSpan.FromSeconds (10));
  131. }
  132. // From WinFX beta2:
  133. // System.ServiceModel.Security.SecurityNegotiationException :
  134. // SOAP security negotiation with 'stream:dummy' for target
  135. // 'stream:dummy' failed. See inner exception for more details.
  136. // ----> System.InvalidOperationException : The request
  137. // message must be protected. This is required by an operation
  138. // of the contract ('IWsTrustFeb2005SecurityTokenService',
  139. // 'http://tempuri.org/'). The protection must be provided by
  140. // the binding ('BasicHttpBinding','http://tempuri.org/').
  141. [Test]
  142. [ExpectedException (typeof (SecurityNegotiationException))]
  143. [Category ("NotWorking")]
  144. public void GetTokenNoSecureBinding ()
  145. {
  146. IssuedSecurityTokenProvider p = SetupProvider (new BasicHttpBinding ());
  147. try {
  148. p.Open ();
  149. p.GetToken (TimeSpan.FromSeconds (10));
  150. } finally {
  151. if (p.State == CommunicationState.Opened)
  152. p.Close ();
  153. }
  154. }
  155. [Test]
  156. // SymmetricSecurityBindingElement requires protection
  157. // token parameters to build a channel or listener factory.
  158. [ExpectedException (typeof (SecurityNegotiationException))]
  159. [Category ("NotWorking")]
  160. public void GetTokenWithoutProtectionTokenParameters ()
  161. {
  162. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (null, false));
  163. try {
  164. p.Open ();
  165. p.GetToken (TimeSpan.FromSeconds (10));
  166. } finally {
  167. if (p.State == CommunicationState.Opened)
  168. p.Close ();
  169. }
  170. }
  171. // SecurityNegotiationException (InvalidOperationException (
  172. // "The service certificate is not provided for target
  173. // 'stream:dummy'. Specify a service certificate in
  174. // ClientCredentials."))
  175. [Test]
  176. [ExpectedException (typeof (SecurityNegotiationException))]
  177. [Category ("NotWorking")]
  178. public void GetTokenWithoutServiceCertificate ()
  179. {
  180. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (null, true));
  181. p.IssuerAddress = new EndpointAddress ("stream:dummy");
  182. try {
  183. p.Open (TimeSpan.FromSeconds (5));
  184. p.GetToken (TimeSpan.FromSeconds (10));
  185. } finally {
  186. if (p.State == CommunicationState.Opened)
  187. p.Close ();
  188. }
  189. }
  190. [Test]
  191. [Category ("NotWorking")]
  192. [ExpectedException (typeof (MyException))]
  193. public void GetTokenWrongResponse ()
  194. {
  195. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetTokenWrongResponse), true));
  196. try {
  197. p.Open (TimeSpan.FromSeconds (5));
  198. p.GetToken (TimeSpan.FromSeconds (10));
  199. } finally {
  200. if (p.State == CommunicationState.Opened)
  201. p.Close ();
  202. }
  203. }
  204. [Test]
  205. [Category ("NotWorking")]
  206. [ExpectedException (typeof (MessageSecurityException))]
  207. public void GetTokenUnsignedReply ()
  208. {
  209. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetTokenUnsignedReply), true));
  210. try {
  211. p.Open (TimeSpan.FromSeconds (5));
  212. p.GetToken (TimeSpan.FromSeconds (10));
  213. } finally {
  214. if (p.State == CommunicationState.Opened)
  215. p.Close ();
  216. }
  217. }
  218. // InnerException: System.InvalidOperationException:
  219. // The issuer must provide a computed key in key entropy mode
  220. // 'CombinedEntropy'.
  221. [Test]
  222. [Ignore ("todo")]
  223. [ExpectedException (typeof (SecurityNegotiationException))]
  224. public void GetTokenNoEntropyInResponseInCombinedMode ()
  225. {
  226. // FIXME: implement it after we get working token issuer.
  227. // In the reply, do not include Nonce
  228. }
  229. // on the other hand, in Client entropy mode it must not
  230. // provide entropy.
  231. [Test]
  232. [Ignore ("todo")]
  233. [ExpectedException (typeof (SecurityNegotiationException))]
  234. public void GetTokenIncludesEntropyInResponseInClientMode ()
  235. {
  236. // FIXME: implement it after we get working token issuer.
  237. // specify SecurityKeyEntropyMode.ClientEntropy on
  238. // client side. And in the reply, include Nonce.
  239. }
  240. [Test]
  241. [Ignore ("need to implement response")]
  242. [Category ("NotWorking")]
  243. public void GetToken ()
  244. {
  245. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetToken), true));
  246. try {
  247. p.Open (TimeSpan.FromSeconds (5));
  248. p.GetToken (TimeSpan.FromSeconds (10));
  249. } finally {
  250. if (p.State == CommunicationState.Opened)
  251. p.Close ();
  252. }
  253. }
  254. class MyException : Exception
  255. {
  256. }
  257. Message OnGetTokenWrongResponse (Message input)
  258. {
  259. VerifyInput (input.CreateBufferedCopy (10000));
  260. throw new MyException ();
  261. }
  262. Message OnGetTokenUnsignedReply (Message input)
  263. {
  264. XmlDocument doc = new XmlDocument ();
  265. doc.LoadXml ("<Response>RESPONSE</Response>");
  266. Message msg = Message.CreateMessage (input.Version, "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/IssueResponse", doc.DocumentElement);
  267. msg.Headers.Add (MessageHeader.CreateHeader (
  268. "Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", null, true));
  269. return msg;
  270. }
  271. Message OnGetToken (Message input)
  272. {
  273. MessageBuffer buf = input.CreateBufferedCopy (10000);
  274. VerifyInput2 (buf);
  275. // FIXME: create response message (when I understand what I should return.)
  276. // throw new MyException ();
  277. //*
  278. XmlDocument doc = new XmlDocument ();
  279. doc.LoadXml ("<Response>RESPONSE</Response>");
  280. X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
  281. SignedXml sxml = new SignedXml (doc);
  282. MemoryStream ms = new MemoryStream (new byte [] {1, 2, 3});
  283. sxml.AddReference (new Reference (ms));
  284. sxml.SigningKey = cert.PrivateKey;
  285. sxml.ComputeSignature ();
  286. Message msg = Message.CreateMessage (input.Version, "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue", sxml.GetXml ());
  287. msg.Headers.Add (MessageHeader.CreateHeader (
  288. "Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", null, true));
  289. return msg;
  290. //*/
  291. }
  292. void VerifyInput (MessageBuffer buf)
  293. {
  294. Message input = buf.CreateMessage ();
  295. /*
  296. XmlWriterSettings settings = new XmlWriterSettings ();
  297. settings.Indent = true;
  298. using (XmlWriter w = XmlWriter.Create (Console.Error, settings)) {
  299. buf.CreateMessage ().WriteMessage (w);
  300. }
  301. Console.Error.WriteLine ("******************** DONE ********************");
  302. Console.Error.Flush ();
  303. */
  304. Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", input.Headers.Action, "GetToken.Request.Action");
  305. Assert.IsNotNull (input.Headers.MessageId, "GetToken.Request.MessageID");
  306. // in the raw Message it is "http://www.w3.org/2005/08/addressing/anonymous", but it is replaced by MessageHeaders implementation.
  307. Assert.AreEqual (new EndpointAddress ("http://schemas.microsoft.com/2005/12/ServiceModel/Addressing/Anonymous"), input.Headers.ReplyTo, "GetToken.Request.ReplyTo");
  308. // o:Security
  309. // FIXME: test WSSecurity more
  310. // <o:Security>
  311. // <u:Timestamp>
  312. // <u:Created>...</u:Created>
  313. // <u:Expires>...</u:Expires>
  314. // </u:Timestamp>
  315. // <o:BinarySecurityToken>...</o:BinarySecurityToken>
  316. // <e:EncryptedKey>
  317. // <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
  318. // <KeyInfo>
  319. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  320. // </KeyInfo>
  321. // <e:CipherData>
  322. // <e:CipherValue>...</e:CipherValue>
  323. // </e:CipherData>
  324. // </e:EncryptedKey>
  325. // [
  326. // <c:DerivedKeyToken>
  327. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  328. // <c:Offset>...</c:Offset>
  329. // <c:Length>...</c:Length>
  330. // <c:Nonce>...</c:Nonce>
  331. // </c:DerivedKeyToken>
  332. // ]
  333. // <e:ReferenceList>
  334. // [
  335. // <e:DataReference>
  336. // ]
  337. // </e:ReferenceList>
  338. // <e:EncryptedData>
  339. // <e:EncryptionMethod/>
  340. // <KeyInfo> {{....}} </KeyInfo>
  341. // <e:CipherData> {{....}} </e:CipherData>
  342. // </e:EncryptedData>
  343. // </o:Security>
  344. int i = input.Headers.FindHeader ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  345. Assert.IsTrue (i >= 0, "Security header existence");
  346. MessageHeaderInfo info = input.Headers [i];
  347. Assert.IsNotNull (info, "Security header item");
  348. XmlReader r = input.Headers.GetReaderAtHeader (i);
  349. // FIXME: test WSSecurity more
  350. // <o:Security>
  351. r.MoveToContent ();
  352. r.ReadStartElement ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  353. // <u:Timestamp>
  354. r.MoveToContent ();
  355. r.ReadStartElement ("Timestamp", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  356. // <u:Created>...</u:Created>
  357. r.MoveToContent ();
  358. r.ReadStartElement ("Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  359. r.ReadString ();
  360. r.MoveToContent ();
  361. r.ReadEndElement ();
  362. // <u:Expires>...</u:Expires>
  363. r.MoveToContent ();
  364. r.ReadStartElement ("Expires", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  365. r.ReadString ();
  366. r.MoveToContent ();
  367. r.ReadEndElement ();
  368. // </u:Timestamp>
  369. r.MoveToContent ();
  370. r.ReadEndElement ();
  371. // <o:BinarySecurityToken>...</o:BinarySecurityToken>
  372. r.MoveToContent ();
  373. r.ReadStartElement ("BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  374. byte [] rawcert = Convert.FromBase64String (r.ReadString ());
  375. r.ReadEndElement ();
  376. X509Certificate2 cert = new X509Certificate2 (rawcert);
  377. // FIXME: test EncryptedKey
  378. r.MoveToContent ();
  379. r.Skip ();
  380. // <e:EncryptedKey>
  381. // <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
  382. // <KeyInfo>
  383. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  384. // </KeyInfo>
  385. // <e:CipherData>
  386. // <e:CipherValue>...</e:CipherValue>
  387. // </e:CipherData>
  388. // </e:EncryptedKey>
  389. // FIXME: test DerivedKeyTokens
  390. r.MoveToContent ();
  391. while (r.LocalName == "DerivedKeyToken") {
  392. r.Skip ();
  393. r.MoveToContent ();
  394. }
  395. // [
  396. // <c:DerivedKeyToken>
  397. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  398. // <c:Offset>...</c:Offset>
  399. // <c:Length>...</c:Length>
  400. // <c:Nonce>...</c:Nonce>
  401. // </c:DerivedKeyToken>
  402. // ]
  403. // <e:ReferenceList>
  404. // [
  405. // <e:DataReference>
  406. // ]
  407. // </e:ReferenceList>
  408. // <e:EncryptedData>
  409. // <e:EncryptionMethod/>
  410. // <KeyInfo> {{....}} </KeyInfo>
  411. // <e:CipherData> {{....}} </e:CipherData>
  412. // </e:EncryptedData>
  413. // </o:Security>
  414. // SOAP Body
  415. r = input.GetReaderAtBodyContents (); // just verifying itself ;)
  416. }
  417. XmlElement VerifyInput2 (MessageBuffer buf)
  418. {
  419. Message msg2 = buf.CreateMessage ();
  420. StringWriter sw = new StringWriter ();
  421. using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw))) {
  422. msg2.WriteMessage (w);
  423. }
  424. XmlDocument doc = new XmlDocument ();
  425. doc.PreserveWhitespace = true;
  426. doc.LoadXml (sw.ToString ());
  427. // decrypt the key with service certificate privkey
  428. PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
  429. EncryptedXml encXml = new EncryptedXml (doc);
  430. encXml.Padding = mode;
  431. X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
  432. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  433. nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
  434. nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
  435. nsmgr.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  436. nsmgr.AddNamespace ("e", "http://www.w3.org/2001/04/xmlenc#");
  437. nsmgr.AddNamespace ("dsig", "http://www.w3.org/2000/09/xmldsig#");
  438. XmlNode n = doc.SelectSingleNode ("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);
  439. Assert.IsNotNull (n, "premise: enckey does not exist");
  440. string raw = n.InnerText;
  441. byte [] rawbytes = Convert.FromBase64String (raw);
  442. RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert2.PrivateKey;
  443. byte [] decryptedKey = EncryptedXml.DecryptKey (rawbytes, rsa, true);//rsa.Decrypt (rawbytes, true);
  444. #if false
  445. // create derived keys
  446. Dictionary<string,byte[]> keys = new Dictionary<string,byte[]> ();
  447. InMemorySymmetricSecurityKey skey =
  448. new InMemorySymmetricSecurityKey (decryptedKey);
  449. foreach (XmlElement el in doc.SelectNodes ("//o:Security/c:DerivedKeyToken", nsmgr)) {
  450. n = el.SelectSingleNode ("c:Offset", nsmgr);
  451. int offset = (n == null) ? 0 :
  452. int.Parse (n.InnerText, CultureInfo.InvariantCulture);
  453. n = el.SelectSingleNode ("c:Length", nsmgr);
  454. int length = (n == null) ? 32 :
  455. int.Parse (n.InnerText, CultureInfo.InvariantCulture);
  456. n = el.SelectSingleNode ("c:Label", nsmgr);
  457. byte [] label = (n == null) ? decryptedKey :
  458. Convert.FromBase64String (n.InnerText);
  459. n = el.SelectSingleNode ("c:Nonce", nsmgr);
  460. byte [] nonce = (n == null) ? new byte [0] :
  461. Convert.FromBase64String (n.InnerText);
  462. byte [] derkey = skey.GenerateDerivedKey (
  463. //SecurityAlgorithms.Psha1KeyDerivation,
  464. "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
  465. // FIXME: maybe due to the label, this key resolution somehow does not seem to work.
  466. label,
  467. nonce,
  468. length * 8,
  469. offset);
  470. keys [el.GetAttribute ("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
  471. }
  472. #endif
  473. // decrypt the signature with the decrypted key
  474. #if true
  475. n = doc.SelectSingleNode ("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
  476. Assert.IsNotNull (n, "premise: encdata does not exist");
  477. raw = n.InnerText;
  478. rawbytes = Convert.FromBase64String (raw);
  479. Rijndael aes = RijndaelManaged.Create ();
  480. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  481. aes.Key = decryptedKey;
  482. aes.Mode = CipherMode.CBC;
  483. aes.Padding = mode;
  484. MemoryStream ms = new MemoryStream ();
  485. CryptoStream cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
  486. cs.Write (rawbytes, 0, rawbytes.Length);
  487. cs.Close ();
  488. byte [] decryptedSignature = ms.ToArray ();
  489. #else
  490. Rijndael aes = RijndaelManaged.Create ();
  491. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  492. aes.Key = decryptedKey;
  493. aes.Mode = CipherMode.CBC;
  494. aes.Padding = mode;
  495. EncryptedData ed = new EncryptedData ();
  496. n = doc.SelectSingleNode ("//o:Security/e:EncryptedData", nsmgr);
  497. Assert.IsNotNull (n, "premise: encdata does not exist");
  498. ed.LoadXml (n as XmlElement);
  499. byte [] decryptedSignature = encXml.DecryptData (ed, aes);
  500. #endif
  501. //Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
  502. //Console.Error.WriteLine ("============= Decrypted Signature End ===========");
  503. // decrypt the body with the decrypted key
  504. #if true
  505. n = doc.SelectSingleNode ("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
  506. Assert.IsNotNull (n, "premise: encdata does not exist");
  507. raw = n.InnerText;
  508. rawbytes = Convert.FromBase64String (raw);
  509. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  510. aes.Key = decryptedKey;
  511. ms = new MemoryStream ();
  512. cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
  513. cs.Write (rawbytes, 0, rawbytes.Length);
  514. cs.Close ();
  515. byte [] decryptedBody = ms.ToArray ();
  516. #else
  517. // decrypt the body with the decrypted key
  518. EncryptedData ed2 = new EncryptedData ();
  519. XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
  520. ed2.LoadXml (el);
  521. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  522. aes.Key = decryptedKey;
  523. byte [] decryptedBody = encXml.DecryptData (ed2, aes);
  524. #endif
  525. //foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
  526. Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedBody));
  527. Console.Error.WriteLine ("============= Decrypted Body End ===========");
  528. // FIXME: find out what first 16 bytes mean.
  529. for (int mmm = 0; mmm < 16; mmm++) decryptedBody [mmm] = 0x20;
  530. doc.LoadXml (Encoding.UTF8.GetString (decryptedBody));
  531. Assert.AreEqual ("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
  532. Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");
  533. return doc.DocumentElement;
  534. }
  535. Binding CreateIssuerBinding (RequestSender handler, bool tokenParams)
  536. {
  537. SymmetricSecurityBindingElement sbe =
  538. new SymmetricSecurityBindingElement ();
  539. if (tokenParams)
  540. sbe.ProtectionTokenParameters = new X509SecurityTokenParameters ();
  541. sbe.LocalServiceSettings.NegotiationTimeout = TimeSpan.FromSeconds (5);
  542. sbe.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
  543. //sbe.IncludeTimestamp = false;
  544. //sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
  545. // for ease of decryption, let's remove DerivedKeyToken.
  546. sbe.SetKeyDerivation (false);
  547. return new CustomBinding (
  548. // new DebugBindingElement (),
  549. sbe,
  550. new TextMessageEncodingBindingElement (),
  551. new HandlerTransportBindingElement (handler));
  552. }
  553. EndpointAddress GetSecureEndpointAddress (string uri)
  554. {
  555. return new EndpointAddress (new Uri (uri),
  556. new X509CertificateEndpointIdentity (
  557. new X509Certificate2 ("Test/Resources/test.pfx", "mono")));
  558. }
  559. IssuedSecurityTokenProvider SetupProvider (Binding binding)
  560. {
  561. IssuedSecurityTokenProvider p =
  562. new IssuedSecurityTokenProvider ();
  563. p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
  564. p.IssuerAddress = GetSecureEndpointAddress ("stream:dummy");
  565. p.IssuerBinding = binding;
  566. // wiithout it indigo causes NRE
  567. p.SecurityAlgorithmSuite = SecurityAlgorithmSuite.Default;
  568. p.TargetAddress = new EndpointAddress ("http://localhost:9090");
  569. return p;
  570. }
  571. }
  572. }