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 "nsNegotiateAuth.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 
00081 #define kNegotiateLen  (sizeof(kNegotiate)-1)
00082 
00083 //-----------------------------------------------------------------------------
00084 
00085 NS_IMETHODIMP
00086 nsHttpNegotiateAuth::GetAuthFlags(PRUint32 *flags)
00087 {
00088     //
00089     // Negotiate Auth creds should not be reused across multiple requests.
00090     // Only perform the negotiation when it is explicitly requested by the
00091     // server.  Thus, do *NOT* use the "REUSABLE_CREDENTIALS" flag here.
00092     //
00093     // CONNECTION_BASED is specified instead of REQUEST_BASED since we need
00094     // to complete a sequence of transactions with the server over the same
00095     // connection.
00096     //
00097     *flags = CONNECTION_BASED | IDENTITY_IGNORED; 
00098     return NS_OK;
00099 }
00100 
00101 //
00102 // Always set *identityInvalid == FALSE here.  This 
00103 // will prevent the browser from popping up the authentication
00104 // prompt window.  Because GSSAPI does not have an API
00105 // for fetching initial credentials (ex: A Kerberos TGT),
00106 // there is no correct way to get the users credentials.
00107 // 
00108 NS_IMETHODIMP
00109 nsHttpNegotiateAuth::ChallengeReceived(nsIHttpChannel *httpChannel,
00110                                        const char *challenge,
00111                                        PRBool isProxyAuth,
00112                                        nsISupports **sessionState,
00113                                        nsISupports **continuationState,
00114                                        PRBool *identityInvalid)
00115 {
00116     nsIAuthModule *module = (nsIAuthModule *) *continuationState;
00117 
00118     *identityInvalid = PR_FALSE;
00119     if (module)
00120         return NS_OK;
00121 
00122     nsresult rv;
00123 
00124     nsCOMPtr<nsIURI> uri;
00125     rv = httpChannel->GetURI(getter_AddRefs(uri));
00126     if (NS_FAILED(rv))
00127         return rv;
00128 
00129     PRUint32 req_flags = nsIAuthModule::REQ_DEFAULT;
00130     nsCAutoString service;
00131 
00132     if (isProxyAuth) {
00133         if (!TestBoolPref(kNegotiateAuthAllowProxies)) {
00134             LOG(("nsHttpNegotiateAuth::ChallengeReceived proxy auth blocked\n"));
00135             return NS_ERROR_ABORT;
00136         }
00137 
00138         nsCOMPtr<nsIHttpChannelInternal> httpInternal =
00139                 do_QueryInterface(httpChannel);
00140         NS_ENSURE_STATE(httpInternal);
00141 
00142         nsCOMPtr<nsIProxyInfo> proxyInfo;
00143         httpInternal->GetProxyInfo(getter_AddRefs(proxyInfo));
00144         NS_ENSURE_STATE(proxyInfo);
00145 
00146         proxyInfo->GetHost(service);
00147     }
00148     else {
00149         PRBool allowed = TestPref(uri, kNegotiateAuthTrustedURIs);
00150         if (!allowed) {
00151             LOG(("nsHttpNegotiateAuth::ChallengeReceived URI blocked\n"));
00152             return NS_ERROR_ABORT;
00153         }
00154 
00155         PRBool delegation = TestPref(uri, kNegotiateAuthDelegationURIs);
00156         if (delegation) {
00157             LOG(("  using REQ_DELEGATE\n"));
00158             req_flags |= nsIAuthModule::REQ_DELEGATE;
00159         }
00160 
00161         rv = uri->GetAsciiHost(service);
00162         if (NS_FAILED(rv))
00163             return rv;
00164     }
00165 
00166     LOG(("  service = %s\n", service.get()));
00167 
00168     //
00169     // The correct service name for IIS servers is "HTTP/f.q.d.n", so
00170     // construct the proper service name for passing to "gss_import_name".
00171     //
00172     // TODO: Possibly make this a configurable service name for use
00173     // with non-standard servers that use stuff like "khttp/f.q.d.n" 
00174     // instead.
00175     //
00176     service.Insert("HTTP@", 0);
00177 
00178     rv = CallCreateInstance(NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate", &module);
00179     if (NS_FAILED(rv))
00180         return rv;
00181 
00182     rv = module->Init(service.get(), req_flags, nsnull, nsnull, nsnull);
00183     if (NS_FAILED(rv)) {
00184         NS_RELEASE(module);
00185         return rv;
00186     }
00187 
00188     *continuationState = module;
00189     return NS_OK;
00190 }
00191 
00192 NS_IMPL_ISUPPORTS1(nsHttpNegotiateAuth, nsIHttpAuthenticator)
00193    
00194 //
00195 // GenerateCredentials
00196 //
00197 // This routine is responsible for creating the correct authentication
00198 // blob to pass to the server that requested "Negotiate" authentication.
00199 //
00200 NS_IMETHODIMP
00201 nsHttpNegotiateAuth::GenerateCredentials(nsIHttpChannel *httpChannel,
00202                                          const char *challenge,
00203                                          PRBool isProxyAuth,
00204                                          const PRUnichar *domain,
00205                                          const PRUnichar *username,
00206                                          const PRUnichar *password,
00207                                          nsISupports **sessionState,
00208                                          nsISupports **continuationState,
00209                                          char **creds)
00210 {
00211     // ChallengeReceived must have been called previously.
00212     nsIAuthModule *module = (nsIAuthModule *) *continuationState;
00213     NS_ENSURE_TRUE(module, NS_ERROR_NOT_INITIALIZED);
00214 
00215     LOG(("nsHttpNegotiateAuth::GenerateCredentials() [challenge=%s]\n", challenge));
00216 
00217     NS_ASSERTION(creds, "null param");
00218 
00219 #ifdef DEBUG
00220     PRBool isGssapiAuth =
00221         !PL_strncasecmp(challenge, kNegotiate, kNegotiateLen);
00222     NS_ASSERTION(isGssapiAuth, "Unexpected challenge");
00223 #endif
00224 
00225     //
00226     // If the "Negotiate:" header had some data associated with it,
00227     // that data should be used as the input to this call.  This may
00228     // be a continuation of an earlier call because GSSAPI authentication
00229     // often takes multiple round-trips to complete depending on the
00230     // context flags given.  We want to use MUTUAL_AUTHENTICATION which
00231     // generally *does* require multiple round-trips.  Don't assume
00232     // auth can be completed in just 1 call.
00233     //
00234     unsigned int len = strlen(challenge);
00235 
00236     void *inToken, *outToken;
00237     PRUint32 inTokenLen, outTokenLen;
00238 
00239     if (len > kNegotiateLen) {
00240         challenge += kNegotiateLen;
00241         while (*challenge == ' ')
00242             challenge++;
00243         len = strlen(challenge);
00244 
00245         inTokenLen = (len * 3)/4;
00246         inToken = malloc(inTokenLen);
00247         if (!inToken)
00248             return (NS_ERROR_OUT_OF_MEMORY);
00249 
00250         // strip off any padding (see bug 230351)
00251         while (challenge[len - 1] == '=')
00252             len--;
00253 
00254         //
00255         // Decode the response that followed the "Negotiate" token
00256         //
00257         if (PL_Base64Decode(challenge, len, (char *) inToken) == NULL) {
00258             free(inToken);
00259             return(NS_ERROR_UNEXPECTED);
00260         }
00261     }
00262     else {
00263         //
00264         // Initializing, don't use an input token.
00265         //
00266         inToken = nsnull;
00267         inTokenLen = 0;
00268     }
00269 
00270     nsresult rv = module->GetNextToken(inToken, inTokenLen, &outToken, &outTokenLen);
00271 
00272     free(inToken);
00273 
00274     if (NS_FAILED(rv))
00275         return rv;
00276 
00277     if (outTokenLen == 0) {
00278         LOG(("  No output token to send, exiting"));
00279         return NS_ERROR_FAILURE;
00280     }
00281 
00282     //
00283     // base64 encode the output token.
00284     //
00285     char *encoded_token = PL_Base64Encode((char *)outToken, outTokenLen, nsnull);
00286 
00287     nsMemory::Free(outToken);
00288 
00289     if (!encoded_token)
00290         return NS_ERROR_OUT_OF_MEMORY;
00291 
00292     LOG(("  Sending a token of length %d\n", outTokenLen));
00293 
00294     // allocate a buffer sizeof("Negotiate" + " " + b64output_token + "\0")
00295     *creds = (char *) nsMemory::Alloc(kNegotiateLen + 1 + strlen(encoded_token) + 1);
00296     if (NS_UNLIKELY(!*creds))
00297         rv = NS_ERROR_OUT_OF_MEMORY;
00298     else
00299         sprintf(*creds, "%s %s", kNegotiate, encoded_token);
00300 
00301     PR_Free(encoded_token);
00302     return rv;
00303 }
00304 
00305 PRBool
00306 nsHttpNegotiateAuth::TestBoolPref(const char *pref)
00307 {
00308     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
00309     if (!prefs)
00310         return PR_FALSE;
00311 
00312     PRBool val;
00313     nsresult rv = prefs->GetBoolPref(pref, &val);
00314     if (NS_FAILED(rv))
00315         return PR_FALSE;
00316 
00317     return val;
00318 }
00319 
00320 PRBool
00321 nsHttpNegotiateAuth::TestPref(nsIURI *uri, const char *pref)
00322 {
00323     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
00324     if (!prefs)
00325         return PR_FALSE;
00326 
00327     nsCAutoString scheme, host;
00328     PRInt32 port;
00329 
00330     if (NS_FAILED(uri->GetScheme(scheme)))
00331         return PR_FALSE;
00332     if (NS_FAILED(uri->GetAsciiHost(host)))
00333         return PR_FALSE;
00334     if (NS_FAILED(uri->GetPort(&port)))
00335         return PR_FALSE;
00336 
00337     char *hostList;
00338     if (NS_FAILED(prefs->GetCharPref(pref, &hostList)) || !hostList)
00339         return PR_FALSE;
00340 
00341     // pseudo-BNF
00342     // ----------
00343     //
00344     // url-list       base-url ( base-url "," LWS )*
00345     // base-url       ( scheme-part | host-part | scheme-part host-part )
00346     // scheme-part    scheme "://"
00347     // host-part      host [":" port]
00348     //
00349     // for example:
00350     //   "https://, http://office.foo.com"
00351     //
00352 
00353     char *start = hostList, *end;
00354     for (;;) {
00355         // skip past any whitespace
00356         while (*start == ' ' || *start == '\t')
00357             ++start;
00358         end = strchr(start, ',');
00359         if (!end)
00360             end = start + strlen(start);
00361         if (start == end)
00362             break;
00363         if (MatchesBaseURI(scheme, host, port, start, end))
00364             return PR_TRUE;
00365         if (*end == '\0')
00366             break;
00367         start = end + 1;
00368     }
00369     
00370     nsMemory::Free(hostList);
00371     return PR_FALSE;
00372 }
00373 
00374 PRBool
00375 nsHttpNegotiateAuth::MatchesBaseURI(const nsCSubstring &matchScheme,
00376                                     const nsCSubstring &matchHost,
00377                                     PRInt32             matchPort,
00378                                     const char         *baseStart,
00379                                     const char         *baseEnd)
00380 {
00381     // check if scheme://host:port matches baseURI
00382 
00383     // parse the base URI
00384     const char *hostStart, *schemeEnd = strstr(baseStart, "://");
00385     if (schemeEnd) {
00386         // the given scheme must match the parsed scheme exactly
00387         if (!matchScheme.Equals(Substring(baseStart, schemeEnd)))
00388             return PR_FALSE;
00389         hostStart = schemeEnd + 3;
00390     }
00391     else
00392         hostStart = baseStart;
00393 
00394     // XXX this does not work for IPv6-literals
00395     const char *hostEnd = strchr(hostStart, ':');
00396     if (hostEnd && hostEnd <= baseEnd) {
00397         // the given port must match the parsed port exactly
00398         int port = atoi(hostEnd + 1);
00399         if (matchPort != (PRInt32) port)
00400             return PR_FALSE;
00401     }
00402     else
00403         hostEnd = baseEnd;
00404 
00405 
00406     // if we didn't parse out a host, then assume we got a match.
00407     if (hostStart == hostEnd)
00408         return PR_TRUE;
00409 
00410     PRUint32 hostLen = hostEnd - hostStart;
00411 
00412     // matchHost must either equal host or be a subdomain of host
00413     if (matchHost.Length() < hostLen)
00414         return PR_FALSE;
00415 
00416     const char *end = matchHost.EndReading();
00417     if (PL_strncasecmp(end - hostLen, hostStart, hostLen) == 0) {
00418         // if matchHost ends with host from the base URI, then make sure it is
00419         // either an exact match, or prefixed with a dot.  we don't want
00420         // "foobar.com" to match "bar.com"
00421         if (matchHost.Length() == hostLen ||
00422             *(end - hostLen) == '.' ||
00423             *(end - hostLen - 1) == '.')
00424             return PR_TRUE;
00425     }
00426 
00427     return PR_FALSE;
00428 }