DigestClient.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. //
  17. // Permission is hereby granted, free of charge, to any person obtaining
  18. // a copy of this software and associated documentation files (the
  19. // "Software"), to deal in the Software without restriction, including
  20. // without limitation the rights to use, copy, modify, merge, publish,
  21. // distribute, sublicense, and/or sell copies of the Software, and to
  22. // permit persons to whom the Software is furnished to do so, subject to
  23. // the following conditions:
  24. //
  25. // The above copyright notice and this permission notice shall be
  26. // included in all copies or substantial portions of the Software.
  27. //
  28. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  29. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  31. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  32. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  33. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  34. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  35. //
  36. using System;
  37. using System.Collections;
  38. using System.Collections.Specialized;
  39. using System.IO;
  40. using System.Net;
  41. using System.Security.Cryptography;
  42. using System.Text;
  43. namespace System.Net
  44. {
  45. //
  46. // This works with apache mod_digest
  47. //TODO:
  48. // MD5-sess
  49. // qop (auth-int)
  50. //
  51. // See RFC 2617 for details.
  52. //
  53. class DigestHeaderParser
  54. {
  55. string header;
  56. int length;
  57. int pos;
  58. static string [] keywords = { "realm", "opaque", "nonce", "algorithm", "qop" };
  59. static char [] endSeparator = new char[] { '"', ',' };
  60. string [] values = new string [keywords.Length];
  61. public DigestHeaderParser (string header)
  62. {
  63. this.header = header.Trim ();
  64. }
  65. public string Realm {
  66. get { return values [0]; }
  67. }
  68. public string Opaque {
  69. get { return values [1]; }
  70. }
  71. public string Nonce {
  72. get { return values [2]; }
  73. }
  74. public string Algorithm {
  75. get { return values [3]; }
  76. }
  77. public string QOP {
  78. get { return values [4]; }
  79. }
  80. public bool Parse ()
  81. {
  82. if (!header.ToLower ().StartsWith ("digest "))
  83. return false;
  84. pos = 6;
  85. length = this.header.Length;
  86. while (pos < length) {
  87. string key, value;
  88. if (!GetKeywordAndValue (out key, out value))
  89. return false;
  90. SkipWhitespace ();
  91. if (pos < length && header [pos] == ',')
  92. pos++;
  93. int idx = Array.IndexOf (keywords, (key));
  94. if (idx == -1)
  95. continue;
  96. if (values [idx] != null)
  97. return false;
  98. values [idx] = value;
  99. }
  100. if (Realm == null || Nonce == null)
  101. return false;
  102. return true;
  103. }
  104. void SkipWhitespace ()
  105. {
  106. char c = ' ';
  107. while (pos < length && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
  108. c = header [pos++];
  109. }
  110. pos--;
  111. }
  112. void SkipNonWhitespace ()
  113. {
  114. char c = 'a';
  115. while (pos < length && c != ' ' && c != '\t' && c != '\r' && c != '\n') {
  116. c = header [pos++];
  117. }
  118. pos--;
  119. }
  120. string GetKey ()
  121. {
  122. SkipWhitespace ();
  123. int begin = pos;
  124. while (pos < length && header [pos] != '=') {
  125. pos++;
  126. }
  127. string key = header.Substring (begin, pos - begin).Trim ().ToLower ();
  128. return key;
  129. }
  130. bool GetKeywordAndValue (out string key, out string value)
  131. {
  132. key = null;
  133. value = null;
  134. key = GetKey ();
  135. if (pos >= length)
  136. return false;
  137. SkipWhitespace ();
  138. if (pos + 1 >= length || header [pos++] != '=')
  139. return false;
  140. SkipWhitespace ();
  141. // note: Apache doesn't use " in all case (like algorithm)
  142. if (pos + 1 >= length)
  143. return false;
  144. bool useQuote = false;
  145. if (header [pos] == '"') {
  146. pos++;
  147. useQuote = true;
  148. }
  149. int beginQ = pos;
  150. if (useQuote) {
  151. pos = header.IndexOf ('"', pos);
  152. if (pos == -1)
  153. return false;
  154. } else {
  155. do {
  156. char c = header [pos];
  157. if (c == ',' || c == ' ' || c == '\t' || c == '\r' || c == '\n')
  158. break;
  159. } while (++pos < length);
  160. if (pos >= length && beginQ == pos)
  161. return false;
  162. }
  163. value = header.Substring (beginQ, pos - beginQ);
  164. pos += 2;
  165. return true;
  166. }
  167. }
  168. class DigestSession
  169. {
  170. static RandomNumberGenerator rng;
  171. DateTime lastUse;
  172. static DigestSession ()
  173. {
  174. rng = RandomNumberGenerator.Create ();
  175. }
  176. private int _nc;
  177. private HashAlgorithm hash;
  178. private DigestHeaderParser parser;
  179. private string _cnonce;
  180. public DigestSession ()
  181. {
  182. _nc = 1;
  183. lastUse = DateTime.Now;
  184. }
  185. public string Algorithm {
  186. get { return parser.Algorithm; }
  187. }
  188. public string Realm {
  189. get { return parser.Realm; }
  190. }
  191. public string Nonce {
  192. get { return parser.Nonce; }
  193. }
  194. public string Opaque {
  195. get { return parser.Opaque; }
  196. }
  197. public string QOP {
  198. get { return parser.QOP; }
  199. }
  200. public string CNonce {
  201. get {
  202. if (_cnonce == null) {
  203. // 15 is a multiple of 3 which is better for base64 because it
  204. // wont end with '=' and risk messing up the server parsing
  205. byte[] bincnonce = new byte [15];
  206. rng.GetBytes (bincnonce);
  207. _cnonce = Convert.ToBase64String (bincnonce);
  208. Array.Clear (bincnonce, 0, bincnonce.Length);
  209. }
  210. return _cnonce;
  211. }
  212. }
  213. public bool Parse (string challenge)
  214. {
  215. parser = new DigestHeaderParser (challenge);
  216. if (!parser.Parse ()) {
  217. return false;
  218. }
  219. // build the hash object (only MD5 is defined in RFC2617)
  220. if ((parser.Algorithm == null) || (parser.Algorithm.ToUpper ().StartsWith ("MD5")))
  221. hash = HashAlgorithm.Create ("MD5");
  222. return true;
  223. }
  224. private string HashToHexString (string toBeHashed)
  225. {
  226. if (hash == null)
  227. return null;
  228. hash.Initialize ();
  229. byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed));
  230. StringBuilder sb = new StringBuilder ();
  231. foreach (byte b in result)
  232. sb.Append (b.ToString ("x2"));
  233. return sb.ToString ();
  234. }
  235. private string HA1 (string username, string password)
  236. {
  237. string ha1 = String.Format ("{0}:{1}:{2}", username, Realm, password);
  238. if (Algorithm != null && Algorithm.ToLower () == "md5-sess")
  239. ha1 = String.Format ("{0}:{1}:{2}", HashToHexString (ha1), Nonce, CNonce);
  240. return HashToHexString (ha1);
  241. }
  242. private string HA2 (HttpWebRequest webRequest)
  243. {
  244. string ha2 = String.Format ("{0}:{1}", webRequest.Method, webRequest.RequestUri.PathAndQuery);
  245. if (QOP == "auth-int") {
  246. // TODO
  247. // ha2 += String.Format (":{0}", hentity);
  248. }
  249. return HashToHexString (ha2);
  250. }
  251. private string Response (string username, string password, HttpWebRequest webRequest)
  252. {
  253. string response = String.Format ("{0}:{1}:", HA1 (username, password), Nonce);
  254. if (QOP != null)
  255. response += String.Format ("{0}:{1}:{2}:", _nc.ToString ("x8"), CNonce, QOP);
  256. response += HA2 (webRequest);
  257. return HashToHexString (response);
  258. }
  259. public Authorization Authenticate (WebRequest webRequest, ICredentials credentials)
  260. {
  261. if (parser == null)
  262. throw new InvalidOperationException ();
  263. HttpWebRequest request = webRequest as HttpWebRequest;
  264. if (request == null)
  265. return null;
  266. lastUse = DateTime.Now;
  267. NetworkCredential cred = credentials.GetCredential (request.RequestUri, "digest");
  268. string userName = cred.UserName;
  269. if (userName == null || userName == "")
  270. return null;
  271. string password = cred.Password;
  272. StringBuilder auth = new StringBuilder ();
  273. auth.AppendFormat ("Digest username=\"{0}\", ", userName);
  274. auth.AppendFormat ("realm=\"{0}\", ", Realm);
  275. auth.AppendFormat ("nonce=\"{0}\", ", Nonce);
  276. auth.AppendFormat ("uri=\"{0}\", ", request.Address.PathAndQuery);
  277. if (Algorithm != null) { // hash algorithm (only MD5 in RFC2617)
  278. auth.AppendFormat ("algorithm=\"{0}\", ", Algorithm);
  279. }
  280. auth.AppendFormat ("response=\"{0}\", ", Response (userName, password, request));
  281. if (QOP != null) { // quality of protection (server decision)
  282. auth.AppendFormat ("qop={0}, ", QOP);
  283. }
  284. lock (this) {
  285. // _nc MUST NOT change from here...
  286. // number of request using this nonce
  287. if (QOP != null) {
  288. auth.AppendFormat ("nc={0:X8}, ", _nc);
  289. _nc++;
  290. }
  291. // until here, now _nc can change
  292. }
  293. if (CNonce != null) // opaque value from the client
  294. auth.AppendFormat ("cnonce=\"{0}\", ", CNonce);
  295. if (Opaque != null) // exact same opaque value as received from server
  296. auth.AppendFormat ("opaque=\"{0}\", ", Opaque);
  297. auth.Length -= 2; // remove ", "
  298. return new Authorization (auth.ToString ());
  299. }
  300. public DateTime LastUse {
  301. get { return lastUse; }
  302. }
  303. }
  304. class DigestClient : IAuthenticationModule
  305. {
  306. static Hashtable cache;
  307. public DigestClient () {}
  308. static Hashtable Cache {
  309. get {
  310. lock (typeof (DigestClient)) {
  311. if (cache == null) {
  312. cache = Hashtable.Synchronized (new Hashtable ());
  313. } else {
  314. CheckExpired (cache.Count);
  315. }
  316. return cache;
  317. }
  318. }
  319. }
  320. static void CheckExpired (int count)
  321. {
  322. if (count < 10)
  323. return;
  324. DateTime t = DateTime.MaxValue;
  325. DateTime now = DateTime.Now;
  326. ArrayList list = null;
  327. foreach (int key in cache.Keys) {
  328. DigestSession elem = (DigestSession) cache [key];
  329. if (elem.LastUse < t &&
  330. (elem.LastUse - now).Ticks > TimeSpan.TicksPerMinute * 10) {
  331. t = elem.LastUse;
  332. if (list == null)
  333. list = new ArrayList ();
  334. list.Add (key);
  335. }
  336. }
  337. if (list != null) {
  338. foreach (int k in list)
  339. cache.Remove (k);
  340. }
  341. }
  342. // IAuthenticationModule
  343. public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials)
  344. {
  345. if (credentials == null || challenge == null)
  346. return null;
  347. string header = challenge.Trim ();
  348. if (header.ToLower ().IndexOf ("digest") == -1)
  349. return null;
  350. HttpWebRequest request = webRequest as HttpWebRequest;
  351. if (request == null)
  352. return null;
  353. int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
  354. DigestSession ds = (DigestSession) Cache [hashcode];
  355. bool addDS = (ds == null);
  356. if (addDS)
  357. ds = new DigestSession ();
  358. if (!ds.Parse (challenge))
  359. return null;
  360. if (addDS)
  361. Cache.Add (hashcode, ds);
  362. return ds.Authenticate (webRequest, credentials);
  363. }
  364. public Authorization PreAuthenticate (WebRequest webRequest, ICredentials credentials)
  365. {
  366. HttpWebRequest request = webRequest as HttpWebRequest;
  367. if (request == null)
  368. return null;
  369. if (credentials == null)
  370. return null;
  371. int hashcode = request.Address.GetHashCode () ^ credentials.GetHashCode ();
  372. DigestSession ds = (DigestSession) Cache [hashcode];
  373. if (ds == null)
  374. return null;
  375. return ds.Authenticate (webRequest, credentials);
  376. }
  377. public string AuthenticationType {
  378. get { return "Digest"; }
  379. }
  380. public bool CanPreAuthenticate {
  381. get { return true; }
  382. }
  383. }
  384. }