A
download UsernameToken.cs
Language: C#
Copyright: (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
LOC: 242
Project Info
mcs
Server: Mono
Type: svn
...soft.Web.Services.Security\
   AsymmetricDecryptionKey.cs
   AsymmetricEncryptionKey.cs
   AuthenticationKey.cs
   BinarySecurityToken.cs
   DecryptionKey.cs
   DecryptionKeyProvider.cs
   EncryptedData.cs
   EncryptedKey.cs
   EncryptionKey.cs
   IDecryptionKeyProvider.cs
   IMutableSecurityToken.cs
   IPasswordProvider.cs
   IReplayCache.cs
   ISecurityElement.cs
   KeyIdentifier.cs
   Nonce.cs
   OASIS.cs
   PasswordOption.cs
   Reference.cs
   ReferenceList.cs
   ReplayCacheManager.cs
   SaML.cs
   Security.cs
   SecurityCollection.cs
   ...ityElementCollection.cs
   SecurityFault.cs
   SecurityFormatException.cs
   SecurityInputFilter.cs
   SecurityOutputFilter.cs
   SecurityToken.cs
   SecurityTokenCache.cs
   SecurityTokenCollection.cs
   SecurityTokenReference.cs
   ...tyTokenReferenceType.cs
   Signature.cs
   SignatureKey.cs
   SignatureOptions.cs
   SignedInfo.cs
   SignedXml.cs
   SignedXmlSignature.cs
   SMSecurity.cs
   SMSecurityBase.cs
   SymmetricDecryptionKey.cs
   SymmetricEncryptionKey.cs
   ...edSecurityTokenCache.cs
   TransformChain.cs
   UsernameToken.cs
   WSEReplayCache.cs
   WSSecurity.cs
   X509SecurityToken.cs
   XmlDsigExcC14NTransform.cs
   ...ithCommentsTransform.cs
   XmlEncryption.cs
   XmlSignature.cs
   Xmltok.cs
   XrML.cs

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
//
// UsernameToken.cs: Handles WS-Security UsernameToken
//
// Author:
//	Sebastien Pouliot (spouliot@motus.com)
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
//

using Microsoft.Web.Services.Timestamp;

using System;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.Web.Services.Protocols;
using System.Xml;

#if WSE2
using System.Collections;
#endif

namespace Microsoft.Web.Services.Security {

	// References:
	// a.	Section 4.1
	//	http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnglobspec/html/ws-security.asp
	// b.	Web Services Security Addendum, Version 1.0, August 18, 2002
	//	http://msdn.microsoft.com/library/en-us/dnglobspec/html/ws-security-addendum.asp
	// c.	WS-Trust, Section 7
	//	http://www-106.ibm.com/developerworks/library/ws-trust/

#if WSE1
	public sealed class UsernameToken : SecurityToken {
#else
	public class UsernameToken : SecurityToken, IMutableSecurityToken {
#endif
		static private IPasswordProvider provider;

		private string username;
		private string password;
		private string digest;
		private PasswordOption option;
		private DateTime created;
		private Nonce nonce;

		static UsernameToken () 
		{
			provider = null;
		}

		public UsernameToken (XmlElement element) : base (element) 
		{
			// base will call the LoadXml (element)
		}

		public UsernameToken (string username, string password) 
			: this (username, password, PasswordOption.SendNone) {}

		public UsernameToken (string username, string password, PasswordOption passwordOption) 
		{
			if ((username == null) || (username == ""))
				throw new ArgumentNullException ("username");
			if ((password == null) || (password == ""))
				throw new ArgumentNullException ("password");

			this.username = username;
			this.password = password;
			option = passwordOption;
		}

		[MonoTODO ("where is the key derivation described ?")]
		public override AuthenticationKey AuthenticationKey {
			get { 
				if (nonce == null) {
					// LAMESPEC: undocumented exception
					throw new InvalidOperationException ("AuthenticationKey"); 
				}
				return null;
			}
		}

		public DateTime Created {
			get { return created; }
		}

		public override DecryptionKey DecryptionKey {
			get { throw new NotSupportedException ("DecryptionKey"); }
		}

		public override EncryptionKey EncryptionKey {
			get { throw new NotSupportedException ("EncryptionKey"); }
		}

		public byte[] Nonce {
			get { 
				if (nonce == null)
					return null;
				return nonce.GetValueBytes (); 
			}
		}

		public string Password {
			get { return password; }
		}

		public PasswordOption PasswordOption {
			get { 
				if (password == null)
					throw new ArgumentException ("no password");
				return option; 
			}
			set { 
				if (password == null)
					throw new ArgumentException ("no password");
				option = value; 
			}
		}

		[MonoTODO ("where is the key derivation described ?")]
		public override SignatureKey SignatureKey {
			get {
				if (password == null)
					throw new InvalidOperationException ("no password");
				// TODO: where is the key derivation described ?
				return null;
			}
		}

		public override bool SupportsDataEncryption {
			get { return false; }
		}

		public override bool SupportsDigitalSignature {
			get { return true; }
		}

		public string Username {
			get { return username; }
		}

		// Reference B, Section 6
		// Password_digest = SHA1 ( nonce + created + password )
		private string HashPassword (string password) 
		{
			byte[] n = nonce.GetValueBytes ();
			byte[] c = Encoding.UTF8.GetBytes (created.ToString (WSTimestamp.TimeFormat));
			byte[] p = Encoding.UTF8.GetBytes (password);
			byte[] toBeDigested = new byte [n.Length + c.Length + p.Length];
			Array.Copy (n, 0, toBeDigested, 0, n.Length);
			Array.Copy (c, 0, toBeDigested, n.Length, c.Length);
			Array.Copy (p, 0, toBeDigested, (n.Length + c.Length), p.Length);
			// protect password
			Array.Clear (p, 0, p.Length);
			SHA1 hash = SHA1.Create ();
			byte[] digest = hash.ComputeHash (toBeDigested);
			// protect password
			Array.Clear (toBeDigested, 0, toBeDigested.Length);
			return Convert.ToBase64String (digest);
		}

		public override XmlElement GetXml (XmlDocument document) 
		{
			if (document == null)
				throw new ArgumentNullException ("document");

			// much cleaner than using StringBuilder!
			XmlElement xel = document.CreateElement (WSSecurity.Prefix, WSSecurity.ElementNames.UsernameToken, WSSecurity.NamespaceURI);
			xel.SetAttribute ("xmlns:" + WSTimestamp.Prefix, WSTimestamp.NamespaceURI);
			xel.SetAttribute (WSTimestamp.AttributeNames.Id, WSTimestamp.NamespaceURI, Id);

			XmlElement xelUsername = document.CreateElement (WSSecurity.Prefix, WSSecurity.ElementNames.Username, WSSecurity.NamespaceURI);
			xelUsername.InnerText = username;
			xel.AppendChild (xelUsername);

			// Nonce and Created are required for hashing the password
			if (nonce == null)
				nonce = new Nonce ();
			// get creation time when serializing
			created = DateTime.UtcNow;

			if (option != PasswordOption.SendNone) {
				XmlElement xelPassword = document.CreateElement (WSSecurity.Prefix, WSSecurity.ElementNames.Password, WSSecurity.NamespaceURI);
				switch (option) {
					case PasswordOption.SendHashed:
						// no WSSecurity.NamespaceURI because it would add a "wsse" before "Type"
						xelPassword.SetAttribute (WSSecurity.AttributeNames.Type, WSSecurity.Prefix + ":PasswordDigest");
						xelPassword.InnerText = HashPassword (password);
						break;
					case PasswordOption.SendPlainText:
						// no WSSecurity.NamespaceURI because it would add a "wsse" before "Type"
						xelPassword.SetAttribute (WSSecurity.AttributeNames.Type, WSSecurity.Prefix + ":PasswordText");
						xelPassword.InnerText = password;
						break;
				}
				xel.AppendChild (xelPassword);
			}
			xel.AppendChild (nonce.GetXml (document));
			XmlElement xelCreated = document.CreateElement (WSTimestamp.Prefix, WSTimestamp.ElementNames.Created, WSTimestamp.NamespaceURI);
			xelCreated.InnerText = created.ToString (WSTimestamp.TimeFormat);
			xel.AppendChild (xelCreated);
			return xel;
		}

		public override void LoadXml (XmlElement element) 
		{
			if (element == null)
				throw new ArgumentNullException ("element");

			if ((element.LocalName != WSSecurity.ElementNames.UsernameToken) || (element.NamespaceURI != WSSecurity.NamespaceURI))
				throw new System.ArgumentException ("invalid LocalName or NamespaceURI");

			// retrieve Id
			XmlAttribute xaId = element.Attributes [WSTimestamp.AttributeNames.Id, WSTimestamp.NamespaceURI];
			if (xaId != null) {
				Id = xaId.InnerText;
			}
			// retreive Username
			XmlNodeList xnl = element.GetElementsByTagName (WSSecurity.ElementNames.Username, WSSecurity.NamespaceURI);
			if ((xnl != null) && (xnl.Count > 0)) {
				username = xnl [0].InnerText;
			}
			// retreive Password (if present), PasswordDigest (if present) or none and set PasswordOption
			xnl = element.GetElementsByTagName (WSSecurity.ElementNames.Password, WSSecurity.NamespaceURI);
			if ((xnl != null) && (xnl.Count > 0)) {
				XmlAttribute pwdType = xnl [0].Attributes [WSSecurity.AttributeNames.Type];
				if (pwdType != null) {
					string s = pwdType.InnerText;
					if (s.EndsWith (":PasswordDigest")) {
						option = PasswordOption.SendHashed;
						digest = xnl [0].InnerText;
					}
					else if (s.EndsWith (":PasswordText")) {
						option = PasswordOption.SendPlainText;
						password = xnl [0].InnerText;
					}
					else
						throw new Exception ("TODO");
				}
			}
			else
				option = PasswordOption.SendNone;
			// retreive Nonce
			xnl = element.GetElementsByTagName (WSSecurity.ElementNames.Nonce, WSSecurity.NamespaceURI);
			if ((xnl != null) && (xnl.Count > 0)) {
				XmlElement xel = (XmlElement) xnl [0];
				if (nonce == null)
					nonce = new Nonce (xel);
				else
					nonce.LoadXml (xel);
			}
			// retreive Created
			xnl = element.GetElementsByTagName (WSTimestamp.ElementNames.Created, WSTimestamp.NamespaceURI);
			if ((xnl != null) && (xnl.Count > 0)) {
				created = DateTime.ParseExact (xnl [0].InnerText, WSTimestamp.TimeFormat, null);
			}

			if (provider == null)
				throw new ConfigurationException (Locale.GetText ("No PasswordProvider configured"));

			string providerPassword = provider.GetPassword (this);
			switch (option) {
				case PasswordOption.SendNone:
					break;
				case PasswordOption.SendHashed:
					if (digest != HashPassword (providerPassword))
						throw new SecurityFault (Locale.GetText ("bad password"), null);
					break;
				case PasswordOption.SendPlainText:
					if (providerPassword != password)
						throw new SecurityFault (Locale.GetText ("bad password"), null);
					break;
			}
		}

#if WSE1
		public override void Verify () {}
#else
		public IList AnyElements {
			get { return null; }
		}

		public SecurityToken Clone ()
		{
			return new UsernameToken (username, password, option); 
		}

		[MonoTODO ("need to compare results with WSE2")]
		public override int GetHashCode () 
		{
			return username.GetHashCode ();
		}

		[MonoTODO ("need to compare results with WSE2")]
		public override bool Equals (SecurityToken token) 
		{
			if (token is UsernameToken) {
				UsernameToken t = token as UsernameToken;
				if ((t.Username == username) && (t.PasswordOption == option)) {
					// 1st case - we have a textual password (SendPlainText)
					if (password != null)
						return (t.Password == password);
					// we may not have the actual password if we're created
					// with the UsernameToken(XmlElement) constructor.
					// TODO: compare hashed password
					// however we can't compare two UsernameToken coming
					// both from UsernameToken(XmlElement) constructor
					return false;
				}
			}
			return false;
		}

		public override bool IsCurrent {
			get { return false; }
		}
#endif
	}
}

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us