Digest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using System;
  2. using System.Collections.Generic;
  3. namespace BestHTTP.Authentication
  4. {
  5. using BestHTTP.Extensions;
  6. using System.Text;
  7. /// <summary>
  8. /// Internal class that stores all information that received from a server in a WWW-Authenticate and need to construct a valid Authorization header. Based on rfc 2617 (http://tools.ietf.org/html/rfc2617).
  9. /// Used only internally by the plugin.
  10. /// </summary>
  11. public sealed class Digest
  12. {
  13. #region Public Properties
  14. /// <summary>
  15. /// The Uri that this Digest is bound to.
  16. /// </summary>
  17. public Uri Uri { get; private set; }
  18. public AuthenticationTypes Type { get; private set; }
  19. /// <summary>
  20. /// A string to be displayed to users so they know which username and password to use.
  21. /// This string should contain at least the name of the host performing the authentication and might additionally indicate the collection of users who might have access.
  22. /// </summary>
  23. public string Realm { get; private set; }
  24. /// <summary>
  25. /// A flag, indicating that the previous request from the client was rejected because the nonce value was stale.
  26. /// If stale is TRUE (case-insensitive), the client may wish to simply retry the request with a new encrypted response, without the user for a new username and password.
  27. /// The server should only set stale to TRUE if it receives a request for which the nonce is invalid but with a valid digest for that nonce
  28. /// (indicating that the client knows the correct username/password).
  29. /// If stale is FALSE, or anything other than TRUE, or the stale directive is not present, the username and/or password are invalid, and new values must be obtained.
  30. /// </summary>
  31. public bool Stale { get; private set; }
  32. #endregion
  33. #region Private Properties
  34. /// <summary>
  35. /// A server-specified data string which should be uniquely generated each time a 401 response is made.
  36. /// Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
  37. /// </summary>
  38. private string Nonce { get; set; }
  39. /// <summary>
  40. /// A string of data, specified by the server, which should be returned by the client unchanged in the Authorization header of subsequent requests with URIs in the same protection space.
  41. /// It is recommended that this string be base64 or data.
  42. /// </summary>
  43. private string Opaque { get; set; }
  44. /// <summary>
  45. /// A string indicating a pair of algorithms used to produce the digest and a checksum. If this is not present it is assumed to be "MD5".
  46. /// If the algorithm is not understood, the challenge should be ignored (and a different one used, if there is more than one).
  47. /// </summary>
  48. private string Algorithm { get; set; }
  49. /// <summary>
  50. /// List of URIs, as specified in RFC XURI, that define the protection space.
  51. /// If a URI is an abs_path, it is relative to the canonical root URL (see section 1.2 above) of the server being accessed.
  52. /// An absoluteURI in this list may refer to a different server than the one being accessed.
  53. /// The client can use this list to determine the set of URIs for which the same authentication information may be sent:
  54. /// any URI that has a URI in this list as a prefix (after both have been made absolute) may be assumed to be in the same protection space.
  55. /// If this directive is omitted or its value is empty, the client should assume that the protection space consists of all URIs on the responding server.
  56. /// </summary>
  57. public List<string> ProtectedUris { get; private set; }
  58. /// <summary>
  59. /// If present, it is a quoted string of one or more tokens indicating the "quality of protection" values supported by the server.
  60. /// The value "auth" indicates authentication. The value "auth-int" indicates authentication with integrity protection.
  61. /// </summary>
  62. private string QualityOfProtections { get; set; }
  63. /// <summary>
  64. /// his MUST be specified if a qop directive is sent (see above), and MUST NOT be specified if the server did not send a qop directive in the WWW-Authenticate header field.
  65. /// The nc-value is the hexadecimal count of the number of requests (including the current request) that the client has sent with the nonce value in this request.
  66. /// </summary>
  67. private int NonceCount { get; set; }
  68. /// <summary>
  69. /// Used to store the last HA1 that can be used in the next header generation when Algorithm is set to "md5-sess".
  70. /// </summary>
  71. private string HA1Sess { get; set; }
  72. #endregion
  73. internal Digest(Uri uri)
  74. {
  75. this.Uri = uri;
  76. this.Algorithm = "md5";
  77. }
  78. /// <summary>
  79. /// Parses a WWW-Authenticate header's value to retrive all information.
  80. /// </summary>
  81. public void ParseChallange(string header)
  82. {
  83. // Reset some values to its defaults.
  84. this.Type = AuthenticationTypes.Unknown;
  85. this.Stale = false;
  86. this.Opaque = null;
  87. this.HA1Sess = null;
  88. this.NonceCount = 0;
  89. this.QualityOfProtections = null;
  90. if (this.ProtectedUris != null)
  91. this.ProtectedUris.Clear();
  92. // Parse the header
  93. WWWAuthenticateHeaderParser qpl = new WWWAuthenticateHeaderParser(header);
  94. // Then process
  95. foreach (var qp in qpl.Values)
  96. switch (qp.Key)
  97. {
  98. case "basic": this.Type = AuthenticationTypes.Basic; break;
  99. case "digest": this.Type = AuthenticationTypes.Digest; break;
  100. case "realm": this.Realm = qp.Value; break;
  101. case "domain":
  102. {
  103. if (string.IsNullOrEmpty(qp.Value) || qp.Value.Length == 0)
  104. break;
  105. if (this.ProtectedUris == null)
  106. this.ProtectedUris = new List<string>();
  107. int idx = 0;
  108. string val = qp.Value.Read(ref idx, ' ');
  109. do
  110. {
  111. this.ProtectedUris.Add(val);
  112. val = qp.Value.Read(ref idx, ' ');
  113. } while (idx < qp.Value.Length);
  114. break;
  115. }
  116. case "nonce": this.Nonce = qp.Value; break;
  117. case "qop": this.QualityOfProtections = qp.Value; break;
  118. case "stale": this.Stale = bool.Parse(qp.Value); break;
  119. case "opaque": this.Opaque = qp.Value; break;
  120. case "algorithm": this.Algorithm = qp.Value; break;
  121. }
  122. }
  123. /// <summary>
  124. /// Generates a string that can be set to an Authorization header.
  125. /// </summary>
  126. public string GenerateResponseHeader(HTTPRequest request, Credentials credentials, bool isProxy = false)
  127. {
  128. try
  129. {
  130. switch (Type)
  131. {
  132. case AuthenticationTypes.Basic:
  133. return string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", credentials.UserName, credentials.Password))));
  134. case AuthenticationTypes.Digest:
  135. {
  136. NonceCount++;
  137. string HA1 = string.Empty;
  138. // The cnonce-value is an opaque quoted string value provided by the client and used by both client and server to avoid chosen plaintext attacks, to provide mutual
  139. // authentication, and to provide some message integrity protection.
  140. string cnonce = new System.Random(request.GetHashCode()).Next(int.MinValue, int.MaxValue).ToString("X8");
  141. string ncvalue = NonceCount.ToString("X8");
  142. switch (Algorithm.TrimAndLower())
  143. {
  144. case "md5":
  145. HA1 = string.Format("{0}:{1}:{2}", credentials.UserName, Realm, credentials.Password).CalculateMD5Hash();
  146. break;
  147. case "md5-sess":
  148. if (string.IsNullOrEmpty(this.HA1Sess))
  149. this.HA1Sess = string.Format("{0}:{1}:{2}:{3}:{4}", credentials.UserName, Realm, credentials.Password, Nonce, ncvalue).CalculateMD5Hash();
  150. HA1 = this.HA1Sess;
  151. break;
  152. default: //throw new NotSupportedException("Not supported hash algorithm found in Web Authentication: " + Algorithm);
  153. return string.Empty;
  154. }
  155. // A string of 32 hex digits, which proves that the user knows a password. Set according to the qop value.
  156. string response = string.Empty;
  157. // The server sent QoP-value can be a list of supported methodes(if sent at all - in this case it's null).
  158. // The rfc is not specify that this is a space or comma separeted list. So it can be "auth, auth-int" or "auth auth-int".
  159. // We will first check the longer value("auth-int") then the short one ("auth"). If one matches we will reset the qop to the exact value.
  160. string qop = this.QualityOfProtections != null ? this.QualityOfProtections.TrimAndLower() : null;
  161. // When we authenticate with a proxy and we want to tunnel the request, we have to use the CONNECT method instead of the
  162. // request's, as the proxy will not know about the request itself.
  163. string method = isProxy ? "CONNECT" : request.MethodType.ToString().ToUpper();
  164. // When we authenticate with a proxy and we want to tunnel the request, the uri must match what we are sending in the CONNECT request's
  165. // Host header.
  166. string uri = isProxy ? request.CurrentUri.Host + ":" + request.CurrentUri.Port : request.CurrentUri.GetRequestPathAndQueryURL();
  167. if (qop == null)
  168. {
  169. string HA2 = string.Concat(request.MethodType.ToString().ToUpper(), ":", request.CurrentUri.GetRequestPathAndQueryURL()).CalculateMD5Hash();
  170. response = string.Format("{0}:{1}:{2}", HA1, Nonce, HA2).CalculateMD5Hash();
  171. }
  172. else if (qop.Contains("auth-int"))
  173. {
  174. qop = "auth-int";
  175. byte[] entityBody = request.GetEntityBody();
  176. if (entityBody == null)
  177. entityBody = string.Empty.GetASCIIBytes();
  178. string HA2 = string.Format("{0}:{1}:{2}", method, uri, entityBody.CalculateMD5Hash()).CalculateMD5Hash();
  179. response = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, Nonce, ncvalue, cnonce, qop, HA2).CalculateMD5Hash();
  180. }
  181. else if (qop.Contains("auth"))
  182. {
  183. qop = "auth";
  184. string HA2 = string.Concat(method, ":", uri).CalculateMD5Hash();
  185. response = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, Nonce, ncvalue, cnonce, qop, HA2).CalculateMD5Hash();
  186. }
  187. else //throw new NotSupportedException("Unrecognized Quality of Protection value found: " + this.QualityOfProtections);
  188. return string.Empty;
  189. string result = string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", cnonce=\"{4}\", response=\"{5}\"",
  190. credentials.UserName, Realm, Nonce, uri, cnonce, response);
  191. if (qop != null)
  192. result += String.Concat(", qop=\"", qop, "\", nc=", ncvalue);
  193. if (!string.IsNullOrEmpty(Opaque))
  194. result = String.Concat(result, ", opaque=\"", Opaque, "\"");
  195. return result;
  196. }// end of case "digest":
  197. default:
  198. break;
  199. }
  200. }
  201. catch
  202. {
  203. }
  204. return string.Empty;
  205. }
  206. public bool IsUriProtected(Uri uri)
  207. {
  208. // http://tools.ietf.org/html/rfc2617#section-3.2.1
  209. // An absoluteURI in this list may refer to
  210. // a different server than the one being accessed. The client can use
  211. // this list to determine the set of URIs for which the same
  212. // authentication information may be sent: any URI that has a URI in
  213. // this list as a prefix (after both have been made absolute) may be
  214. // assumed to be in the same protection space. If this directive is
  215. // omitted or its value is empty, the client should assume that the
  216. // protection space consists of all URIs on the responding server.
  217. if (string.CompareOrdinal(uri.Host, this.Uri.Host) != 0)
  218. return false;
  219. string uriStr = uri.ToString();
  220. if (ProtectedUris != null && ProtectedUris.Count > 0)
  221. for (int i = 0; i < ProtectedUris.Count; ++i)
  222. if (uriStr.Contains(ProtectedUris[i]))
  223. return true;
  224. return true;
  225. }
  226. }
  227. }