Bumping manifests a=b2g-bump
[gecko.git] / extensions / auth / nsHttpNegotiateAuth.cpp
blobdab22b93f5489718a8d946f59280e6e5d95a2a15
1 /* vim:set ts=4 sw=4 sts=4 et cindent: */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 //
7 // HTTP Negotiate Authentication Support Module
8 //
9 // Described by IETF Internet draft: draft-brezak-kerberos-http-00.txt
10 // (formerly draft-brezak-spnego-http-04.txt)
12 // Also described here:
13 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsecure/html/http-sso-1.asp
16 #include <string.h>
17 #include <stdlib.h>
19 #include "nsAuth.h"
20 #include "nsHttpNegotiateAuth.h"
22 #include "nsIHttpAuthenticableChannel.h"
23 #include "nsIProxiedChannel.h"
24 #include "nsIAuthModule.h"
25 #include "nsIServiceManager.h"
26 #include "nsIPrefService.h"
27 #include "nsIPrefBranch.h"
28 #include "nsIProxyInfo.h"
29 #include "nsIURI.h"
30 #include "nsCOMPtr.h"
31 #include "nsString.h"
32 #include "nsNetCID.h"
33 #include "plbase64.h"
34 #include "plstr.h"
35 #include "prprf.h"
36 #include "prlog.h"
37 #include "prmem.h"
38 #include "prnetdb.h"
39 #include "mozilla/Likely.h"
41 //-----------------------------------------------------------------------------
43 static const char kNegotiate[] = "Negotiate";
44 static const char kNegotiateAuthTrustedURIs[] = "network.negotiate-auth.trusted-uris";
45 static const char kNegotiateAuthDelegationURIs[] = "network.negotiate-auth.delegation-uris";
46 static const char kNegotiateAuthAllowProxies[] = "network.negotiate-auth.allow-proxies";
47 static const char kNegotiateAuthAllowNonFqdn[] = "network.negotiate-auth.allow-non-fqdn";
48 static const char kNegotiateAuthSSPI[] = "network.auth.use-sspi";
50 #define kNegotiateLen (sizeof(kNegotiate)-1)
52 //-----------------------------------------------------------------------------
54 NS_IMETHODIMP
55 nsHttpNegotiateAuth::GetAuthFlags(uint32_t *flags)
58 // Negotiate Auth creds should not be reused across multiple requests.
59 // Only perform the negotiation when it is explicitly requested by the
60 // server. Thus, do *NOT* use the "REUSABLE_CREDENTIALS" flag here.
62 // CONNECTION_BASED is specified instead of REQUEST_BASED since we need
63 // to complete a sequence of transactions with the server over the same
64 // connection.
66 *flags = CONNECTION_BASED | IDENTITY_IGNORED;
67 return NS_OK;
71 // Always set *identityInvalid == FALSE here. This
72 // will prevent the browser from popping up the authentication
73 // prompt window. Because GSSAPI does not have an API
74 // for fetching initial credentials (ex: A Kerberos TGT),
75 // there is no correct way to get the users credentials.
76 //
77 NS_IMETHODIMP
78 nsHttpNegotiateAuth::ChallengeReceived(nsIHttpAuthenticableChannel *authChannel,
79 const char *challenge,
80 bool isProxyAuth,
81 nsISupports **sessionState,
82 nsISupports **continuationState,
83 bool *identityInvalid)
85 nsIAuthModule *module = (nsIAuthModule *) *continuationState;
87 *identityInvalid = false;
88 if (module)
89 return NS_OK;
91 nsresult rv;
93 nsCOMPtr<nsIURI> uri;
94 rv = authChannel->GetURI(getter_AddRefs(uri));
95 if (NS_FAILED(rv))
96 return rv;
98 uint32_t req_flags = nsIAuthModule::REQ_DEFAULT;
99 nsAutoCString service;
101 if (isProxyAuth) {
102 if (!TestBoolPref(kNegotiateAuthAllowProxies)) {
103 LOG(("nsHttpNegotiateAuth::ChallengeReceived proxy auth blocked\n"));
104 return NS_ERROR_ABORT;
107 req_flags |= nsIAuthModule::REQ_PROXY_AUTH;
108 nsCOMPtr<nsIProxyInfo> proxyInfo;
109 authChannel->GetProxyInfo(getter_AddRefs(proxyInfo));
110 NS_ENSURE_STATE(proxyInfo);
112 proxyInfo->GetHost(service);
114 else {
115 bool allowed = TestNonFqdn(uri) ||
116 TestPref(uri, kNegotiateAuthTrustedURIs);
117 if (!allowed) {
118 LOG(("nsHttpNegotiateAuth::ChallengeReceived URI blocked\n"));
119 return NS_ERROR_ABORT;
122 bool delegation = TestPref(uri, kNegotiateAuthDelegationURIs);
123 if (delegation) {
124 LOG((" using REQ_DELEGATE\n"));
125 req_flags |= nsIAuthModule::REQ_DELEGATE;
128 rv = uri->GetAsciiHost(service);
129 if (NS_FAILED(rv))
130 return rv;
133 LOG((" service = %s\n", service.get()));
136 // The correct service name for IIS servers is "HTTP/f.q.d.n", so
137 // construct the proper service name for passing to "gss_import_name".
139 // TODO: Possibly make this a configurable service name for use
140 // with non-standard servers that use stuff like "khttp/f.q.d.n"
141 // instead.
143 service.Insert("HTTP@", 0);
145 const char *contractID;
146 if (TestBoolPref(kNegotiateAuthSSPI)) {
147 LOG((" using negotiate-sspi\n"));
148 contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-sspi";
150 else {
151 LOG((" using negotiate-gss\n"));
152 contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-gss";
155 rv = CallCreateInstance(contractID, &module);
157 if (NS_FAILED(rv)) {
158 LOG((" Failed to load Negotiate Module \n"));
159 return rv;
162 rv = module->Init(service.get(), req_flags, nullptr, nullptr, nullptr);
164 if (NS_FAILED(rv)) {
165 NS_RELEASE(module);
166 return rv;
169 *continuationState = module;
170 return NS_OK;
173 NS_IMPL_ISUPPORTS(nsHttpNegotiateAuth, nsIHttpAuthenticator)
176 // GenerateCredentials
178 // This routine is responsible for creating the correct authentication
179 // blob to pass to the server that requested "Negotiate" authentication.
181 NS_IMETHODIMP
182 nsHttpNegotiateAuth::GenerateCredentials(nsIHttpAuthenticableChannel *authChannel,
183 const char *challenge,
184 bool isProxyAuth,
185 const char16_t *domain,
186 const char16_t *username,
187 const char16_t *password,
188 nsISupports **sessionState,
189 nsISupports **continuationState,
190 uint32_t *flags,
191 char **creds)
193 // ChallengeReceived must have been called previously.
194 nsIAuthModule *module = (nsIAuthModule *) *continuationState;
195 NS_ENSURE_TRUE(module, NS_ERROR_NOT_INITIALIZED);
197 *flags = USING_INTERNAL_IDENTITY;
199 LOG(("nsHttpNegotiateAuth::GenerateCredentials() [challenge=%s]\n", challenge));
201 NS_ASSERTION(creds, "null param");
203 #ifdef DEBUG
204 bool isGssapiAuth =
205 !PL_strncasecmp(challenge, kNegotiate, kNegotiateLen);
206 NS_ASSERTION(isGssapiAuth, "Unexpected challenge");
207 #endif
210 // If the "Negotiate:" header had some data associated with it,
211 // that data should be used as the input to this call. This may
212 // be a continuation of an earlier call because GSSAPI authentication
213 // often takes multiple round-trips to complete depending on the
214 // context flags given. We want to use MUTUAL_AUTHENTICATION which
215 // generally *does* require multiple round-trips. Don't assume
216 // auth can be completed in just 1 call.
218 unsigned int len = strlen(challenge);
220 void *inToken, *outToken;
221 uint32_t inTokenLen, outTokenLen;
223 if (len > kNegotiateLen) {
224 challenge += kNegotiateLen;
225 while (*challenge == ' ')
226 challenge++;
227 len = strlen(challenge);
229 // strip off any padding (see bug 230351)
230 while (challenge[len - 1] == '=')
231 len--;
233 inTokenLen = (len * 3)/4;
234 inToken = malloc(inTokenLen);
235 if (!inToken)
236 return (NS_ERROR_OUT_OF_MEMORY);
239 // Decode the response that followed the "Negotiate" token
241 if (PL_Base64Decode(challenge, len, (char *) inToken) == nullptr) {
242 free(inToken);
243 return(NS_ERROR_UNEXPECTED);
246 else {
248 // Initializing, don't use an input token.
250 inToken = nullptr;
251 inTokenLen = 0;
254 nsresult rv = module->GetNextToken(inToken, inTokenLen, &outToken, &outTokenLen);
256 free(inToken);
258 if (NS_FAILED(rv))
259 return rv;
261 if (outTokenLen == 0) {
262 LOG((" No output token to send, exiting"));
263 return NS_ERROR_FAILURE;
267 // base64 encode the output token.
269 char *encoded_token = PL_Base64Encode((char *)outToken, outTokenLen, nullptr);
271 nsMemory::Free(outToken);
273 if (!encoded_token)
274 return NS_ERROR_OUT_OF_MEMORY;
276 LOG((" Sending a token of length %d\n", outTokenLen));
278 // allocate a buffer sizeof("Negotiate" + " " + b64output_token + "\0")
279 *creds = (char *) nsMemory::Alloc(kNegotiateLen + 1 + strlen(encoded_token) + 1);
280 if (MOZ_UNLIKELY(!*creds))
281 rv = NS_ERROR_OUT_OF_MEMORY;
282 else
283 sprintf(*creds, "%s %s", kNegotiate, encoded_token);
285 PR_Free(encoded_token);
286 return rv;
289 bool
290 nsHttpNegotiateAuth::TestBoolPref(const char *pref)
292 nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
293 if (!prefs)
294 return false;
296 bool val;
297 nsresult rv = prefs->GetBoolPref(pref, &val);
298 if (NS_FAILED(rv))
299 return false;
301 return val;
304 bool
305 nsHttpNegotiateAuth::TestNonFqdn(nsIURI *uri)
307 nsAutoCString host;
308 PRNetAddr addr;
310 if (!TestBoolPref(kNegotiateAuthAllowNonFqdn))
311 return false;
313 if (NS_FAILED(uri->GetAsciiHost(host)))
314 return false;
316 // return true if host does not contain a dot and is not an ip address
317 return !host.IsEmpty() && host.FindChar('.') == kNotFound &&
318 PR_StringToNetAddr(host.BeginReading(), &addr) != PR_SUCCESS;
321 bool
322 nsHttpNegotiateAuth::TestPref(nsIURI *uri, const char *pref)
324 nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
325 if (!prefs)
326 return false;
328 nsAutoCString scheme, host;
329 int32_t port;
331 if (NS_FAILED(uri->GetScheme(scheme)))
332 return false;
333 if (NS_FAILED(uri->GetAsciiHost(host)))
334 return false;
335 if (NS_FAILED(uri->GetPort(&port)))
336 return false;
338 char *hostList;
339 if (NS_FAILED(prefs->GetCharPref(pref, &hostList)) || !hostList)
340 return false;
342 // pseudo-BNF
343 // ----------
345 // url-list base-url ( base-url "," LWS )*
346 // base-url ( scheme-part | host-part | scheme-part host-part )
347 // scheme-part scheme "://"
348 // host-part host [":" port]
350 // for example:
351 // "https://, http://office.foo.com"
354 char *start = hostList, *end;
355 for (;;) {
356 // skip past any whitespace
357 while (*start == ' ' || *start == '\t')
358 ++start;
359 end = strchr(start, ',');
360 if (!end)
361 end = start + strlen(start);
362 if (start == end)
363 break;
364 if (MatchesBaseURI(scheme, host, port, start, end))
365 return true;
366 if (*end == '\0')
367 break;
368 start = end + 1;
371 nsMemory::Free(hostList);
372 return false;
375 bool
376 nsHttpNegotiateAuth::MatchesBaseURI(const nsCSubstring &matchScheme,
377 const nsCSubstring &matchHost,
378 int32_t matchPort,
379 const char *baseStart,
380 const char *baseEnd)
382 // check if scheme://host:port matches baseURI
384 // parse the base URI
385 const char *hostStart, *schemeEnd = strstr(baseStart, "://");
386 if (schemeEnd) {
387 // the given scheme must match the parsed scheme exactly
388 if (!matchScheme.Equals(Substring(baseStart, schemeEnd)))
389 return false;
390 hostStart = schemeEnd + 3;
392 else
393 hostStart = baseStart;
395 // XXX this does not work for IPv6-literals
396 const char *hostEnd = strchr(hostStart, ':');
397 if (hostEnd && hostEnd < baseEnd) {
398 // the given port must match the parsed port exactly
399 int port = atoi(hostEnd + 1);
400 if (matchPort != (int32_t) port)
401 return false;
403 else
404 hostEnd = baseEnd;
407 // if we didn't parse out a host, then assume we got a match.
408 if (hostStart == hostEnd)
409 return true;
411 uint32_t hostLen = hostEnd - hostStart;
413 // matchHost must either equal host or be a subdomain of host
414 if (matchHost.Length() < hostLen)
415 return false;
417 const char *end = matchHost.EndReading();
418 if (PL_strncasecmp(end - hostLen, hostStart, hostLen) == 0) {
419 // if matchHost ends with host from the base URI, then make sure it is
420 // either an exact match, or prefixed with a dot. we don't want
421 // "foobar.com" to match "bar.com"
422 if (matchHost.Length() == hostLen ||
423 *(end - hostLen) == '.' ||
424 *(end - hostLen - 1) == '.')
425 return true;
428 return false;