Back to index

lightning-sunbird  0.9+nobinonly
nsHttpNegotiateAuth.cpp
Go to the documentation of this file.
00001 /* vim:set ts=4 sw=4 sts=4 et cindent: */
00002 /* ***** BEGIN LICENSE BLOCK *****
00003  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00004  *
00005  * The contents of this file are subject to the Mozilla Public License Version
00006  * 1.1 (the "License"); you may not use this file except in compliance with
00007  * the License. You may obtain a copy of the License at
00008  * http://www.mozilla.org/MPL/
00009  *
00010  * Software distributed under the License is distributed on an "AS IS" basis,
00011  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00012  * for the specific language governing rights and limitations under the
00013  * License.
00014  *
00015  * The Original Code is the Negotiateauth
00016  *
00017  * The Initial Developer of the Original Code is Daniel Kouril.
00018  * Portions created by the Initial Developer are Copyright (C) 2003
00019  * the Initial Developer. All Rights Reserved.
00020  *
00021  * Contributor(s):
00022  *   Daniel Kouril <kouril@ics.muni.cz> (original author)
00023  *   Wyllys Ingersoll <wyllys.ingersoll@sun.com>
00024  *   Christopher Nebergall <cneberg@sandia.gov>
00025  *   Darin Fisher <darin@meer.net>
00026  *
00027  * Alternatively, the contents of this file may be used under the terms of
00028  * either the GNU General Public License Version 2 or later (the "GPL"), or
00029  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00030  * in which case the provisions of the GPL or the LGPL are applicable instead
00031  * of those above. If you wish to allow use of your version of this file only
00032  * under the terms of either the GPL or the LGPL, and not to allow others to
00033  * use your version of this file under the terms of the MPL, indicate your
00034  * decision by deleting the provisions above and replace them with the notice
00035  * and other provisions required by the GPL or the LGPL. If you do not delete
00036  * the provisions above, a recipient may use your version of this file under
00037  * the terms of any one of the MPL, the GPL or the LGPL.
00038  *
00039  * ***** END LICENSE BLOCK ***** */
00040 
00041 //
00042 // HTTP Negotiate Authentication Support Module
00043 //
00044 // Described by IETF Internet draft: draft-brezak-kerberos-http-00.txt
00045 // (formerly draft-brezak-spnego-http-04.txt)
00046 //
00047 // Also described here:
00048 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsecure/html/http-sso-1.asp
00049 //
00050 
00051 #include <string.h>
00052 #include <stdlib.h>
00053 
00054 #include "nsAuth.h"
00055 #include "nsHttpNegotiateAuth.h"
00056 
00057 #include "nsIHttpChannel.h"
00058 #include "nsIHttpChannelInternal.h"
00059 #include "nsIAuthModule.h"
00060 #include "nsIServiceManager.h"
00061 #include "nsIPrefService.h"
00062 #include "nsIPrefBranch.h"
00063 #include "nsIProxyInfo.h"
00064 #include "nsIURI.h"
00065 #include "nsCOMPtr.h"
00066 #include "nsString.h"
00067 #include "nsNetCID.h"
00068 #include "plbase64.h"
00069 #include "plstr.h"
00070 #include "prprf.h"
00071 #include "prlog.h"
00072 #include "prmem.h"
00073 
00074 //-----------------------------------------------------------------------------
00075 
00076 static const char kNegotiate[] = "Negotiate";
00077 static const char kNegotiateAuthTrustedURIs[] = "network.negotiate-auth.trusted-uris";
00078 static const char kNegotiateAuthDelegationURIs[] = "network.negotiate-auth.delegation-uris";
00079 static const char kNegotiateAuthAllowProxies[] = "network.negotiate-auth.allow-proxies";
00080 static const char kNegotiateAuthSSPI[] = "network.auth.use-sspi";
00081 
00082 #define kNegotiateLen  (sizeof(kNegotiate)-1)
00083 
00084 //-----------------------------------------------------------------------------
00085 
00086 NS_IMETHODIMP
00087 nsHttpNegotiateAuth::GetAuthFlags(PRUint32 *flags)
00088 {
00089     //
00090     // Negotiate Auth creds should not be reused across multiple requests.
00091     // Only perform the negotiation when it is explicitly requested by the
00092     // server.  Thus, do *NOT* use the "REUSABLE_CREDENTIALS" flag here.
00093     //
00094     // CONNECTION_BASED is specified instead of REQUEST_BASED since we need
00095     // to complete a sequence of transactions with the server over the same
00096     // connection.
00097     //
00098     *flags = CONNECTION_BASED | IDENTITY_IGNORED; 
00099     return NS_OK;
00100 }
00101 
00102 //
00103 // Always set *identityInvalid == FALSE here.  This 
00104 // will prevent the browser from popping up the authentication
00105 // prompt window.  Because GSSAPI does not have an API
00106 // for fetching initial credentials (ex: A Kerberos TGT),
00107 // there is no correct way to get the users credentials.
00108 // 
00109 NS_IMETHODIMP
00110 nsHttpNegotiateAuth::ChallengeReceived(nsIHttpChannel *httpChannel,
00111                                        const char *challenge,
00112                                        PRBool isProxyAuth,
00113                                        nsISupports **sessionState,
00114                                        nsISupports **continuationState,
00115                                        PRBool *identityInvalid)
00116 {
00117     nsIAuthModule *module = (nsIAuthModule *) *continuationState;
00118 
00119     *identityInvalid = PR_FALSE;
00120     if (module)
00121         return NS_OK;
00122 
00123     nsresult rv;
00124 
00125     nsCOMPtr<nsIURI> uri;
00126     rv = httpChannel->GetURI(getter_AddRefs(uri));
00127     if (NS_FAILED(rv))
00128         return rv;
00129 
00130     PRUint32 req_flags = nsIAuthModule::REQ_DEFAULT;
00131     nsCAutoString service;
00132 
00133     if (isProxyAuth) {
00134         if (!TestBoolPref(kNegotiateAuthAllowProxies)) {
00135             LOG(("nsHttpNegotiateAuth::ChallengeReceived proxy auth blocked\n"));
00136             return NS_ERROR_ABORT;
00137         }
00138 
00139         nsCOMPtr<nsIHttpChannelInternal> httpInternal =
00140                 do_QueryInterface(httpChannel);
00141         NS_ENSURE_STATE(httpInternal);
00142 
00143         nsCOMPtr<nsIProxyInfo> proxyInfo;
00144         httpInternal->GetProxyInfo(getter_AddRefs(proxyInfo));
00145         NS_ENSURE_STATE(proxyInfo);
00146 
00147         proxyInfo->GetHost(service);
00148     }
00149     else {
00150         PRBool allowed = TestPref(uri, kNegotiateAuthTrustedURIs);
00151         if (!allowed) {
00152             LOG(("nsHttpNegotiateAuth::ChallengeReceived URI blocked\n"));
00153             return NS_ERROR_ABORT;
00154         }
00155 
00156         PRBool delegation = TestPref(uri, kNegotiateAuthDelegationURIs);
00157         if (delegation) {
00158             LOG(("  using REQ_DELEGATE\n"));
00159             req_flags |= nsIAuthModule::REQ_DELEGATE;
00160         }
00161 
00162         rv = uri->GetAsciiHost(service);
00163         if (NS_FAILED(rv))
00164             return rv;
00165     }
00166 
00167     LOG(("  service = %s\n", service.get()));
00168 
00169     //
00170     // The correct service name for IIS servers is "HTTP/f.q.d.n", so
00171     // construct the proper service name for passing to "gss_import_name".
00172     //
00173     // TODO: Possibly make this a configurable service name for use
00174     // with non-standard servers that use stuff like "khttp/f.q.d.n" 
00175     // instead.
00176     //
00177     service.Insert("HTTP@", 0);
00178 
00179     const char *contractID;
00180     if (TestBoolPref(kNegotiateAuthSSPI)) {
00181           LOG(("  using negotiate-sspi\n"));
00182           contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-sspi";
00183     }
00184     else {
00185           LOG(("  using negotiate-gss\n"));
00186           contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-gss";
00187     }
00188 
00189     rv = CallCreateInstance(contractID, &module);
00190 
00191     if (NS_FAILED(rv)) {
00192         LOG(("  Failed to load Negotiate Module \n"));
00193         return rv;
00194     }
00195 
00196     rv = module->Init(service.get(), req_flags, nsnull, nsnull, nsnull);
00197 
00198     if (NS_FAILED(rv)) {
00199         NS_RELEASE(module);
00200         return rv;
00201     }
00202 
00203     *continuationState = module;
00204     return NS_OK;
00205 }
00206 
00207 NS_IMPL_ISUPPORTS1(nsHttpNegotiateAuth, nsIHttpAuthenticator)
00208    
00209 //
00210 // GenerateCredentials
00211 //
00212 // This routine is responsible for creating the correct authentication
00213 // blob to pass to the server that requested "Negotiate" authentication.
00214 //
00215 NS_IMETHODIMP
00216 nsHttpNegotiateAuth::GenerateCredentials(nsIHttpChannel *httpChannel,
00217                                          const char *challenge,
00218                                          PRBool isProxyAuth,
00219                                          const PRUnichar *domain,
00220                                          const PRUnichar *username,
00221                                          const PRUnichar *password,
00222                                          nsISupports **sessionState,
00223                                          nsISupports **continuationState,
00224                                          char **creds)
00225 {
00226     // ChallengeReceived must have been called previously.
00227     nsIAuthModule *module = (nsIAuthModule *) *continuationState;
00228     NS_ENSURE_TRUE(module, NS_ERROR_NOT_INITIALIZED);
00229 
00230     LOG(("nsHttpNegotiateAuth::GenerateCredentials() [challenge=%s]\n", challenge));
00231 
00232     NS_ASSERTION(creds, "null param");
00233 
00234 #ifdef DEBUG
00235     PRBool isGssapiAuth =
00236         !PL_strncasecmp(challenge, kNegotiate, kNegotiateLen);
00237     NS_ASSERTION(isGssapiAuth, "Unexpected challenge");
00238 #endif
00239 
00240     //
00241     // If the "Negotiate:" header had some data associated with it,
00242     // that data should be used as the input to this call.  This may
00243     // be a continuation of an earlier call because GSSAPI authentication
00244     // often takes multiple round-trips to complete depending on the
00245     // context flags given.  We want to use MUTUAL_AUTHENTICATION which
00246     // generally *does* require multiple round-trips.  Don't assume
00247     // auth can be completed in just 1 call.
00248     //
00249     unsigned int len = strlen(challenge);
00250 
00251     void *inToken, *outToken;
00252     PRUint32 inTokenLen, outTokenLen;
00253 
00254     if (len > kNegotiateLen) {
00255         challenge += kNegotiateLen;
00256         while (*challenge == ' ')
00257             challenge++;
00258         len = strlen(challenge);
00259 
00260         inTokenLen = (len * 3)/4;
00261         inToken = malloc(inTokenLen);
00262         if (!inToken)
00263             return (NS_ERROR_OUT_OF_MEMORY);
00264 
00265         // strip off any padding (see bug 230351)
00266         while (challenge[len - 1] == '=')
00267             len--;
00268 
00269         //
00270         // Decode the response that followed the "Negotiate" token
00271         //
00272         if (PL_Base64Decode(challenge, len, (char *) inToken) == NULL) {
00273             free(inToken);
00274             return(NS_ERROR_UNEXPECTED);
00275         }
00276     }
00277     else {
00278         //
00279         // Initializing, don't use an input token.
00280         //
00281         inToken = nsnull;
00282         inTokenLen = 0;
00283     }
00284 
00285     nsresult rv = module->GetNextToken(inToken, inTokenLen, &outToken, &outTokenLen);
00286 
00287     free(inToken);
00288 
00289     if (NS_FAILED(rv))
00290         return rv;
00291 
00292     if (outTokenLen == 0) {
00293         LOG(("  No output token to send, exiting"));
00294         return NS_ERROR_FAILURE;
00295     }
00296 
00297     //
00298     // base64 encode the output token.
00299     //
00300     char *encoded_token = PL_Base64Encode((char *)outToken, outTokenLen, nsnull);
00301 
00302     nsMemory::Free(outToken);
00303 
00304     if (!encoded_token)
00305         return NS_ERROR_OUT_OF_MEMORY;
00306 
00307     LOG(("  Sending a token of length %d\n", outTokenLen));
00308 
00309     // allocate a buffer sizeof("Negotiate" + " " + b64output_token + "\0")
00310     *creds = (char *) nsMemory::Alloc(kNegotiateLen + 1 + strlen(encoded_token) + 1);
00311     if (NS_UNLIKELY(!*creds))
00312         rv = NS_ERROR_OUT_OF_MEMORY;
00313     else
00314         sprintf(*creds, "%s %s", kNegotiate, encoded_token);
00315 
00316     PR_Free(encoded_token);
00317     return rv;
00318 }
00319 
00320 PRBool
00321 nsHttpNegotiateAuth::TestBoolPref(const char *pref)
00322 {
00323     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
00324     if (!prefs)
00325         return PR_FALSE;
00326 
00327     PRBool val;
00328     nsresult rv = prefs->GetBoolPref(pref, &val);
00329     if (NS_FAILED(rv))
00330         return PR_FALSE;
00331 
00332     return val;
00333 }
00334 
00335 PRBool
00336 nsHttpNegotiateAuth::TestPref(nsIURI *uri, const char *pref)
00337 {
00338     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
00339     if (!prefs)
00340         return PR_FALSE;
00341 
00342     nsCAutoString scheme, host;
00343     PRInt32 port;
00344 
00345     if (NS_FAILED(uri->GetScheme(scheme)))
00346         return PR_FALSE;
00347     if (NS_FAILED(uri->GetAsciiHost(host)))
00348         return PR_FALSE;
00349     if (NS_FAILED(uri->GetPort(&port)))
00350         return PR_FALSE;
00351 
00352     char *hostList;
00353     if (NS_FAILED(prefs->GetCharPref(pref, &hostList)) || !hostList)
00354         return PR_FALSE;
00355 
00356     // pseudo-BNF
00357     // ----------
00358     //
00359     // url-list       base-url ( base-url "," LWS )*
00360     // base-url       ( scheme-part | host-part | scheme-part host-part )
00361     // scheme-part    scheme "://"
00362     // host-part      host [":" port]
00363     //
00364     // for example:
00365     //   "https://, http://office.foo.com"
00366     //
00367 
00368     char *start = hostList, *end;
00369     for (;;) {
00370         // skip past any whitespace
00371         while (*start == ' ' || *start == '\t')
00372             ++start;
00373         end = strchr(start, ',');
00374         if (!end)
00375             end = start + strlen(start);
00376         if (start == end)
00377             break;
00378         if (MatchesBaseURI(scheme, host, port, start, end))
00379             return PR_TRUE;
00380         if (*end == '\0')
00381             break;
00382         start = end + 1;
00383     }
00384     
00385     nsMemory::Free(hostList);
00386     return PR_FALSE;
00387 }
00388 
00389 PRBool
00390 nsHttpNegotiateAuth::MatchesBaseURI(const nsCSubstring &matchScheme,
00391                                     const nsCSubstring &matchHost,
00392                                     PRInt32             matchPort,
00393                                     const char         *baseStart,
00394                                     const char         *baseEnd)
00395 {
00396     // check if scheme://host:port matches baseURI
00397 
00398     // parse the base URI
00399     const char *hostStart, *schemeEnd = strstr(baseStart, "://");
00400     if (schemeEnd) {
00401         // the given scheme must match the parsed scheme exactly
00402         if (!matchScheme.Equals(Substring(baseStart, schemeEnd)))
00403             return PR_FALSE;
00404         hostStart = schemeEnd + 3;
00405     }
00406     else
00407         hostStart = baseStart;
00408 
00409     // XXX this does not work for IPv6-literals
00410     const char *hostEnd = strchr(hostStart, ':');
00411     if (hostEnd && hostEnd <= baseEnd) {
00412         // the given port must match the parsed port exactly
00413         int port = atoi(hostEnd + 1);
00414         if (matchPort != (PRInt32) port)
00415             return PR_FALSE;
00416     }
00417     else
00418         hostEnd = baseEnd;
00419 
00420 
00421     // if we didn't parse out a host, then assume we got a match.
00422     if (hostStart == hostEnd)
00423         return PR_TRUE;
00424 
00425     PRUint32 hostLen = hostEnd - hostStart;
00426 
00427     // matchHost must either equal host or be a subdomain of host
00428     if (matchHost.Length() < hostLen)
00429         return PR_FALSE;
00430 
00431     const char *end = matchHost.EndReading();
00432     if (PL_strncasecmp(end - hostLen, hostStart, hostLen) == 0) {
00433         // if matchHost ends with host from the base URI, then make sure it is
00434         // either an exact match, or prefixed with a dot.  we don't want
00435         // "foobar.com" to match "bar.com"
00436         if (matchHost.Length() == hostLen ||
00437             *(end - hostLen) == '.' ||
00438             *(end - hostLen - 1) == '.')
00439             return PR_TRUE;
00440     }
00441 
00442     return PR_FALSE;
00443 }