File: IssuedSecurityTokenProviderTest.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (628 lines) | stat: -rw-r--r-- 23,147 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//
// IssuedSecurityTokenProviderTest.cs
//
// Author:
//	Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !MOBILE && !XAMMAC_4_5
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.IdentityModel.Tokens;
using System.Text;
using System.Xml;
using NUnit.Framework;

using MonoTests.System.ServiceModel.Channels;

using MonoTests.Helpers;

namespace MonoTests.System.ServiceModel.Security.Tokens
{
	[TestFixture]
	public class IssuedSecurityTokenProviderTest
	{
		[Test]
		public void DefaultValues ()
		{
			IssuedSecurityTokenProvider p =
				new IssuedSecurityTokenProvider ();
			Assert.AreEqual (true, p.CacheIssuedTokens, "#1");
			Assert.AreEqual (TimeSpan.FromMinutes (1), p.DefaultOpenTimeout, "#2");
			Assert.AreEqual (TimeSpan.FromMinutes (1), p.DefaultCloseTimeout, "#3");
			Assert.IsNotNull (p.IdentityVerifier, "#4");
			Assert.AreEqual (60, p.IssuedTokenRenewalThresholdPercentage, "#5");
			Assert.IsNull (p.IssuerAddress, "#6");
			Assert.AreEqual (0, p.IssuerChannelBehaviors.Count, "#7");
			Assert.AreEqual (SecurityKeyEntropyMode.CombinedEntropy, p.KeyEntropyMode, "#8");
			Assert.AreEqual (TimeSpan.MaxValue, p.MaxIssuedTokenCachingTime, "#9");
			Assert.AreEqual (MessageSecurityVersion.Default,
				p.MessageSecurityVersion, "#10");
			Assert.IsNull (p.SecurityAlgorithmSuite, "#11");
			Assert.IsNull (p.SecurityTokenSerializer, "#12");
			Assert.IsNull (p.TargetAddress, "#13");
			Assert.AreEqual (true, p.SupportsTokenCancellation, "#14");
			Assert.AreEqual (0, p.TokenRequestParameters.Count, "#15");
			Assert.IsNull (p.IssuerBinding, "#16");
		}

		[Test]
		[ExpectedException (typeof (InvalidOperationException))]
		public void OpenWithoutSerializer ()
		{
			IssuedSecurityTokenProvider p =
				new IssuedSecurityTokenProvider ();
			p.Open ();
		}

		[Test]
		[ExpectedException (typeof (InvalidOperationException))]
		public void OpenWithoutIssuerAddress ()
		{
			IssuedSecurityTokenProvider p =
				new IssuedSecurityTokenProvider ();
			p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
			p.Open ();
		}

		[Test]
		[ExpectedException (typeof (InvalidOperationException))]
		public void OpenWithoutBinding ()
		{
			IssuedSecurityTokenProvider p =
				new IssuedSecurityTokenProvider ();
			p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
			p.IssuerAddress = new EndpointAddress ("http://localhost:8080");
			p.Open ();
		}

		[Test]
		[ExpectedException (typeof (InvalidOperationException))]
		public void OpenWithoutTargetAddress ()
		{
			IssuedSecurityTokenProvider p =
				new IssuedSecurityTokenProvider ();
			p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
			p.IssuerAddress = new EndpointAddress ("http://localhost:8080");
			p.IssuerBinding = new BasicHttpBinding ();

			// wiithout it indigo causes NRE
			p.SecurityAlgorithmSuite = SecurityAlgorithmSuite.Default;
			p.Open ();
		}

		[Test]
		[Category ("NotWorking")]
		public void Open ()
		{
			IssuedSecurityTokenProvider p = SetupProvider (new BasicHttpBinding ());
			try {
				p.Open ();
			} finally {
				if (p.State == CommunicationState.Opened)
					p.Close ();
			}
		}

		[Test]
		[ExpectedException (typeof (InvalidOperationException))]
		public void GetTokenWithoutOpen ()
		{
			IssuedSecurityTokenProvider p =
				new IssuedSecurityTokenProvider ();
			p.GetToken (TimeSpan.FromSeconds (10));
		}

		// From WinFX beta2:
		// System.ServiceModel.Security.SecurityNegotiationException : 
		// SOAP security negotiation with 'stream:dummy' for target
		// 'stream:dummy' failed. See inner exception for more details.
		// ----> System.InvalidOperationException : The request
		// message must be protected. This is required by an operation
		// of the contract ('IWsTrustFeb2005SecurityTokenService',
		// 'http://tempuri.org/'). The protection must be provided by
		// the binding ('BasicHttpBinding','http://tempuri.org/').
		[Test]
		[ExpectedException (typeof (SecurityNegotiationException))]
		[Category ("NotWorking")]
		public void GetTokenNoSecureBinding ()
		{
			IssuedSecurityTokenProvider p = SetupProvider (new BasicHttpBinding ());
			try {
				p.Open ();
				p.GetToken (TimeSpan.FromSeconds (10));
			} finally {
				if (p.State == CommunicationState.Opened)
					p.Close ();
			}
		}

		[Test]
		// SymmetricSecurityBindingElement requires protection
		// token parameters to build a channel or listener factory.
		[ExpectedException (typeof (SecurityNegotiationException))]
		[Category ("NotWorking")]
		public void GetTokenWithoutProtectionTokenParameters ()
		{
			IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (null, false));
			try {
				p.Open ();
				p.GetToken (TimeSpan.FromSeconds (10));
			} finally {
				if (p.State == CommunicationState.Opened)
					p.Close ();
			}
		}

		// SecurityNegotiationException (InvalidOperationException (
		//   "The service certificate is not provided for target
		//   'stream:dummy'. Specify a service certificate in 
		//   ClientCredentials."))
		[Test]
		[ExpectedException (typeof (SecurityNegotiationException))]
		[Category ("NotWorking")]
		public void GetTokenWithoutServiceCertificate ()
		{
			IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (null, true));
			p.IssuerAddress = new EndpointAddress ("stream:dummy");
			try {
				p.Open (TimeSpan.FromSeconds (5));
				p.GetToken (TimeSpan.FromSeconds (10));
			} finally {
				if (p.State == CommunicationState.Opened)
					p.Close ();
			}
		}

		[Test]
		[Category ("NotWorking")]
		[ExpectedException (typeof (MyException))]
		public void GetTokenWrongResponse ()
		{
			IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetTokenWrongResponse), true));
			try {
				p.Open (TimeSpan.FromSeconds (5));
				p.GetToken (TimeSpan.FromSeconds (10));
			} finally {
				if (p.State == CommunicationState.Opened)
					p.Close ();
			}
		}

		[Test]
		[Category ("NotWorking")]
		[ExpectedException (typeof (MessageSecurityException))]
		public void GetTokenUnsignedReply ()
		{
			IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetTokenUnsignedReply), true));
			try {
				p.Open (TimeSpan.FromSeconds (5));
				p.GetToken (TimeSpan.FromSeconds (10));
			} finally {
				if (p.State == CommunicationState.Opened)
					p.Close ();
			}
		}

		// InnerException: System.InvalidOperationException:
		// The issuer must provide a computed key in key entropy mode
		// 'CombinedEntropy'.
		[Test]
		[Ignore ("todo")]
		[ExpectedException (typeof (SecurityNegotiationException))]
		public void GetTokenNoEntropyInResponseInCombinedMode ()
		{
			// FIXME: implement it after we get working token issuer.
			// In the reply, do not include Nonce
		}

		// on the other hand, in Client entropy mode it must not
		// provide entropy.
		[Test]
		[Ignore ("todo")]
		[ExpectedException (typeof (SecurityNegotiationException))]
		public void GetTokenIncludesEntropyInResponseInClientMode ()
		{
			// FIXME: implement it after we get working token issuer.
			// specify SecurityKeyEntropyMode.ClientEntropy on 
			// client side. And in the reply, include Nonce.
		}

		[Test]
		[Ignore ("need to implement response")]
		[Category ("NotWorking")]
		public void GetToken ()
		{
			IssuedSecurityTokenProvider p = SetupProvider (CreateIssuerBinding (new RequestSender (OnGetToken), true));
			try {
				p.Open (TimeSpan.FromSeconds (5));
				p.GetToken (TimeSpan.FromSeconds (10));
			} finally {
				if (p.State == CommunicationState.Opened)
					p.Close ();
			}
		}

		class MyException : Exception
		{
		}

		Message OnGetTokenWrongResponse (Message input)
		{
			VerifyInput (input.CreateBufferedCopy (10000));

			throw new MyException ();
		}

		Message OnGetTokenUnsignedReply (Message input)
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<Response>RESPONSE</Response>");

			Message msg = Message.CreateMessage (input.Version, "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/IssueResponse", doc.DocumentElement);
			msg.Headers.Add (MessageHeader.CreateHeader (
				"Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", null, true));

			return msg;
		}

		Message OnGetToken (Message input)
		{
			MessageBuffer buf = input.CreateBufferedCopy (10000);
			VerifyInput2 (buf);

			// FIXME: create response message (when I understand what I should return.)
//			throw new MyException ();
//*
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<Response>RESPONSE</Response>");
			X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono");
			SignedXml sxml = new SignedXml (doc);
			MemoryStream ms = new MemoryStream (new byte [] {1, 2, 3});
			sxml.AddReference (new Reference (ms));
			sxml.SigningKey = cert.PrivateKey;
			sxml.ComputeSignature ();

			Message msg = Message.CreateMessage (input.Version, "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue", sxml.GetXml ());
			msg.Headers.Add (MessageHeader.CreateHeader (
				"Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", null, true));

			return msg;
//*/
		}

		void VerifyInput (MessageBuffer buf)
		{
			Message input = buf.CreateMessage ();
/*
XmlWriterSettings settings = new XmlWriterSettings ();
settings.Indent = true;
using (XmlWriter w = XmlWriter.Create (Console.Error, settings)) {
buf.CreateMessage ().WriteMessage (w);
}
Console.Error.WriteLine ("******************** DONE ********************");
Console.Error.Flush ();
*/

			Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", input.Headers.Action, "GetToken.Request.Action");
			Assert.IsNotNull (input.Headers.MessageId, "GetToken.Request.MessageID");
			// in the raw Message it is "http://www.w3.org/2005/08/addressing/anonymous", but it is replaced by MessageHeaders implementation.
			Assert.AreEqual (new EndpointAddress ("http://schemas.microsoft.com/2005/12/ServiceModel/Addressing/Anonymous"), input.Headers.ReplyTo, "GetToken.Request.ReplyTo");

			// o:Security
			// FIXME: test WSSecurity more
			// <o:Security>
			//  <u:Timestamp>
			//   <u:Created>...</u:Created>
			//   <u:Expires>...</u:Expires>
			//  </u:Timestamp>
			//  <o:BinarySecurityToken>...</o:BinarySecurityToken>
			//  <e:EncryptedKey>
			//   <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
			//   <KeyInfo>
			//    <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   </KeyInfo>
			//   <e:CipherData>
			//    <e:CipherValue>...</e:CipherValue>
			//   </e:CipherData>
			//  </e:EncryptedKey>
			//  [
			//  <c:DerivedKeyToken>
			//   <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   <c:Offset>...</c:Offset>
			//   <c:Length>...</c:Length>
			//   <c:Nonce>...</c:Nonce>
			//  </c:DerivedKeyToken>
			//  ]
			//  <e:ReferenceList>
			//   [
			//   <e:DataReference>
			//   ]
			//  </e:ReferenceList>
			//  <e:EncryptedData>
			//   <e:EncryptionMethod/>
			//   <KeyInfo> {{....}} </KeyInfo>
			//   <e:CipherData> {{....}} </e:CipherData>
			//  </e:EncryptedData>
			// </o:Security>
			int i = input.Headers.FindHeader ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			Assert.IsTrue (i >= 0, "Security header existence");
			MessageHeaderInfo info = input.Headers [i];
			Assert.IsNotNull (info, "Security header item");
			XmlReader r = input.Headers.GetReaderAtHeader (i);

			// FIXME: test WSSecurity more
			// <o:Security>
			r.MoveToContent ();
			r.ReadStartElement ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			//  <u:Timestamp>
			r.MoveToContent ();
			r.ReadStartElement ("Timestamp", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
			//   <u:Created>...</u:Created>
			r.MoveToContent ();
			r.ReadStartElement ("Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
			r.ReadString ();
			r.MoveToContent ();
			r.ReadEndElement ();
			//   <u:Expires>...</u:Expires>
			r.MoveToContent ();
			r.ReadStartElement ("Expires", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
			r.ReadString ();
			r.MoveToContent ();
			r.ReadEndElement ();
			//  </u:Timestamp>
			r.MoveToContent ();
			r.ReadEndElement ();
			//  <o:BinarySecurityToken>...</o:BinarySecurityToken>
			r.MoveToContent ();
			r.ReadStartElement ("BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			byte [] rawcert = Convert.FromBase64String (r.ReadString ());
			r.ReadEndElement ();
			X509Certificate2 cert = new X509Certificate2 (rawcert);

			// FIXME: test EncryptedKey
			r.MoveToContent ();
			r.Skip ();
			//  <e:EncryptedKey>
			//   <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
			//   <KeyInfo>
			//    <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   </KeyInfo>
			//   <e:CipherData>
			//    <e:CipherValue>...</e:CipherValue>
			//   </e:CipherData>
			//  </e:EncryptedKey>

			// FIXME: test DerivedKeyTokens
			r.MoveToContent ();
			while (r.LocalName == "DerivedKeyToken") {
				r.Skip ();
				r.MoveToContent ();
			}
			//  [
			//  <c:DerivedKeyToken>
			//   <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   <c:Offset>...</c:Offset>
			//   <c:Length>...</c:Length>
			//   <c:Nonce>...</c:Nonce>
			//  </c:DerivedKeyToken>
			//  ]
			
			//  <e:ReferenceList>
			//   [
			//   <e:DataReference>
			//   ]
			//  </e:ReferenceList>
			//  <e:EncryptedData>
			//   <e:EncryptionMethod/>
			//   <KeyInfo> {{....}} </KeyInfo>
			//   <e:CipherData> {{....}} </e:CipherData>
			//  </e:EncryptedData>
			// </o:Security>

			// SOAP Body
			r = input.GetReaderAtBodyContents (); // just verifying itself ;)
		}

		XmlElement VerifyInput2 (MessageBuffer buf)
		{
			Message msg2 = buf.CreateMessage ();
			StringWriter sw = new StringWriter ();
			using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw))) {
				msg2.WriteMessage (w);
			}
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			doc.LoadXml (sw.ToString ());

			// decrypt the key with service certificate privkey
			PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
			EncryptedXml encXml = new EncryptedXml (doc);
			encXml.Padding = mode;
			X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono");
			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
			nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
			nsmgr.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			nsmgr.AddNamespace ("e", "http://www.w3.org/2001/04/xmlenc#");
			nsmgr.AddNamespace ("dsig", "http://www.w3.org/2000/09/xmldsig#");
			XmlNode n = doc.SelectSingleNode ("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: enckey does not exist");
			string raw = n.InnerText;
			byte [] rawbytes = Convert.FromBase64String (raw);
			RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert2.PrivateKey;
			byte [] decryptedKey = EncryptedXml.DecryptKey (rawbytes, rsa, true);//rsa.Decrypt (rawbytes, true);

#if false
			// create derived keys
			Dictionary<string,byte[]> keys = new Dictionary<string,byte[]> ();
			InMemorySymmetricSecurityKey skey =
				new InMemorySymmetricSecurityKey (decryptedKey);
			foreach (XmlElement el in doc.SelectNodes ("//o:Security/c:DerivedKeyToken", nsmgr)) {
				n = el.SelectSingleNode ("c:Offset", nsmgr);
				int offset = (n == null) ? 0 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Length", nsmgr);
				int length = (n == null) ? 32 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Label", nsmgr);
				byte [] label = (n == null) ? decryptedKey :
					Convert.FromBase64String (n.InnerText);
				n = el.SelectSingleNode ("c:Nonce", nsmgr);
				byte [] nonce = (n == null) ? new byte [0] :
					Convert.FromBase64String (n.InnerText);
				byte [] derkey = skey.GenerateDerivedKey (
					//SecurityAlgorithms.Psha1KeyDerivation,
					"http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
					label,
					nonce,
					length * 8,
					offset);

				keys [el.GetAttribute ("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
			}
#endif

			// decrypt the signature with the decrypted key
#if true
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;
			MemoryStream ms = new MemoryStream ();
			CryptoStream cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedSignature = ms.ToArray ();
#else
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;

			EncryptedData ed = new EncryptedData ();
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			ed.LoadXml (n as XmlElement);
			byte [] decryptedSignature = encXml.DecryptData (ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

			// decrypt the body with the decrypted key
#if true
			n = doc.SelectSingleNode ("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			ms = new MemoryStream ();
			cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedBody = ms.ToArray ();
#else
			// decrypt the body with the decrypted key
			EncryptedData ed2 = new EncryptedData ();
			XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
			ed2.LoadXml (el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			byte [] decryptedBody = encXml.DecryptData (ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedBody));
Console.Error.WriteLine ("============= Decrypted Body End ===========");

			// FIXME: find out what first 16 bytes mean.
			for (int mmm = 0; mmm < 16; mmm++) decryptedBody [mmm] = 0x20;
			doc.LoadXml (Encoding.UTF8.GetString (decryptedBody));
			Assert.AreEqual ("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
			Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

			return doc.DocumentElement;
		}

		Binding CreateIssuerBinding (RequestSender handler, bool tokenParams)
		{
			SymmetricSecurityBindingElement sbe =
				new SymmetricSecurityBindingElement ();
			if (tokenParams)
				sbe.ProtectionTokenParameters = new X509SecurityTokenParameters ();
			sbe.LocalServiceSettings.NegotiationTimeout = TimeSpan.FromSeconds (5);
			sbe.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
			//sbe.IncludeTimestamp = false;
			//sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;

			// for ease of decryption, let's remove DerivedKeyToken.
			sbe.SetKeyDerivation (false);

			return new CustomBinding (
//				new DebugBindingElement (),
				sbe,
				new TextMessageEncodingBindingElement (),
				new HandlerTransportBindingElement (handler));
		}

		EndpointAddress GetSecureEndpointAddress (string uri)
		{
			return new EndpointAddress (new Uri (uri),
				new X509CertificateEndpointIdentity (
					new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono")));
		}

		IssuedSecurityTokenProvider SetupProvider (Binding binding)
		{
			IssuedSecurityTokenProvider p =
				new IssuedSecurityTokenProvider ();
			p.SecurityTokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
			p.IssuerAddress = GetSecureEndpointAddress ("stream:dummy");
			p.IssuerBinding = binding;

			// wiithout it indigo causes NRE
			p.SecurityAlgorithmSuite = SecurityAlgorithmSuite.Default;

			p.TargetAddress = new EndpointAddress ("http://localhost:9090");
			return p;
		}
	}
}
#endif