/extensions/auth/nsHttpNegotiateAuth.cpp

http://github.com/zpao/v8monkey · C++ · 442 lines · 251 code · 68 blank · 123 comment · 60 complexity · 5f69a96e7ccea8d7842947dcd9c68972 MD5 · raw file

  1. /* vim:set ts=4 sw=4 sts=4 et cindent: */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. * http://www.mozilla.org/MPL/
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. *
  15. * The Original Code is the Negotiateauth
  16. *
  17. * The Initial Developer of the Original Code is Daniel Kouril.
  18. * Portions created by the Initial Developer are Copyright (C) 2003
  19. * the Initial Developer. All Rights Reserved.
  20. *
  21. * Contributor(s):
  22. * Daniel Kouril <kouril@ics.muni.cz> (original author)
  23. * Wyllys Ingersoll <wyllys.ingersoll@sun.com>
  24. * Christopher Nebergall <cneberg@sandia.gov>
  25. * Darin Fisher <darin@meer.net>
  26. *
  27. * Alternatively, the contents of this file may be used under the terms of
  28. * either the GNU General Public License Version 2 or later (the "GPL"), or
  29. * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  30. * in which case the provisions of the GPL or the LGPL are applicable instead
  31. * of those above. If you wish to allow use of your version of this file only
  32. * under the terms of either the GPL or the LGPL, and not to allow others to
  33. * use your version of this file under the terms of the MPL, indicate your
  34. * decision by deleting the provisions above and replace them with the notice
  35. * and other provisions required by the GPL or the LGPL. If you do not delete
  36. * the provisions above, a recipient may use your version of this file under
  37. * the terms of any one of the MPL, the GPL or the LGPL.
  38. *
  39. * ***** END LICENSE BLOCK ***** */
  40. //
  41. // HTTP Negotiate Authentication Support Module
  42. //
  43. // Described by IETF Internet draft: draft-brezak-kerberos-http-00.txt
  44. // (formerly draft-brezak-spnego-http-04.txt)
  45. //
  46. // Also described here:
  47. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsecure/html/http-sso-1.asp
  48. //
  49. #include <string.h>
  50. #include <stdlib.h>
  51. #include "nsAuth.h"
  52. #include "nsHttpNegotiateAuth.h"
  53. #include "nsIHttpAuthenticableChannel.h"
  54. #include "nsIProxiedChannel.h"
  55. #include "nsIAuthModule.h"
  56. #include "nsIServiceManager.h"
  57. #include "nsIPrefService.h"
  58. #include "nsIPrefBranch.h"
  59. #include "nsIProxyInfo.h"
  60. #include "nsIURI.h"
  61. #include "nsCOMPtr.h"
  62. #include "nsString.h"
  63. #include "nsNetCID.h"
  64. #include "plbase64.h"
  65. #include "plstr.h"
  66. #include "prprf.h"
  67. #include "prlog.h"
  68. #include "prmem.h"
  69. //-----------------------------------------------------------------------------
  70. static const char kNegotiate[] = "Negotiate";
  71. static const char kNegotiateAuthTrustedURIs[] = "network.negotiate-auth.trusted-uris";
  72. static const char kNegotiateAuthDelegationURIs[] = "network.negotiate-auth.delegation-uris";
  73. static const char kNegotiateAuthAllowProxies[] = "network.negotiate-auth.allow-proxies";
  74. static const char kNegotiateAuthSSPI[] = "network.auth.use-sspi";
  75. #define kNegotiateLen (sizeof(kNegotiate)-1)
  76. //-----------------------------------------------------------------------------
  77. NS_IMETHODIMP
  78. nsHttpNegotiateAuth::GetAuthFlags(PRUint32 *flags)
  79. {
  80. //
  81. // Negotiate Auth creds should not be reused across multiple requests.
  82. // Only perform the negotiation when it is explicitly requested by the
  83. // server. Thus, do *NOT* use the "REUSABLE_CREDENTIALS" flag here.
  84. //
  85. // CONNECTION_BASED is specified instead of REQUEST_BASED since we need
  86. // to complete a sequence of transactions with the server over the same
  87. // connection.
  88. //
  89. *flags = CONNECTION_BASED | IDENTITY_IGNORED;
  90. return NS_OK;
  91. }
  92. //
  93. // Always set *identityInvalid == FALSE here. This
  94. // will prevent the browser from popping up the authentication
  95. // prompt window. Because GSSAPI does not have an API
  96. // for fetching initial credentials (ex: A Kerberos TGT),
  97. // there is no correct way to get the users credentials.
  98. //
  99. NS_IMETHODIMP
  100. nsHttpNegotiateAuth::ChallengeReceived(nsIHttpAuthenticableChannel *authChannel,
  101. const char *challenge,
  102. bool isProxyAuth,
  103. nsISupports **sessionState,
  104. nsISupports **continuationState,
  105. bool *identityInvalid)
  106. {
  107. nsIAuthModule *module = (nsIAuthModule *) *continuationState;
  108. *identityInvalid = false;
  109. if (module)
  110. return NS_OK;
  111. nsresult rv;
  112. nsCOMPtr<nsIURI> uri;
  113. rv = authChannel->GetURI(getter_AddRefs(uri));
  114. if (NS_FAILED(rv))
  115. return rv;
  116. PRUint32 req_flags = nsIAuthModule::REQ_DEFAULT;
  117. nsCAutoString service;
  118. if (isProxyAuth) {
  119. if (!TestBoolPref(kNegotiateAuthAllowProxies)) {
  120. LOG(("nsHttpNegotiateAuth::ChallengeReceived proxy auth blocked\n"));
  121. return NS_ERROR_ABORT;
  122. }
  123. nsCOMPtr<nsIProxyInfo> proxyInfo;
  124. authChannel->GetProxyInfo(getter_AddRefs(proxyInfo));
  125. NS_ENSURE_STATE(proxyInfo);
  126. proxyInfo->GetHost(service);
  127. }
  128. else {
  129. bool allowed = TestPref(uri, kNegotiateAuthTrustedURIs);
  130. if (!allowed) {
  131. LOG(("nsHttpNegotiateAuth::ChallengeReceived URI blocked\n"));
  132. return NS_ERROR_ABORT;
  133. }
  134. bool delegation = TestPref(uri, kNegotiateAuthDelegationURIs);
  135. if (delegation) {
  136. LOG((" using REQ_DELEGATE\n"));
  137. req_flags |= nsIAuthModule::REQ_DELEGATE;
  138. }
  139. rv = uri->GetAsciiHost(service);
  140. if (NS_FAILED(rv))
  141. return rv;
  142. }
  143. LOG((" service = %s\n", service.get()));
  144. //
  145. // The correct service name for IIS servers is "HTTP/f.q.d.n", so
  146. // construct the proper service name for passing to "gss_import_name".
  147. //
  148. // TODO: Possibly make this a configurable service name for use
  149. // with non-standard servers that use stuff like "khttp/f.q.d.n"
  150. // instead.
  151. //
  152. service.Insert("HTTP@", 0);
  153. const char *contractID;
  154. if (TestBoolPref(kNegotiateAuthSSPI)) {
  155. LOG((" using negotiate-sspi\n"));
  156. contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-sspi";
  157. }
  158. else {
  159. LOG((" using negotiate-gss\n"));
  160. contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-gss";
  161. }
  162. rv = CallCreateInstance(contractID, &module);
  163. if (NS_FAILED(rv)) {
  164. LOG((" Failed to load Negotiate Module \n"));
  165. return rv;
  166. }
  167. rv = module->Init(service.get(), req_flags, nsnull, nsnull, nsnull);
  168. if (NS_FAILED(rv)) {
  169. NS_RELEASE(module);
  170. return rv;
  171. }
  172. *continuationState = module;
  173. return NS_OK;
  174. }
  175. NS_IMPL_ISUPPORTS1(nsHttpNegotiateAuth, nsIHttpAuthenticator)
  176. //
  177. // GenerateCredentials
  178. //
  179. // This routine is responsible for creating the correct authentication
  180. // blob to pass to the server that requested "Negotiate" authentication.
  181. //
  182. NS_IMETHODIMP
  183. nsHttpNegotiateAuth::GenerateCredentials(nsIHttpAuthenticableChannel *authChannel,
  184. const char *challenge,
  185. bool isProxyAuth,
  186. const PRUnichar *domain,
  187. const PRUnichar *username,
  188. const PRUnichar *password,
  189. nsISupports **sessionState,
  190. nsISupports **continuationState,
  191. PRUint32 *flags,
  192. char **creds)
  193. {
  194. // ChallengeReceived must have been called previously.
  195. nsIAuthModule *module = (nsIAuthModule *) *continuationState;
  196. NS_ENSURE_TRUE(module, NS_ERROR_NOT_INITIALIZED);
  197. *flags = USING_INTERNAL_IDENTITY;
  198. LOG(("nsHttpNegotiateAuth::GenerateCredentials() [challenge=%s]\n", challenge));
  199. NS_ASSERTION(creds, "null param");
  200. #ifdef DEBUG
  201. bool isGssapiAuth =
  202. !PL_strncasecmp(challenge, kNegotiate, kNegotiateLen);
  203. NS_ASSERTION(isGssapiAuth, "Unexpected challenge");
  204. #endif
  205. //
  206. // If the "Negotiate:" header had some data associated with it,
  207. // that data should be used as the input to this call. This may
  208. // be a continuation of an earlier call because GSSAPI authentication
  209. // often takes multiple round-trips to complete depending on the
  210. // context flags given. We want to use MUTUAL_AUTHENTICATION which
  211. // generally *does* require multiple round-trips. Don't assume
  212. // auth can be completed in just 1 call.
  213. //
  214. unsigned int len = strlen(challenge);
  215. void *inToken, *outToken;
  216. PRUint32 inTokenLen, outTokenLen;
  217. if (len > kNegotiateLen) {
  218. challenge += kNegotiateLen;
  219. while (*challenge == ' ')
  220. challenge++;
  221. len = strlen(challenge);
  222. // strip off any padding (see bug 230351)
  223. while (challenge[len - 1] == '=')
  224. len--;
  225. inTokenLen = (len * 3)/4;
  226. inToken = malloc(inTokenLen);
  227. if (!inToken)
  228. return (NS_ERROR_OUT_OF_MEMORY);
  229. //
  230. // Decode the response that followed the "Negotiate" token
  231. //
  232. if (PL_Base64Decode(challenge, len, (char *) inToken) == NULL) {
  233. free(inToken);
  234. return(NS_ERROR_UNEXPECTED);
  235. }
  236. }
  237. else {
  238. //
  239. // Initializing, don't use an input token.
  240. //
  241. inToken = nsnull;
  242. inTokenLen = 0;
  243. }
  244. nsresult rv = module->GetNextToken(inToken, inTokenLen, &outToken, &outTokenLen);
  245. free(inToken);
  246. if (NS_FAILED(rv))
  247. return rv;
  248. if (outTokenLen == 0) {
  249. LOG((" No output token to send, exiting"));
  250. return NS_ERROR_FAILURE;
  251. }
  252. //
  253. // base64 encode the output token.
  254. //
  255. char *encoded_token = PL_Base64Encode((char *)outToken, outTokenLen, nsnull);
  256. nsMemory::Free(outToken);
  257. if (!encoded_token)
  258. return NS_ERROR_OUT_OF_MEMORY;
  259. LOG((" Sending a token of length %d\n", outTokenLen));
  260. // allocate a buffer sizeof("Negotiate" + " " + b64output_token + "\0")
  261. *creds = (char *) nsMemory::Alloc(kNegotiateLen + 1 + strlen(encoded_token) + 1);
  262. if (NS_UNLIKELY(!*creds))
  263. rv = NS_ERROR_OUT_OF_MEMORY;
  264. else
  265. sprintf(*creds, "%s %s", kNegotiate, encoded_token);
  266. PR_Free(encoded_token);
  267. return rv;
  268. }
  269. bool
  270. nsHttpNegotiateAuth::TestBoolPref(const char *pref)
  271. {
  272. nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  273. if (!prefs)
  274. return false;
  275. bool val;
  276. nsresult rv = prefs->GetBoolPref(pref, &val);
  277. if (NS_FAILED(rv))
  278. return false;
  279. return val;
  280. }
  281. bool
  282. nsHttpNegotiateAuth::TestPref(nsIURI *uri, const char *pref)
  283. {
  284. nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  285. if (!prefs)
  286. return false;
  287. nsCAutoString scheme, host;
  288. PRInt32 port;
  289. if (NS_FAILED(uri->GetScheme(scheme)))
  290. return false;
  291. if (NS_FAILED(uri->GetAsciiHost(host)))
  292. return false;
  293. if (NS_FAILED(uri->GetPort(&port)))
  294. return false;
  295. char *hostList;
  296. if (NS_FAILED(prefs->GetCharPref(pref, &hostList)) || !hostList)
  297. return false;
  298. // pseudo-BNF
  299. // ----------
  300. //
  301. // url-list base-url ( base-url "," LWS )*
  302. // base-url ( scheme-part | host-part | scheme-part host-part )
  303. // scheme-part scheme "://"
  304. // host-part host [":" port]
  305. //
  306. // for example:
  307. // "https://, http://office.foo.com"
  308. //
  309. char *start = hostList, *end;
  310. for (;;) {
  311. // skip past any whitespace
  312. while (*start == ' ' || *start == '\t')
  313. ++start;
  314. end = strchr(start, ',');
  315. if (!end)
  316. end = start + strlen(start);
  317. if (start == end)
  318. break;
  319. if (MatchesBaseURI(scheme, host, port, start, end))
  320. return true;
  321. if (*end == '\0')
  322. break;
  323. start = end + 1;
  324. }
  325. nsMemory::Free(hostList);
  326. return false;
  327. }
  328. bool
  329. nsHttpNegotiateAuth::MatchesBaseURI(const nsCSubstring &matchScheme,
  330. const nsCSubstring &matchHost,
  331. PRInt32 matchPort,
  332. const char *baseStart,
  333. const char *baseEnd)
  334. {
  335. // check if scheme://host:port matches baseURI
  336. // parse the base URI
  337. const char *hostStart, *schemeEnd = strstr(baseStart, "://");
  338. if (schemeEnd) {
  339. // the given scheme must match the parsed scheme exactly
  340. if (!matchScheme.Equals(Substring(baseStart, schemeEnd)))
  341. return false;
  342. hostStart = schemeEnd + 3;
  343. }
  344. else
  345. hostStart = baseStart;
  346. // XXX this does not work for IPv6-literals
  347. const char *hostEnd = strchr(hostStart, ':');
  348. if (hostEnd && hostEnd < baseEnd) {
  349. // the given port must match the parsed port exactly
  350. int port = atoi(hostEnd + 1);
  351. if (matchPort != (PRInt32) port)
  352. return false;
  353. }
  354. else
  355. hostEnd = baseEnd;
  356. // if we didn't parse out a host, then assume we got a match.
  357. if (hostStart == hostEnd)
  358. return true;
  359. PRUint32 hostLen = hostEnd - hostStart;
  360. // matchHost must either equal host or be a subdomain of host
  361. if (matchHost.Length() < hostLen)
  362. return false;
  363. const char *end = matchHost.EndReading();
  364. if (PL_strncasecmp(end - hostLen, hostStart, hostLen) == 0) {
  365. // if matchHost ends with host from the base URI, then make sure it is
  366. // either an exact match, or prefixed with a dot. we don't want
  367. // "foobar.com" to match "bar.com"
  368. if (matchHost.Length() == hostLen ||
  369. *(end - hostLen) == '.' ||
  370. *(end - hostLen - 1) == '.')
  371. return true;
  372. }
  373. return false;
  374. }