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 string [] values = new string [keywords.Length];
66 public DigestHeaderParser (string header)
68 this.header = header.Trim ();
72 get { return values [0]; }
75 public string Opaque {
76 get { return values [1]; }
80 get { return values [2]; }
83 public string Algorithm {
84 get { return values [3]; }
88 get { return values [4]; }
93 if (!header.ToLower ().StartsWith ("digest "))
97 length = this.header.Length;
98 while (pos < length) {
100 if (!GetKeywordAndValue (out key, out value))
104 if (pos < length && header [pos] == ',')
107 int idx = Array.IndexOf (keywords, (key));
111 if (values [idx] != null)
114 values [idx] = value;
117 if (Realm == null || Nonce == null)
123 void SkipWhitespace ()
126 while (pos < length && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
136 while (pos < length && header [pos] != '=') {
140 string key = header.Substring (begin, pos - begin).Trim ().ToLower ();
144 bool GetKeywordAndValue (out string key, out string value)
153 if (pos + 1 >= length || header [pos++] != '=')
157 // note: Apache doesn't use " in all case (like algorithm)
158 if (pos + 1 >= length)
161 bool useQuote = false;
162 if (header [pos] == '"') {
169 pos = header.IndexOf ('"', pos);
174 char c = header [pos];
175 if (c == ',' || c == ' ' || c == '\t' || c == '\r' || c == '\n')
177 } while (++pos < length);
179 if (pos >= length && beginQ == pos)
183 value = header.Substring (beginQ, pos - beginQ);
191 static RandomNumberGenerator rng;
194 static DigestSession ()
196 rng = RandomNumberGenerator.Create ();
200 private HashAlgorithm hash;
201 private DigestHeaderParser parser;
202 private string _cnonce;
204 public DigestSession ()
207 lastUse = DateTime.Now;
210 public string Algorithm {
211 get { return parser.Algorithm; }
214 public string Realm {
215 get { return parser.Realm; }
218 public string Nonce {
219 get { return parser.Nonce; }
222 public string Opaque {
223 get { return parser.Opaque; }
227 get { return parser.QOP; }
230 public string CNonce {
232 if (_cnonce == null) {
233 // 15 is a multiple of 3 which is better for base64 because it
234 // wont end with '=' and risk messing up the server parsing
235 byte[] bincnonce = new byte [15];
236 rng.GetBytes (bincnonce);
237 _cnonce = Convert.ToBase64String (bincnonce);
238 Array.Clear (bincnonce, 0, bincnonce.Length);
244 public bool Parse (string challenge)
246 parser = new DigestHeaderParser (challenge);
247 if (!parser.Parse ()) {
251 // build the hash object (only MD5 is defined in RFC2617)
252 if ((parser.Algorithm == null) || (parser.Algorithm.ToUpper ().StartsWith ("MD5")))
253 hash = HashAlgorithm.Create ("MD5");
258 private string HashToHexString (string toBeHashed)
264 byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed));
266 StringBuilder sb = new StringBuilder ();
267 foreach (byte b in result)
268 sb.Append (b.ToString ("x2"));
269 return sb.ToString ();
272 private string HA1 (string username, string password)
274 string ha1 = String.Format ("{0}:{1}:{2}", username, Realm, password);
275 if (Algorithm != null && Algorithm.ToLower () == "md5-sess")
276 ha1 = String.Format ("{0}:{1}:{2}", HashToHexString (ha1), Nonce, CNonce);
277 return HashToHexString (ha1);
280 private string HA2 (HttpWebRequest webRequest)
282 string ha2 = String.Format ("{0}:{1}", webRequest.Method, webRequest.RequestUri.PathAndQuery);
283 if (QOP == "auth-int") {
285 // ha2 += String.Format (":{0}", hentity);
287 return HashToHexString (ha2);
290 private string Response (string username, string password, HttpWebRequest webRequest)
292 string response = String.Format ("{0}:{1}:", HA1 (username, password), Nonce);
294 response += String.Format ("{0}:{1}:{2}:", _nc.ToString ("X8"), CNonce, QOP);
295 response += HA2 (webRequest);
296 return HashToHexString (response);
299 public Authorization Authenticate (WebRequest webRequest, ICredentials credentials)
302 throw new InvalidOperationException ();
304 HttpWebRequest request = webRequest as HttpWebRequest;
308 lastUse = DateTime.Now;
309 NetworkCredential cred = credentials.GetCredential (request.RequestUri, "digest");
313 string userName = cred.UserName;
314 if (userName == null || userName == "")
317 string password = cred.Password;
319 StringBuilder auth = new StringBuilder ();
320 auth.AppendFormat ("Digest username=\"{0}\", ", userName);
321 auth.AppendFormat ("realm=\"{0}\", ", Realm);
322 auth.AppendFormat ("nonce=\"{0}\", ", Nonce);
323 auth.AppendFormat ("uri=\"{0}\", ", request.Address.PathAndQuery);
325 if (Algorithm != null) { // hash algorithm (only MD5 in RFC2617)
326 auth.AppendFormat ("algorithm=\"{0}\", ", Algorithm);
329 auth.AppendFormat ("response=\"{0}\", ", Response (userName, password, request));
331 if (QOP != null) { // quality of protection (server decision)
332 auth.AppendFormat ("qop=\"{0}\", ", QOP);
336 // _nc MUST NOT change from here...
337 // number of request using this nonce
339 auth.AppendFormat ("nc={0:X8}, ", _nc);
342 // until here, now _nc can change
345 if (CNonce != null) // opaque value from the client
346 auth.AppendFormat ("cnonce=\"{0}\", ", CNonce);
348 if (Opaque != null) // exact same opaque value as received from server
349 auth.AppendFormat ("opaque=\"{0}\", ", Opaque);
351 auth.Length -= 2; // remove ", "
352 return new Authorization (auth.ToString ());
355 public DateTime LastUse {
356 get { return lastUse; }
360 class DigestClient : IAuthenticationModule
363 static readonly Hashtable cache = Hashtable.Synchronized (new Hashtable ());
365 static Hashtable Cache {
367 lock (cache.SyncRoot) {
368 CheckExpired (cache.Count);
375 static void CheckExpired (int count)
380 DateTime t = DateTime.MaxValue;
381 DateTime now = DateTime.Now;
382 ArrayList list = null;
383 foreach (int key in cache.Keys) {
384 DigestSession elem = (DigestSession) cache [key];
385 if (elem.LastUse < t &&
386 (elem.LastUse - now).Ticks > TimeSpan.TicksPerMinute * 10) {
389 list = new ArrayList ();
396 foreach (int k in list)
401 // IAuthenticationModule
403 public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials)
405 if (credentials == null || challenge == null)
408 string header = challenge.Trim ();
409 if (header.ToLower ().IndexOf ("digest") == -1)
412 HttpWebRequest request = webRequest as HttpWebRequest;
416 int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
417 DigestSession ds = (DigestSession) Cache [hashcode];
418 bool addDS = (ds == null);
420 ds = new DigestSession ();
422 if (!ds.Parse (challenge))
426 Cache.Add (hashcode, ds);
428 return ds.Authenticate (webRequest, credentials);
431 public Authorization PreAuthenticate (WebRequest webRequest, ICredentials credentials)
433 HttpWebRequest request = webRequest as HttpWebRequest;
437 if (credentials == null)
440 int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
441 DigestSession ds = (DigestSession) Cache [hashcode];
445 return ds.Authenticate (webRequest, credentials);
448 public string AuthenticationType {
449 get { return "Digest"; }
452 public bool CanPreAuthenticate {