DigestClient.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //
  2. // System.Net.DigestClient.cs
  3. //
  4. // Authors:
  5. // Greg Reinacker ([email protected])
  6. // Sebastien Pouliot ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected]
  8. //
  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)
  12. //
  13. // Original (server-side) source code available at
  14. // http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html
  15. //
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Specialized;
  19. using System.IO;
  20. using System.Net;
  21. using System.Security.Cryptography;
  22. using System.Text;
  23. namespace System.Net
  24. {
  25. //
  26. // This works with apache mod_digest
  27. //TODO:
  28. // MD5-sess
  29. // qop (auth-int)
  30. //
  31. // See RFC 2617 for details.
  32. //
  33. class DigestHeaderParser
  34. {
  35. string header;
  36. int length;
  37. int pos;
  38. static string [] keywords = { "realm", "opaque", "nonce", "algorithm", "qop" };
  39. string [] values = new string [keywords.Length];
  40. public DigestHeaderParser (string header)
  41. {
  42. this.header = header.Trim ();
  43. }
  44. public string Realm {
  45. get { return values [0]; }
  46. }
  47. public string Opaque {
  48. get { return values [1]; }
  49. }
  50. public string Nonce {
  51. get { return values [2]; }
  52. }
  53. public string Algorithm {
  54. get { return values [3]; }
  55. }
  56. public string QOP {
  57. get { return values [4]; }
  58. }
  59. public bool Parse ()
  60. {
  61. if (!header.ToLower ().StartsWith ("digest "))
  62. return false;
  63. pos = 6;
  64. length = this.header.Length;
  65. while (pos < length) {
  66. string key, value;
  67. if (!GetKeywordAndValue (out key, out value))
  68. return false;
  69. SkipWhitespace ();
  70. if (pos < length && header [pos] == ',')
  71. pos++;
  72. int idx = Array.IndexOf (keywords, (key));
  73. if (idx == -1)
  74. continue;
  75. if (values [idx] != null)
  76. return false;
  77. values [idx] = value;
  78. }
  79. if (Realm == null || Nonce == null)
  80. return false;
  81. return true;
  82. }
  83. void SkipWhitespace ()
  84. {
  85. char c = ' ';
  86. while (pos < length && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
  87. c = header [pos++];
  88. }
  89. pos--;
  90. }
  91. void SkipNonWhitespace ()
  92. {
  93. char c = 'a';
  94. while (pos < length && c != ' ' && c != '\t' && c != '\r' && c != '\n') {
  95. c = header [pos++];
  96. }
  97. pos--;
  98. }
  99. string GetKey ()
  100. {
  101. SkipWhitespace ();
  102. int begin = pos;
  103. while (pos < length && header [pos] != '=') {
  104. pos++;
  105. }
  106. string key = header.Substring (begin, pos - begin).Trim ().ToLower ();
  107. return key;
  108. }
  109. bool GetKeywordAndValue (out string key, out string value)
  110. {
  111. key = null;
  112. value = null;
  113. key = GetKey ();
  114. if (pos >= length)
  115. return false;
  116. SkipWhitespace ();
  117. if (pos + 1 >= length || header [pos++] != '=')
  118. return false;
  119. SkipWhitespace ();
  120. if (pos + 1 >= length || header [pos++] != '"')
  121. return false;
  122. int beginQ = pos;
  123. pos = header.IndexOf ('"', pos);
  124. if (pos == -1)
  125. return false;
  126. value = header.Substring (beginQ, pos - beginQ);
  127. pos += 2;
  128. return true;
  129. }
  130. }
  131. class DigestSession
  132. {
  133. static RandomNumberGenerator rng;
  134. static DigestSession ()
  135. {
  136. rng = RandomNumberGenerator.Create ();
  137. }
  138. private int _nc;
  139. private HashAlgorithm hash;
  140. private DigestHeaderParser parser;
  141. private string _cnonce;
  142. public DigestSession ()
  143. {
  144. _nc = 1;
  145. }
  146. public string Algorithm {
  147. get { return parser.Algorithm; }
  148. }
  149. public string Realm {
  150. get { return parser.Realm; }
  151. }
  152. public string Nonce {
  153. get { return parser.Nonce; }
  154. }
  155. public string Opaque {
  156. get { return parser.Opaque; }
  157. }
  158. public string QOP {
  159. get { return parser.QOP; }
  160. }
  161. public string CNonce {
  162. get {
  163. if (_cnonce == null) {
  164. // 15 is a multiple of 3 which is better for base64 because it
  165. // wont end with '=' and risk messing up the server parsing
  166. byte[] bincnonce = new byte [15];
  167. rng.GetBytes (bincnonce);
  168. _cnonce = Convert.ToBase64String (bincnonce);
  169. Array.Clear (bincnonce, 0, bincnonce.Length);
  170. }
  171. return _cnonce;
  172. }
  173. }
  174. public bool Parse (string challenge)
  175. {
  176. parser = new DigestHeaderParser (challenge);
  177. if (!parser.Parse ()) {
  178. Console.WriteLine ("Parser");
  179. return false;
  180. }
  181. // build the hash object (only MD5 is defined in RFC2617)
  182. if ((parser.Algorithm == null) || (parser.Algorithm.ToUpper ().StartsWith ("MD5")))
  183. hash = HashAlgorithm.Create ("MD5");
  184. return true;
  185. }
  186. private string HashToHexString (string toBeHashed)
  187. {
  188. if (hash == null)
  189. return null;
  190. hash.Initialize ();
  191. byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed));
  192. StringBuilder sb = new StringBuilder ();
  193. foreach (byte b in result)
  194. sb.Append (b.ToString ("x2"));
  195. return sb.ToString ();
  196. }
  197. private string HA1 (string username, string password)
  198. {
  199. string ha1 = String.Format ("{0}:{1}:{2}", username, Realm, password);
  200. if (Algorithm != null && Algorithm.ToLower () == "md5-sess")
  201. ha1 = String.Format ("{0}:{1}:{2}", HashToHexString (ha1), Nonce, CNonce);
  202. return HashToHexString (ha1);
  203. }
  204. private string HA2 (HttpWebRequest webRequest)
  205. {
  206. string ha2 = String.Format ("{0}:{1}", webRequest.Method, webRequest.RequestUri.AbsolutePath);
  207. if (QOP == "auth-int") {
  208. // TODO
  209. // ha2 += String.Format (":{0}", hentity);
  210. }
  211. return HashToHexString (ha2);
  212. }
  213. private string Response (string username, string password, HttpWebRequest webRequest)
  214. {
  215. string response = String.Format ("{0}:{1}:", HA1 (username, password), Nonce);
  216. if (QOP != null)
  217. response += String.Format ("{0}:{1}:{2}:", _nc.ToString ("x8"), CNonce, QOP);
  218. response += HA2 (webRequest);
  219. return HashToHexString (response);
  220. }
  221. public Authorization Authenticate (WebRequest webRequest, ICredentials credentials)
  222. {
  223. if (parser == null)
  224. throw new InvalidOperationException ();
  225. HttpWebRequest request = webRequest as HttpWebRequest;
  226. if (request == null)
  227. return null;
  228. NetworkCredential cred = credentials.GetCredential (request.RequestUri, "digest");
  229. string userName = cred.UserName;
  230. if (userName == null || userName == "")
  231. return null;
  232. string password = cred.Password;
  233. StringBuilder auth = new StringBuilder ();
  234. auth.AppendFormat ("Digest username=\"{0}\", ", userName);
  235. auth.AppendFormat ("realm=\"{0}\", ", Realm);
  236. auth.AppendFormat ("nonce=\"{0}\", ", Nonce);
  237. auth.AppendFormat ("uri=\"{0}\", ", request.Address.PathAndQuery);
  238. if (QOP != null) // quality of protection (server decision)
  239. auth.AppendFormat ("qop=\"{0}\", ", QOP);
  240. if (Algorithm != null) // hash algorithm (only MD5 in RFC2617)
  241. auth.AppendFormat ("algorithm=\"{0}\", ", Algorithm);
  242. lock (this) {
  243. // _nc MUST NOT change from here...
  244. // number of request using this nonce
  245. if (QOP != null) {
  246. auth.AppendFormat ("nc={0:X8}, ", _nc);
  247. _nc++;
  248. }
  249. // until here, now _nc can change
  250. }
  251. if (QOP != null) // opaque value from the client
  252. auth.AppendFormat ("cnonce=\"{0}\", ", CNonce);
  253. if (Opaque != null) // exact same opaque value as received from server
  254. auth.AppendFormat ("opaque=\"{0}\", ", Opaque);
  255. auth.AppendFormat ("response=\"{0}\"", Response (userName, password, request));
  256. return new Authorization (auth.ToString ());
  257. }
  258. }
  259. class DigestClient : IAuthenticationModule
  260. {
  261. static Hashtable cache; // cache entries by nonce
  262. static DigestClient ()
  263. {
  264. cache = Hashtable.Synchronized (new Hashtable ());
  265. }
  266. public DigestClient () {}
  267. // IAuthenticationModule
  268. public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials)
  269. {
  270. if (credentials == null || challenge == null)
  271. return null;
  272. string header = challenge.Trim ();
  273. if (header.ToLower ().IndexOf ("digest") == -1)
  274. return null;
  275. HttpWebRequest request = webRequest as HttpWebRequest;
  276. if (request == null)
  277. return null;
  278. DigestSession ds = (DigestSession) cache [request.Address];
  279. bool addDS = (ds == null);
  280. if (addDS)
  281. ds = new DigestSession ();
  282. if (!ds.Parse (challenge))
  283. return null;
  284. if (addDS)
  285. cache.Add (request.Address, ds);
  286. return ds.Authenticate (webRequest, credentials);
  287. }
  288. public Authorization PreAuthenticate (WebRequest webRequest, ICredentials credentials)
  289. {
  290. HttpWebRequest request = webRequest as HttpWebRequest;
  291. if (request == null)
  292. return null;
  293. // check cache for URI
  294. DigestSession ds = (DigestSession) cache [request.Address];
  295. if (ds == null)
  296. return null;
  297. return ds.Authenticate (webRequest, credentials);
  298. }
  299. public string AuthenticationType {
  300. get { return "Digest"; }
  301. }
  302. public bool CanPreAuthenticate {
  303. get { return true; }
  304. }
  305. }
  306. }