DigestClient.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. static char [] endSeparator = new char[] { '"', ',' };
  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. // note: Apache doesn't use " in all case (like algorithm)
  122. if (pos + 1 >= length)
  123. return false;
  124. bool useQuote = false;
  125. if (header [pos] == '"') {
  126. pos++;
  127. useQuote = true;
  128. }
  129. int beginQ = pos;
  130. if (useQuote) {
  131. pos = header.IndexOf ('"', pos);
  132. if (pos == -1)
  133. return false;
  134. } else {
  135. do {
  136. char c = header [pos];
  137. if (c == ',' || c == ' ' || c == '\t' || c == '\r' || c == '\n')
  138. break;
  139. } while (++pos < length);
  140. if (pos >= length && beginQ == pos)
  141. return false;
  142. }
  143. value = header.Substring (beginQ, pos - beginQ);
  144. pos += 2;
  145. return true;
  146. }
  147. }
  148. class DigestSession
  149. {
  150. static RandomNumberGenerator rng;
  151. DateTime lastUse;
  152. static DigestSession ()
  153. {
  154. rng = RandomNumberGenerator.Create ();
  155. }
  156. private int _nc;
  157. private HashAlgorithm hash;
  158. private DigestHeaderParser parser;
  159. private string _cnonce;
  160. public DigestSession ()
  161. {
  162. _nc = 1;
  163. lastUse = DateTime.Now;
  164. }
  165. public string Algorithm {
  166. get { return parser.Algorithm; }
  167. }
  168. public string Realm {
  169. get { return parser.Realm; }
  170. }
  171. public string Nonce {
  172. get { return parser.Nonce; }
  173. }
  174. public string Opaque {
  175. get { return parser.Opaque; }
  176. }
  177. public string QOP {
  178. get { return parser.QOP; }
  179. }
  180. public string CNonce {
  181. get {
  182. if (_cnonce == null) {
  183. // 15 is a multiple of 3 which is better for base64 because it
  184. // wont end with '=' and risk messing up the server parsing
  185. byte[] bincnonce = new byte [15];
  186. rng.GetBytes (bincnonce);
  187. _cnonce = Convert.ToBase64String (bincnonce);
  188. Array.Clear (bincnonce, 0, bincnonce.Length);
  189. }
  190. return _cnonce;
  191. }
  192. }
  193. public bool Parse (string challenge)
  194. {
  195. parser = new DigestHeaderParser (challenge);
  196. if (!parser.Parse ()) {
  197. return false;
  198. }
  199. // build the hash object (only MD5 is defined in RFC2617)
  200. if ((parser.Algorithm == null) || (parser.Algorithm.ToUpper ().StartsWith ("MD5")))
  201. hash = HashAlgorithm.Create ("MD5");
  202. return true;
  203. }
  204. private string HashToHexString (string toBeHashed)
  205. {
  206. if (hash == null)
  207. return null;
  208. hash.Initialize ();
  209. byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed));
  210. StringBuilder sb = new StringBuilder ();
  211. foreach (byte b in result)
  212. sb.Append (b.ToString ("x2"));
  213. return sb.ToString ();
  214. }
  215. private string HA1 (string username, string password)
  216. {
  217. string ha1 = String.Format ("{0}:{1}:{2}", username, Realm, password);
  218. if (Algorithm != null && Algorithm.ToLower () == "md5-sess")
  219. ha1 = String.Format ("{0}:{1}:{2}", HashToHexString (ha1), Nonce, CNonce);
  220. return HashToHexString (ha1);
  221. }
  222. private string HA2 (HttpWebRequest webRequest)
  223. {
  224. string ha2 = String.Format ("{0}:{1}", webRequest.Method, webRequest.RequestUri.AbsolutePath);
  225. if (QOP == "auth-int") {
  226. // TODO
  227. // ha2 += String.Format (":{0}", hentity);
  228. }
  229. return HashToHexString (ha2);
  230. }
  231. private string Response (string username, string password, HttpWebRequest webRequest)
  232. {
  233. string response = String.Format ("{0}:{1}:", HA1 (username, password), Nonce);
  234. if (QOP != null)
  235. response += String.Format ("{0}:{1}:{2}:", _nc.ToString ("x8"), CNonce, QOP);
  236. response += HA2 (webRequest);
  237. return HashToHexString (response);
  238. }
  239. public Authorization Authenticate (WebRequest webRequest, ICredentials credentials)
  240. {
  241. if (parser == null)
  242. throw new InvalidOperationException ();
  243. HttpWebRequest request = webRequest as HttpWebRequest;
  244. if (request == null)
  245. return null;
  246. lastUse = DateTime.Now;
  247. NetworkCredential cred = credentials.GetCredential (request.RequestUri, "digest");
  248. string userName = cred.UserName;
  249. if (userName == null || userName == "")
  250. return null;
  251. string password = cred.Password;
  252. StringBuilder auth = new StringBuilder ();
  253. auth.AppendFormat ("Digest username=\"{0}\", ", userName);
  254. auth.AppendFormat ("realm=\"{0}\", ", Realm);
  255. auth.AppendFormat ("nonce=\"{0}\", ", Nonce);
  256. auth.AppendFormat ("uri=\"{0}\", ", request.Address.PathAndQuery);
  257. if (Algorithm != null) { // hash algorithm (only MD5 in RFC2617)
  258. auth.AppendFormat ("algorithm=\"{0}\", ", Algorithm);
  259. }
  260. auth.AppendFormat ("response=\"{0}\", ", Response (userName, password, request));
  261. if (QOP != null) { // quality of protection (server decision)
  262. auth.AppendFormat ("qop={0}, ", QOP);
  263. }
  264. lock (this) {
  265. // _nc MUST NOT change from here...
  266. // number of request using this nonce
  267. if (QOP != null) {
  268. auth.AppendFormat ("nc={0:X8}, ", _nc);
  269. _nc++;
  270. }
  271. // until here, now _nc can change
  272. }
  273. if (CNonce != null) // opaque value from the client
  274. auth.AppendFormat ("cnonce=\"{0}\", ", CNonce);
  275. if (Opaque != null) // exact same opaque value as received from server
  276. auth.AppendFormat ("opaque=\"{0}\", ", Opaque);
  277. auth.Length -= 2; // remove ", "
  278. return new Authorization (auth.ToString ());
  279. }
  280. public DateTime LastUse {
  281. get { return lastUse; }
  282. }
  283. }
  284. class DigestClient : IAuthenticationModule
  285. {
  286. static Hashtable cache;
  287. public DigestClient () {}
  288. static Hashtable Cache {
  289. get {
  290. lock (typeof (DigestClient)) {
  291. if (cache == null) {
  292. cache = Hashtable.Synchronized (new Hashtable ());
  293. } else {
  294. CheckExpired (cache.Count);
  295. }
  296. return cache;
  297. }
  298. }
  299. }
  300. static void CheckExpired (int count)
  301. {
  302. if (count < 10)
  303. return;
  304. DateTime t = DateTime.MaxValue;
  305. DateTime now = DateTime.Now;
  306. ArrayList list = null;
  307. foreach (int key in cache.Keys) {
  308. DigestSession elem = (DigestSession) cache [key];
  309. if (elem.LastUse < t &&
  310. (elem.LastUse - now).Ticks > TimeSpan.TicksPerMinute * 10) {
  311. t = elem.LastUse;
  312. if (list == null)
  313. list = new ArrayList ();
  314. list.Add (key);
  315. }
  316. }
  317. if (list != null) {
  318. foreach (int k in list)
  319. cache.Remove (k);
  320. }
  321. }
  322. // IAuthenticationModule
  323. public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials)
  324. {
  325. if (credentials == null || challenge == null)
  326. return null;
  327. string header = challenge.Trim ();
  328. if (header.ToLower ().IndexOf ("digest") == -1)
  329. return null;
  330. HttpWebRequest request = webRequest as HttpWebRequest;
  331. if (request == null)
  332. return null;
  333. int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
  334. DigestSession ds = (DigestSession) Cache [hashcode];
  335. bool addDS = (ds == null);
  336. if (addDS)
  337. ds = new DigestSession ();
  338. if (!ds.Parse (challenge))
  339. return null;
  340. if (addDS)
  341. Cache.Add (hashcode, ds);
  342. return ds.Authenticate (webRequest, credentials);
  343. }
  344. public Authorization PreAuthenticate (WebRequest webRequest, ICredentials credentials)
  345. {
  346. HttpWebRequest request = webRequest as HttpWebRequest;
  347. if (request == null)
  348. return null;
  349. if (credentials == null)
  350. return null;
  351. int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
  352. DigestSession ds = (DigestSession) Cache [hashcode];
  353. if (ds == null)
  354. return null;
  355. return ds.Authenticate (webRequest, credentials);
  356. }
  357. public string AuthenticationType {
  358. get { return "Digest"; }
  359. }
  360. public bool CanPreAuthenticate {
  361. get { return true; }
  362. }
  363. }
  364. }