2 // System.Net.DigestClient.cs
5 // Greg Reinacker (gregr@rassoc.com)
6 // Sebastien Pouliot (spouliot@motus.com)
7 // Gonzalo Paniagua Javier (gonzalo@ximian.com
9 // Copyright 2002-2003 Greg Reinacker, Reinacker & Associates, Inc. All rights reserved.
10 // Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com)
11 // (c) 2003 Novell, Inc. (http://www.novell.com)
13 // Original (server-side) source code available at
14 // http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html
18 // Permission is hereby granted, free of charge, to any person obtaining
19 // a copy of this software and associated documentation files (the
20 // "Software"), to deal in the Software without restriction, including
21 // without limitation the rights to use, copy, modify, merge, publish,
22 // distribute, sublicense, and/or sell copies of the Software, and to
23 // permit persons to whom the Software is furnished to do so, subject to
24 // the following conditions:
26 // The above copyright notice and this permission notice shall be
27 // included in all copies or substantial portions of the Software.
29 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
33 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
34 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
39 using System.Collections;
40 using System.Collections.Specialized;
43 using System.Security.Cryptography;
49 // This works with apache mod_digest
54 // See RFC 2617 for details.
58 class DigestHeaderParser
63 static string [] keywords = { "realm", "opaque", "nonce", "algorithm", "qop" };
64 static char [] endSeparator = new char[] { '"', ',' };
65 string [] values = new string [keywords.Length];
67 public DigestHeaderParser (string header)
69 this.header = header.Trim ();
73 get { return values [0]; }
76 public string Opaque {
77 get { return values [1]; }
81 get { return values [2]; }
84 public string Algorithm {
85 get { return values [3]; }
89 get { return values [4]; }
94 if (!header.ToLower ().StartsWith ("digest "))
98 length = this.header.Length;
99 while (pos < length) {
101 if (!GetKeywordAndValue (out key, out value))
105 if (pos < length && header [pos] == ',')
108 int idx = Array.IndexOf (keywords, (key));
112 if (values [idx] != null)
115 values [idx] = value;
118 if (Realm == null || Nonce == null)
124 void SkipWhitespace ()
127 while (pos < length && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
133 void SkipNonWhitespace ()
136 while (pos < length && c != ' ' && c != '\t' && c != '\r' && c != '\n') {
146 while (pos < length && header [pos] != '=') {
150 string key = header.Substring (begin, pos - begin).Trim ().ToLower ();
154 bool GetKeywordAndValue (out string key, out string value)
163 if (pos + 1 >= length || header [pos++] != '=')
167 // note: Apache doesn't use " in all case (like algorithm)
168 if (pos + 1 >= length)
171 bool useQuote = false;
172 if (header [pos] == '"') {
179 pos = header.IndexOf ('"', pos);
184 char c = header [pos];
185 if (c == ',' || c == ' ' || c == '\t' || c == '\r' || c == '\n')
187 } while (++pos < length);
189 if (pos >= length && beginQ == pos)
193 value = header.Substring (beginQ, pos - beginQ);
201 static RandomNumberGenerator rng;
204 static DigestSession ()
206 rng = RandomNumberGenerator.Create ();
210 private HashAlgorithm hash;
211 private DigestHeaderParser parser;
212 private string _cnonce;
214 public DigestSession ()
217 lastUse = DateTime.Now;
220 public string Algorithm {
221 get { return parser.Algorithm; }
224 public string Realm {
225 get { return parser.Realm; }
228 public string Nonce {
229 get { return parser.Nonce; }
232 public string Opaque {
233 get { return parser.Opaque; }
237 get { return parser.QOP; }
240 public string CNonce {
242 if (_cnonce == null) {
243 // 15 is a multiple of 3 which is better for base64 because it
244 // wont end with '=' and risk messing up the server parsing
245 byte[] bincnonce = new byte [15];
246 rng.GetBytes (bincnonce);
247 _cnonce = Convert.ToBase64String (bincnonce);
248 Array.Clear (bincnonce, 0, bincnonce.Length);
254 public bool Parse (string challenge)
256 parser = new DigestHeaderParser (challenge);
257 if (!parser.Parse ()) {
261 // build the hash object (only MD5 is defined in RFC2617)
262 if ((parser.Algorithm == null) || (parser.Algorithm.ToUpper ().StartsWith ("MD5")))
263 hash = HashAlgorithm.Create ("MD5");
268 private string HashToHexString (string toBeHashed)
274 byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed));
276 StringBuilder sb = new StringBuilder ();
277 foreach (byte b in result)
278 sb.Append (b.ToString ("x2"));
279 return sb.ToString ();
282 private string HA1 (string username, string password)
284 string ha1 = String.Format ("{0}:{1}:{2}", username, Realm, password);
285 if (Algorithm != null && Algorithm.ToLower () == "md5-sess")
286 ha1 = String.Format ("{0}:{1}:{2}", HashToHexString (ha1), Nonce, CNonce);
287 return HashToHexString (ha1);
290 private string HA2 (HttpWebRequest webRequest)
292 string ha2 = String.Format ("{0}:{1}", webRequest.Method, webRequest.RequestUri.PathAndQuery);
293 if (QOP == "auth-int") {
295 // ha2 += String.Format (":{0}", hentity);
297 return HashToHexString (ha2);
300 private string Response (string username, string password, HttpWebRequest webRequest)
302 string response = String.Format ("{0}:{1}:", HA1 (username, password), Nonce);
304 response += String.Format ("{0}:{1}:{2}:", _nc.ToString ("x8"), CNonce, QOP);
305 response += HA2 (webRequest);
306 return HashToHexString (response);
309 public Authorization Authenticate (WebRequest webRequest, ICredentials credentials)
312 throw new InvalidOperationException ();
314 HttpWebRequest request = webRequest as HttpWebRequest;
318 lastUse = DateTime.Now;
319 NetworkCredential cred = credentials.GetCredential (request.RequestUri, "digest");
323 string userName = cred.UserName;
324 if (userName == null || userName == "")
327 string password = cred.Password;
329 StringBuilder auth = new StringBuilder ();
330 auth.AppendFormat ("Digest username=\"{0}\", ", userName);
331 auth.AppendFormat ("realm=\"{0}\", ", Realm);
332 auth.AppendFormat ("nonce=\"{0}\", ", Nonce);
333 auth.AppendFormat ("uri=\"{0}\", ", request.Address.PathAndQuery);
335 if (Algorithm != null) { // hash algorithm (only MD5 in RFC2617)
336 auth.AppendFormat ("algorithm=\"{0}\", ", Algorithm);
339 auth.AppendFormat ("response=\"{0}\", ", Response (userName, password, request));
341 if (QOP != null) { // quality of protection (server decision)
342 auth.AppendFormat ("qop={0}, ", QOP);
346 // _nc MUST NOT change from here...
347 // number of request using this nonce
349 auth.AppendFormat ("nc={0:X8}, ", _nc);
352 // until here, now _nc can change
355 if (CNonce != null) // opaque value from the client
356 auth.AppendFormat ("cnonce=\"{0}\", ", CNonce);
358 if (Opaque != null) // exact same opaque value as received from server
359 auth.AppendFormat ("opaque=\"{0}\", ", Opaque);
361 auth.Length -= 2; // remove ", "
362 return new Authorization (auth.ToString ());
365 public DateTime LastUse {
366 get { return lastUse; }
370 class DigestClient : IAuthenticationModule
373 static Hashtable cache;
375 public DigestClient () {}
377 static Hashtable Cache {
379 lock (typeof (DigestClient)) {
381 cache = Hashtable.Synchronized (new Hashtable ());
383 CheckExpired (cache.Count);
391 static void CheckExpired (int count)
396 DateTime t = DateTime.MaxValue;
397 DateTime now = DateTime.Now;
398 ArrayList list = null;
399 foreach (int key in cache.Keys) {
400 DigestSession elem = (DigestSession) cache [key];
401 if (elem.LastUse < t &&
402 (elem.LastUse - now).Ticks > TimeSpan.TicksPerMinute * 10) {
405 list = new ArrayList ();
412 foreach (int k in list)
417 // IAuthenticationModule
419 public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials)
421 if (credentials == null || challenge == null)
424 string header = challenge.Trim ();
425 if (header.ToLower ().IndexOf ("digest") == -1)
428 HttpWebRequest request = webRequest as HttpWebRequest;
432 int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
433 DigestSession ds = (DigestSession) Cache [hashcode];
434 bool addDS = (ds == null);
436 ds = new DigestSession ();
438 if (!ds.Parse (challenge))
442 Cache.Add (hashcode, ds);
444 return ds.Authenticate (webRequest, credentials);
447 public Authorization PreAuthenticate (WebRequest webRequest, ICredentials credentials)
449 HttpWebRequest request = webRequest as HttpWebRequest;
453 if (credentials == null)
456 int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
457 DigestSession ds = (DigestSession) Cache [hashcode];
461 return ds.Authenticate (webRequest, credentials);
464 public string AuthenticationType {
465 get { return "Digest"; }
468 public bool CanPreAuthenticate {