DigestClient.cs 8.7 KB

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