IssuedSecurityTokenProviderTest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. public void Open ()
  114. {
  115. IssuedSecurityTokenProvider p = SetupProvider (new BasicHttpBinding ());
  116. try {
  117. p.Open ();
  118. } finally {
  119. if (p.State == CommunicationState.Opened)
  120. p.Close ();
  121. }
  122. }
  123. [Test]
  124. [ExpectedException (typeof (InvalidOperationException))]
  125. public void GetTokenWithoutOpen ()
  126. {
  127. IssuedSecurityTokenProvider p =
  128. new IssuedSecurityTokenProvider ();
  129. p.GetToken (TimeSpan.FromSeconds (10));
  130. }
  131. // From WinFX beta2:
  132. // System.ServiceModel.Security.SecurityNegotiationException :
  133. // SOAP security negotiation with 'stream:dummy' for target
  134. // 'stream:dummy' failed. See inner exception for more details.
  135. // ----> System.InvalidOperationException : The request
  136. // message must be protected. This is required by an operation
  137. // of the contract ('IWsTrustFeb2005SecurityTokenService',
  138. // 'http://tempuri.org/'). The protection must be provided by
  139. // the binding ('BasicHttpBinding','http://tempuri.org/').
  140. [Test]
  141. [ExpectedException (typeof (SecurityNegotiationException))]
  142. [Category ("NotWorking")]
  143. public void GetTokenNoSecureBinding ()
  144. {
  145. IssuedSecurityTokenProvider p = SetupProvider (new BasicHttpBinding ());
  146. try {
  147. p.Open ();
  148. p.GetToken (TimeSpan.FromSeconds (10));
  149. } finally {
  150. if (p.State == CommunicationState.Opened)
  151. p.Close ();
  152. }
  153. }
  154. [Test]
  155. // SymmetricSecurityBindingElement requires protection
  156. // token parameters to build a channel or listener factory.
  157. [ExpectedException (typeof (SecurityNegotiationException))]
  158. [Category ("NotWorking")]
  159. public void GetTokenWithoutProtectionTokenParameters ()
  160. {
  161. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (null, false));
  162. try {
  163. p.Open ();
  164. p.GetToken (TimeSpan.FromSeconds (10));
  165. } finally {
  166. if (p.State == CommunicationState.Opened)
  167. p.Close ();
  168. }
  169. }
  170. // SecurityNegotiationException (InvalidOperationException (
  171. // "The service certificate is not provided for target
  172. // 'stream:dummy'. Specify a service certificate in
  173. // ClientCredentials."))
  174. [Test]
  175. [ExpectedException (typeof (SecurityNegotiationException))]
  176. [Category ("NotWorking")]
  177. public void GetTokenWithoutServiceCertificate ()
  178. {
  179. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (null, true));
  180. p.IssuerAddress = new EndpointAddress ("stream:dummy");
  181. try {
  182. p.Open (TimeSpan.FromSeconds (5));
  183. p.GetToken (TimeSpan.FromSeconds (10));
  184. } finally {
  185. if (p.State == CommunicationState.Opened)
  186. p.Close ();
  187. }
  188. }
  189. [Test]
  190. [Category ("NotWorking")]
  191. [ExpectedException (typeof (MyException))]
  192. public void GetTokenWrongResponse ()
  193. {
  194. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetTokenWrongResponse), true));
  195. try {
  196. p.Open (TimeSpan.FromSeconds (5));
  197. p.GetToken (TimeSpan.FromSeconds (10));
  198. } finally {
  199. if (p.State == CommunicationState.Opened)
  200. p.Close ();
  201. }
  202. }
  203. [Test]
  204. [Category ("NotWorking")]
  205. [ExpectedException (typeof (MessageSecurityException))]
  206. public void GetTokenUnsignedReply ()
  207. {
  208. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetTokenUnsignedReply), true));
  209. try {
  210. p.Open (TimeSpan.FromSeconds (5));
  211. p.GetToken (TimeSpan.FromSeconds (10));
  212. } finally {
  213. if (p.State == CommunicationState.Opened)
  214. p.Close ();
  215. }
  216. }
  217. // InnerException: System.InvalidOperationException:
  218. // The issuer must provide a computed key in key entropy mode
  219. // 'CombinedEntropy'.
  220. [Test]
  221. [Ignore ("todo")]
  222. [ExpectedException (typeof (SecurityNegotiationException))]
  223. public void GetTokenNoEntropyInResponseInCombinedMode ()
  224. {
  225. // FIXME: implement it after we get working token issuer.
  226. // In the reply, do not include Nonce
  227. }
  228. // on the other hand, in Client entropy mode it must not
  229. // provide entropy.
  230. [Test]
  231. [Ignore ("todo")]
  232. [ExpectedException (typeof (SecurityNegotiationException))]
  233. public void GetTokenIncludesEntropyInResponseInClientMode ()
  234. {
  235. // FIXME: implement it after we get working token issuer.
  236. // specify SecurityKeyEntropyMode.ClientEntropy on
  237. // client side. And in the reply, include Nonce.
  238. }
  239. [Test]
  240. [Ignore ("need to implement response")]
  241. [Category ("NotWorking")]
  242. public void GetToken ()
  243. {
  244. IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetToken), true));
  245. try {
  246. p.Open (TimeSpan.FromSeconds (5));
  247. p.GetToken (TimeSpan.FromSeconds (10));
  248. } finally {
  249. if (p.State == CommunicationState.Opened)
  250. p.Close ();
  251. }
  252. }
  253. class MyException : Exception
  254. {
  255. }
  256. Message OnGetTokenWrongResponse (Message input)
  257. {
  258. VerifyInput (input.CreateBufferedCopy (10000));
  259. throw new MyException ();
  260. }
  261. Message OnGetTokenUnsignedReply (Message input)
  262. {
  263. XmlDocument doc = new XmlDocument ();
  264. doc.LoadXml ("<Response>RESPONSE</Response>");
  265. Message msg = Message.CreateMessage (input.Version, "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/IssueResponse", doc.DocumentElement);
  266. msg.Headers.Add (MessageHeader.CreateHeader (
  267. "Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", null, true));
  268. return msg;
  269. }
  270. Message OnGetToken (Message input)
  271. {
  272. MessageBuffer buf = input.CreateBufferedCopy (10000);
  273. VerifyInput2 (buf);
  274. // FIXME: create response message (when I understand what I should return.)
  275. // throw new MyException ();
  276. //*
  277. XmlDocument doc = new XmlDocument ();
  278. doc.LoadXml ("<Response>RESPONSE</Response>");
  279. X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
  280. SignedXml sxml = new SignedXml (doc);
  281. MemoryStream ms = new MemoryStream (new byte [] {1, 2, 3});
  282. sxml.AddReference (new Reference (ms));
  283. sxml.SigningKey = cert.PrivateKey;
  284. sxml.ComputeSignature ();
  285. Message msg = Message.CreateMessage (input.Version, "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue", sxml.GetXml ());
  286. msg.Headers.Add (MessageHeader.CreateHeader (
  287. "Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", null, true));
  288. return msg;
  289. //*/
  290. }
  291. void VerifyInput (MessageBuffer buf)
  292. {
  293. Message input = buf.CreateMessage ();
  294. /*
  295. XmlWriterSettings settings = new XmlWriterSettings ();
  296. settings.Indent = true;
  297. using (XmlWriter w = XmlWriter.Create (Console.Error, settings)) {
  298. buf.CreateMessage ().WriteMessage (w);
  299. }
  300. Console.Error.WriteLine ("******************** DONE ********************");
  301. Console.Error.Flush ();
  302. */
  303. Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", input.Headers.Action, "GetToken.Request.Action");
  304. Assert.IsNotNull (input.Headers.MessageId, "GetToken.Request.MessageID");
  305. // in the raw Message it is "http://www.w3.org/2005/08/addressing/anonymous", but it is replaced by MessageHeaders implementation.
  306. Assert.AreEqual (new EndpointAddress ("http://schemas.microsoft.com/2005/12/ServiceModel/Addressing/Anonymous"), input.Headers.ReplyTo, "GetToken.Request.ReplyTo");
  307. // o:Security
  308. // FIXME: test WSSecurity more
  309. // <o:Security>
  310. // <u:Timestamp>
  311. // <u:Created>...</u:Created>
  312. // <u:Expires>...</u:Expires>
  313. // </u:Timestamp>
  314. // <o:BinarySecurityToken>...</o:BinarySecurityToken>
  315. // <e:EncryptedKey>
  316. // <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
  317. // <KeyInfo>
  318. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  319. // </KeyInfo>
  320. // <e:CipherData>
  321. // <e:CipherValue>...</e:CipherValue>
  322. // </e:CipherData>
  323. // </e:EncryptedKey>
  324. // [
  325. // <c:DerivedKeyToken>
  326. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  327. // <c:Offset>...</c:Offset>
  328. // <c:Length>...</c:Length>
  329. // <c:Nonce>...</c:Nonce>
  330. // </c:DerivedKeyToken>
  331. // ]
  332. // <e:ReferenceList>
  333. // [
  334. // <e:DataReference>
  335. // ]
  336. // </e:ReferenceList>
  337. // <e:EncryptedData>
  338. // <e:EncryptionMethod/>
  339. // <KeyInfo> {{....}} </KeyInfo>
  340. // <e:CipherData> {{....}} </e:CipherData>
  341. // </e:EncryptedData>
  342. // </o:Security>
  343. int i = input.Headers.FindHeader ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  344. Assert.IsTrue (i >= 0, "Security header existence");
  345. MessageHeaderInfo info = input.Headers [i];
  346. Assert.IsNotNull (info, "Security header item");
  347. XmlReader r = input.Headers.GetReaderAtHeader (i);
  348. // FIXME: test WSSecurity more
  349. // <o:Security>
  350. r.MoveToContent ();
  351. r.ReadStartElement ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  352. // <u:Timestamp>
  353. r.MoveToContent ();
  354. r.ReadStartElement ("Timestamp", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  355. // <u:Created>...</u:Created>
  356. r.MoveToContent ();
  357. r.ReadStartElement ("Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  358. r.ReadString ();
  359. r.MoveToContent ();
  360. r.ReadEndElement ();
  361. // <u:Expires>...</u:Expires>
  362. r.MoveToContent ();
  363. r.ReadStartElement ("Expires", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  364. r.ReadString ();
  365. r.MoveToContent ();
  366. r.ReadEndElement ();
  367. // </u:Timestamp>
  368. r.MoveToContent ();
  369. r.ReadEndElement ();
  370. // <o:BinarySecurityToken>...</o:BinarySecurityToken>
  371. r.MoveToContent ();
  372. r.ReadStartElement ("BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  373. byte [] rawcert = Convert.FromBase64String (r.ReadString ());
  374. r.ReadEndElement ();
  375. X509Certificate2 cert = new X509Certificate2 (rawcert);
  376. // FIXME: test EncryptedKey
  377. r.MoveToContent ();
  378. r.Skip ();
  379. // <e:EncryptedKey>
  380. // <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
  381. // <KeyInfo>
  382. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  383. // </KeyInfo>
  384. // <e:CipherData>
  385. // <e:CipherValue>...</e:CipherValue>
  386. // </e:CipherData>
  387. // </e:EncryptedKey>
  388. // FIXME: test DerivedKeyTokens
  389. r.MoveToContent ();
  390. while (r.LocalName == "DerivedKeyToken") {
  391. r.Skip ();
  392. r.MoveToContent ();
  393. }
  394. // [
  395. // <c:DerivedKeyToken>
  396. // <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
  397. // <c:Offset>...</c:Offset>
  398. // <c:Length>...</c:Length>
  399. // <c:Nonce>...</c:Nonce>
  400. // </c:DerivedKeyToken>
  401. // ]
  402. // <e:ReferenceList>
  403. // [
  404. // <e:DataReference>
  405. // ]
  406. // </e:ReferenceList>
  407. // <e:EncryptedData>
  408. // <e:EncryptionMethod/>
  409. // <KeyInfo> {{....}} </KeyInfo>
  410. // <e:CipherData> {{....}} </e:CipherData>
  411. // </e:EncryptedData>
  412. // </o:Security>
  413. // SOAP Body
  414. r = input.GetReaderAtBodyContents (); // just verifying itself ;)
  415. }
  416. XmlElement VerifyInput2 (MessageBuffer buf)
  417. {
  418. Message msg2 = buf.CreateMessage ();
  419. StringWriter sw = new StringWriter ();
  420. using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw))) {
  421. msg2.WriteMessage (w);
  422. }
  423. XmlDocument doc = new XmlDocument ();
  424. doc.PreserveWhitespace = true;
  425. doc.LoadXml (sw.ToString ());
  426. // decrypt the key with service certificate privkey
  427. PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
  428. EncryptedXml encXml = new EncryptedXml (doc);
  429. encXml.Padding = mode;
  430. X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
  431. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  432. nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
  433. nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
  434. nsmgr.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  435. nsmgr.AddNamespace ("e", "http://www.w3.org/2001/04/xmlenc#");
  436. nsmgr.AddNamespace ("dsig", "http://www.w3.org/2000/09/xmldsig#");
  437. XmlNode n = doc.SelectSingleNode ("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);
  438. Assert.IsNotNull (n, "premise: enckey does not exist");
  439. string raw = n.InnerText;
  440. byte [] rawbytes = Convert.FromBase64String (raw);
  441. RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert2.PrivateKey;
  442. byte [] decryptedKey = EncryptedXml.DecryptKey (rawbytes, rsa, true);//rsa.Decrypt (rawbytes, true);
  443. #if false
  444. // create derived keys
  445. Dictionary<string,byte[]> keys = new Dictionary<string,byte[]> ();
  446. InMemorySymmetricSecurityKey skey =
  447. new InMemorySymmetricSecurityKey (decryptedKey);
  448. foreach (XmlElement el in doc.SelectNodes ("//o:Security/c:DerivedKeyToken", nsmgr)) {
  449. n = el.SelectSingleNode ("c:Offset", nsmgr);
  450. int offset = (n == null) ? 0 :
  451. int.Parse (n.InnerText, CultureInfo.InvariantCulture);
  452. n = el.SelectSingleNode ("c:Length", nsmgr);
  453. int length = (n == null) ? 32 :
  454. int.Parse (n.InnerText, CultureInfo.InvariantCulture);
  455. n = el.SelectSingleNode ("c:Label", nsmgr);
  456. byte [] label = (n == null) ? decryptedKey :
  457. Convert.FromBase64String (n.InnerText);
  458. n = el.SelectSingleNode ("c:Nonce", nsmgr);
  459. byte [] nonce = (n == null) ? new byte [0] :
  460. Convert.FromBase64String (n.InnerText);
  461. byte [] derkey = skey.GenerateDerivedKey (
  462. //SecurityAlgorithms.Psha1KeyDerivation,
  463. "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
  464. // FIXME: maybe due to the label, this key resolution somehow does not seem to work.
  465. label,
  466. nonce,
  467. length * 8,
  468. offset);
  469. keys [el.GetAttribute ("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
  470. }
  471. #endif
  472. // decrypt the signature with the decrypted key
  473. #if true
  474. n = doc.SelectSingleNode ("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
  475. Assert.IsNotNull (n, "premise: encdata does not exist");
  476. raw = n.InnerText;
  477. rawbytes = Convert.FromBase64String (raw);
  478. Rijndael aes = RijndaelManaged.Create ();
  479. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  480. aes.Key = decryptedKey;
  481. aes.Mode = CipherMode.CBC;
  482. aes.Padding = mode;
  483. MemoryStream ms = new MemoryStream ();
  484. CryptoStream cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
  485. cs.Write (rawbytes, 0, rawbytes.Length);
  486. cs.Close ();
  487. byte [] decryptedSignature = ms.ToArray ();
  488. #else
  489. Rijndael aes = RijndaelManaged.Create ();
  490. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  491. aes.Key = decryptedKey;
  492. aes.Mode = CipherMode.CBC;
  493. aes.Padding = mode;
  494. EncryptedData ed = new EncryptedData ();
  495. n = doc.SelectSingleNode ("//o:Security/e:EncryptedData", nsmgr);
  496. Assert.IsNotNull (n, "premise: encdata does not exist");
  497. ed.LoadXml (n as XmlElement);
  498. byte [] decryptedSignature = encXml.DecryptData (ed, aes);
  499. #endif
  500. //Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
  501. //Console.Error.WriteLine ("============= Decrypted Signature End ===========");
  502. // decrypt the body with the decrypted key
  503. #if true
  504. n = doc.SelectSingleNode ("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
  505. Assert.IsNotNull (n, "premise: encdata does not exist");
  506. raw = n.InnerText;
  507. rawbytes = Convert.FromBase64String (raw);
  508. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  509. aes.Key = decryptedKey;
  510. ms = new MemoryStream ();
  511. cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
  512. cs.Write (rawbytes, 0, rawbytes.Length);
  513. cs.Close ();
  514. byte [] decryptedBody = ms.ToArray ();
  515. #else
  516. // decrypt the body with the decrypted key
  517. EncryptedData ed2 = new EncryptedData ();
  518. XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
  519. ed2.LoadXml (el);
  520. // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
  521. aes.Key = decryptedKey;
  522. byte [] decryptedBody = encXml.DecryptData (ed2, aes);
  523. #endif
  524. //foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
  525. Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedBody));
  526. Console.Error.WriteLine ("============= Decrypted Body End ===========");
  527. // FIXME: find out what first 16 bytes mean.
  528. for (int mmm = 0; mmm < 16; mmm++) decryptedBody [mmm] = 0x20;
  529. doc.LoadXml (Encoding.UTF8.GetString (decryptedBody));
  530. Assert.AreEqual ("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
  531. Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");
  532. return doc.DocumentElement;
  533. }
  534. Binding CreateIssuerBinding (RequestSender handler, bool tokenParams)
  535. {
  536. SymmetricSecurityBindingElement sbe =
  537. new SymmetricSecurityBindingElement ();
  538. if (tokenParams)
  539. sbe.ProtectionTokenParameters = new X509SecurityTokenParameters ();
  540. sbe.LocalServiceSettings.NegotiationTimeout = TimeSpan.FromSeconds (5);
  541. sbe.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
  542. //sbe.IncludeTimestamp = false;
  543. //sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
  544. // for ease of decryption, let's remove DerivedKeyToken.
  545. sbe.SetKeyDerivation (false);
  546. return new CustomBinding (
  547. // new DebugBindingElement (),
  548. sbe,
  549. new TextMessageEncodingBindingElement (),
  550. new HandlerTransportBindingElement (handler));
  551. }
  552. EndpointAddress GetSecureEndpointAddress (string uri)
  553. {
  554. return new EndpointAddress (new Uri (uri),
  555. new X509CertificateEndpointIdentity (
  556. new X509Certificate2 ("Test/Resources/test.pfx", "mono")));
  557. }
  558. IssuedSecurityTokenProvider SetupProvider (Binding binding)
  559. {
  560. IssuedSecurityTokenProvider p =
  561. new IssuedSecurityTokenProvider ();
  562. p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
  563. p.IssuerAddress = GetSecureEndpointAddress ("stream:dummy");
  564. p.IssuerBinding = binding;
  565. // wiithout it indigo causes NRE
  566. p.SecurityAlgorithmSuite = SecurityAlgorithmSuite.Default;
  567. p.TargetAddress = new EndpointAddress ("http://localhost:9090");
  568. return p;
  569. }
  570. }
  571. }