DigestClient.cs 11 KB

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