nsHttpNegotiateAuth.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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/. */
  5. //
  6. // HTTP Negotiate Authentication Support Module
  7. //
  8. // Described by IETF Internet draft: draft-brezak-kerberos-http-00.txt
  9. // (formerly draft-brezak-spnego-http-04.txt)
  10. //
  11. // Also described here:
  12. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsecure/html/http-sso-1.asp
  13. //
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include "nsAuth.h"
  17. #include "nsHttpNegotiateAuth.h"
  18. #include "nsIHttpAuthenticableChannel.h"
  19. #include "nsIProxiedChannel.h"
  20. #include "nsIAuthModule.h"
  21. #include "nsIServiceManager.h"
  22. #include "nsIPrefService.h"
  23. #include "nsIPrefBranch.h"
  24. #include "nsIProxyInfo.h"
  25. #include "nsIURI.h"
  26. #include "nsCOMPtr.h"
  27. #include "nsString.h"
  28. #include "nsNetCID.h"
  29. #include "plbase64.h"
  30. #include "plstr.h"
  31. #include "mozilla/Base64.h"
  32. #include "prprf.h"
  33. #include "mozilla/Logging.h"
  34. #include "prmem.h"
  35. #include "prnetdb.h"
  36. #include "mozilla/Likely.h"
  37. #include "mozilla/Sprintf.h"
  38. #include "nsIChannel.h"
  39. #include "nsNetUtil.h"
  40. #include "nsThreadUtils.h"
  41. #include "nsIHttpAuthenticatorCallback.h"
  42. #include "mozilla/Mutex.h"
  43. #include "nsICancelable.h"
  44. using mozilla::Base64Decode;
  45. //-----------------------------------------------------------------------------
  46. static const char kNegotiate[] = "Negotiate";
  47. static const char kNegotiateAuthTrustedURIs[] = "network.negotiate-auth.trusted-uris";
  48. static const char kNegotiateAuthDelegationURIs[] = "network.negotiate-auth.delegation-uris";
  49. static const char kNegotiateAuthAllowProxies[] = "network.negotiate-auth.allow-proxies";
  50. static const char kNegotiateAuthAllowNonFqdn[] = "network.negotiate-auth.allow-non-fqdn";
  51. static const char kNegotiateAuthSSPI[] = "network.auth.use-sspi";
  52. static const char kSSOinPBmode[] = "network.auth.private-browsing-sso";
  53. #define kNegotiateLen (sizeof(kNegotiate)-1)
  54. #define DEFAULT_THREAD_TIMEOUT_MS 30000
  55. //-----------------------------------------------------------------------------
  56. // Return false when the channel comes from a Private browsing window.
  57. static bool
  58. TestNotInPBMode(nsIHttpAuthenticableChannel *authChannel, bool proxyAuth)
  59. {
  60. // Proxy should go all the time, it's not considered a privacy leak
  61. // to send default credentials to a proxy.
  62. if (proxyAuth) {
  63. return true;
  64. }
  65. nsCOMPtr<nsIChannel> bareChannel = do_QueryInterface(authChannel);
  66. MOZ_ASSERT(bareChannel);
  67. if (!NS_UsePrivateBrowsing(bareChannel)) {
  68. return true;
  69. }
  70. nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  71. if (prefs) {
  72. bool ssoInPb;
  73. if (NS_SUCCEEDED(prefs->GetBoolPref(kSSOinPBmode, &ssoInPb)) && ssoInPb) {
  74. return true;
  75. }
  76. // When the "Never remember history" option is set, all channels are
  77. // set PB mode flag, but here we want to make an exception, users
  78. // want their credentials go out.
  79. bool dontRememberHistory;
  80. if (NS_SUCCEEDED(prefs->GetBoolPref("browser.privatebrowsing.autostart",
  81. &dontRememberHistory)) &&
  82. dontRememberHistory) {
  83. return true;
  84. }
  85. }
  86. return false;
  87. }
  88. NS_IMETHODIMP
  89. nsHttpNegotiateAuth::GetAuthFlags(uint32_t *flags)
  90. {
  91. //
  92. // Negotiate Auth creds should not be reused across multiple requests.
  93. // Only perform the negotiation when it is explicitly requested by the
  94. // server. Thus, do *NOT* use the "REUSABLE_CREDENTIALS" flag here.
  95. //
  96. // CONNECTION_BASED is specified instead of REQUEST_BASED since we need
  97. // to complete a sequence of transactions with the server over the same
  98. // connection.
  99. //
  100. *flags = CONNECTION_BASED | IDENTITY_IGNORED;
  101. return NS_OK;
  102. }
  103. //
  104. // Always set *identityInvalid == FALSE here. This
  105. // will prevent the browser from popping up the authentication
  106. // prompt window. Because GSSAPI does not have an API
  107. // for fetching initial credentials (ex: A Kerberos TGT),
  108. // there is no correct way to get the users credentials.
  109. //
  110. NS_IMETHODIMP
  111. nsHttpNegotiateAuth::ChallengeReceived(nsIHttpAuthenticableChannel *authChannel,
  112. const char *challenge,
  113. bool isProxyAuth,
  114. nsISupports **sessionState,
  115. nsISupports **continuationState,
  116. bool *identityInvalid)
  117. {
  118. nsIAuthModule *module = (nsIAuthModule *) *continuationState;
  119. *identityInvalid = false;
  120. if (module)
  121. return NS_OK;
  122. nsresult rv;
  123. nsCOMPtr<nsIURI> uri;
  124. rv = authChannel->GetURI(getter_AddRefs(uri));
  125. if (NS_FAILED(rv))
  126. return rv;
  127. uint32_t req_flags = nsIAuthModule::REQ_DEFAULT;
  128. nsAutoCString service;
  129. if (isProxyAuth) {
  130. if (!TestBoolPref(kNegotiateAuthAllowProxies)) {
  131. LOG(("nsHttpNegotiateAuth::ChallengeReceived proxy auth blocked\n"));
  132. return NS_ERROR_ABORT;
  133. }
  134. req_flags |= nsIAuthModule::REQ_PROXY_AUTH;
  135. nsCOMPtr<nsIProxyInfo> proxyInfo;
  136. authChannel->GetProxyInfo(getter_AddRefs(proxyInfo));
  137. NS_ENSURE_STATE(proxyInfo);
  138. proxyInfo->GetHost(service);
  139. }
  140. else {
  141. bool allowed = TestNotInPBMode(authChannel, isProxyAuth) &&
  142. (TestNonFqdn(uri) ||
  143. TestPref(uri, kNegotiateAuthTrustedURIs));
  144. if (!allowed) {
  145. LOG(("nsHttpNegotiateAuth::ChallengeReceived URI blocked\n"));
  146. return NS_ERROR_ABORT;
  147. }
  148. bool delegation = TestPref(uri, kNegotiateAuthDelegationURIs);
  149. if (delegation) {
  150. LOG((" using REQ_DELEGATE\n"));
  151. req_flags |= nsIAuthModule::REQ_DELEGATE;
  152. }
  153. rv = uri->GetAsciiHost(service);
  154. if (NS_FAILED(rv))
  155. return rv;
  156. }
  157. LOG((" service = %s\n", service.get()));
  158. //
  159. // The correct service name for IIS servers is "HTTP/f.q.d.n", so
  160. // construct the proper service name for passing to "gss_import_name".
  161. //
  162. // TODO: Possibly make this a configurable service name for use
  163. // with non-standard servers that use stuff like "khttp/f.q.d.n"
  164. // instead.
  165. //
  166. service.Insert("HTTP@", 0);
  167. const char *contractID;
  168. if (TestBoolPref(kNegotiateAuthSSPI)) {
  169. LOG((" using negotiate-sspi\n"));
  170. contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-sspi";
  171. }
  172. else {
  173. LOG((" using negotiate-gss\n"));
  174. contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-gss";
  175. }
  176. rv = CallCreateInstance(contractID, &module);
  177. if (NS_FAILED(rv)) {
  178. LOG((" Failed to load Negotiate Module \n"));
  179. return rv;
  180. }
  181. rv = module->Init(service.get(), req_flags, nullptr, nullptr, nullptr);
  182. if (NS_FAILED(rv)) {
  183. NS_RELEASE(module);
  184. return rv;
  185. }
  186. *continuationState = module;
  187. return NS_OK;
  188. }
  189. NS_IMPL_ISUPPORTS(nsHttpNegotiateAuth, nsIHttpAuthenticator)
  190. namespace {
  191. //
  192. // GetNextTokenCompleteEvent
  193. //
  194. // This event is fired on main thread when async call of
  195. // nsHttpNegotiateAuth::GenerateCredentials is finished. During the Run()
  196. // method the nsIHttpAuthenticatorCallback::OnCredsAvailable is called with
  197. // obtained credentials, flags and NS_OK when successful, otherwise
  198. // NS_ERROR_FAILURE is returned as a result of failed operation.
  199. //
  200. class GetNextTokenCompleteEvent final : public nsIRunnable,
  201. public nsICancelable
  202. {
  203. virtual ~GetNextTokenCompleteEvent()
  204. {
  205. if (mCreds) {
  206. free(mCreds);
  207. }
  208. };
  209. public:
  210. NS_DECL_THREADSAFE_ISUPPORTS
  211. explicit GetNextTokenCompleteEvent(nsIHttpAuthenticatorCallback* aCallback)
  212. : mCallback(aCallback)
  213. , mCreds(nullptr)
  214. , mCancelled(false)
  215. {
  216. }
  217. NS_IMETHODIMP DispatchSuccess(char *aCreds,
  218. uint32_t aFlags,
  219. already_AddRefed<nsISupports> aSessionState,
  220. already_AddRefed<nsISupports> aContinuationState)
  221. {
  222. // Called from worker thread
  223. MOZ_ASSERT(!NS_IsMainThread());
  224. mCreds = aCreds;
  225. mFlags = aFlags;
  226. mResult = NS_OK;
  227. mSessionState = aSessionState;
  228. mContinuationState = aContinuationState;
  229. return NS_DispatchToMainThread(this, NS_DISPATCH_NORMAL);
  230. }
  231. NS_IMETHODIMP DispatchError(already_AddRefed<nsISupports> aSessionState,
  232. already_AddRefed<nsISupports> aContinuationState)
  233. {
  234. // Called from worker thread
  235. MOZ_ASSERT(!NS_IsMainThread());
  236. mResult = NS_ERROR_FAILURE;
  237. mSessionState = aSessionState;
  238. mContinuationState = aContinuationState;
  239. return NS_DispatchToMainThread(this, NS_DISPATCH_NORMAL);
  240. }
  241. NS_IMETHODIMP Run() override
  242. {
  243. // Runs on main thread
  244. MOZ_ASSERT(NS_IsMainThread());
  245. if (!mCancelled) {
  246. nsCOMPtr<nsIHttpAuthenticatorCallback> callback;
  247. callback.swap(mCallback);
  248. callback->OnCredsGenerated(mCreds, mFlags, mResult, mSessionState, mContinuationState);
  249. }
  250. return NS_OK;
  251. }
  252. NS_IMETHODIMP Cancel(nsresult aReason) override
  253. {
  254. // Supposed to be called from main thread
  255. MOZ_ASSERT(NS_IsMainThread());
  256. mCancelled = true;
  257. return NS_OK;
  258. }
  259. private:
  260. nsCOMPtr<nsIHttpAuthenticatorCallback> mCallback;
  261. char *mCreds; // This class owns it, freed in destructor
  262. uint32_t mFlags;
  263. nsresult mResult;
  264. bool mCancelled;
  265. nsCOMPtr<nsISupports> mSessionState;
  266. nsCOMPtr<nsISupports> mContinuationState;
  267. };
  268. NS_IMPL_ISUPPORTS(GetNextTokenCompleteEvent, nsIRunnable, nsICancelable)
  269. //
  270. // GetNextTokenRunnable
  271. //
  272. // This runnable is created by GenerateCredentialsAsync and it runs
  273. // in nsHttpNegotiateAuth::mNegotiateThread and calling GenerateCredentials.
  274. //
  275. class GetNextTokenRunnable final : public mozilla::Runnable
  276. {
  277. virtual ~GetNextTokenRunnable() {}
  278. public:
  279. GetNextTokenRunnable(nsIHttpAuthenticableChannel *authChannel,
  280. const char *challenge,
  281. bool isProxyAuth,
  282. const char16_t *domain,
  283. const char16_t *username,
  284. const char16_t *password,
  285. nsISupports *sessionState,
  286. nsISupports *continuationState,
  287. GetNextTokenCompleteEvent *aCompleteEvent
  288. )
  289. : mAuthChannel(authChannel)
  290. , mChallenge(challenge)
  291. , mIsProxyAuth(isProxyAuth)
  292. , mDomain(domain)
  293. , mUsername(username)
  294. , mPassword(password)
  295. , mSessionState(sessionState)
  296. , mContinuationState(continuationState)
  297. , mCompleteEvent(aCompleteEvent)
  298. {
  299. }
  300. NS_IMETHODIMP Run() override
  301. {
  302. // Runs on worker thread
  303. MOZ_ASSERT(!NS_IsMainThread());
  304. char *creds;
  305. uint32_t flags;
  306. nsresult rv = ObtainCredentialsAndFlags(&creds, &flags);
  307. // Passing session and continuation state this way to not touch
  308. // referencing of the object that may not be thread safe.
  309. // Not having a thread safe referencing doesn't mean the object
  310. // cannot be used on multiple threads (one example is nsAuthSSPI.)
  311. // This ensures state objects will be destroyed on the main thread
  312. // when not changed by GenerateCredentials.
  313. if (NS_FAILED(rv)) {
  314. return mCompleteEvent->DispatchError(mSessionState.forget(),
  315. mContinuationState.forget());
  316. }
  317. return mCompleteEvent->DispatchSuccess(creds, flags,
  318. mSessionState.forget(),
  319. mContinuationState.forget());
  320. }
  321. NS_IMETHODIMP ObtainCredentialsAndFlags(char **aCreds, uint32_t *aFlags)
  322. {
  323. nsresult rv;
  324. // Use negotiate service to call GenerateCredentials outside of main thread
  325. nsAutoCString contractId;
  326. contractId.Assign(NS_HTTP_AUTHENTICATOR_CONTRACTID_PREFIX);
  327. contractId.Append("negotiate");
  328. nsCOMPtr<nsIHttpAuthenticator> authenticator =
  329. do_GetService(contractId.get(), &rv);
  330. NS_ENSURE_SUCCESS(rv, rv);
  331. nsISupports *sessionState = mSessionState;
  332. nsISupports *continuationState = mContinuationState;
  333. // The continuationState is for the sake of completeness propagated
  334. // to the caller (despite it is not changed in any GenerateCredentials
  335. // implementation).
  336. //
  337. // The only implementation that use sessionState is the
  338. // nsHttpDigestAuth::GenerateCredentials. Since there's no reason
  339. // to implement nsHttpDigestAuth::GenerateCredentialsAsync
  340. // because digest auth does not block the main thread, we won't
  341. // propagate changes to sessionState to the caller because of
  342. // the change is too complicated on the caller side.
  343. //
  344. // Should any of the session or continuation states change inside
  345. // this method, they must be threadsafe.
  346. rv = authenticator->GenerateCredentials(mAuthChannel,
  347. mChallenge.get(),
  348. mIsProxyAuth,
  349. mDomain.get(),
  350. mUsername.get(),
  351. mPassword.get(),
  352. &sessionState,
  353. &continuationState,
  354. aFlags,
  355. aCreds);
  356. if (mSessionState != sessionState) {
  357. mSessionState = sessionState;
  358. }
  359. if (mContinuationState != continuationState) {
  360. mContinuationState = continuationState;
  361. }
  362. return rv;
  363. }
  364. private:
  365. nsCOMPtr<nsIHttpAuthenticableChannel> mAuthChannel;
  366. nsCString mChallenge;
  367. bool mIsProxyAuth;
  368. nsString mDomain;
  369. nsString mUsername;
  370. nsString mPassword;
  371. nsCOMPtr<nsISupports> mSessionState;
  372. nsCOMPtr<nsISupports> mContinuationState;
  373. RefPtr<GetNextTokenCompleteEvent> mCompleteEvent;
  374. };
  375. } // anonymous namespace
  376. NS_IMETHODIMP
  377. nsHttpNegotiateAuth::GenerateCredentialsAsync(nsIHttpAuthenticableChannel *authChannel,
  378. nsIHttpAuthenticatorCallback* aCallback,
  379. const char *challenge,
  380. bool isProxyAuth,
  381. const char16_t *domain,
  382. const char16_t *username,
  383. const char16_t *password,
  384. nsISupports *sessionState,
  385. nsISupports *continuationState,
  386. nsICancelable **aCancelable)
  387. {
  388. NS_ENSURE_ARG(aCallback);
  389. NS_ENSURE_ARG_POINTER(aCancelable);
  390. RefPtr<GetNextTokenCompleteEvent> cancelEvent =
  391. new GetNextTokenCompleteEvent(aCallback);
  392. nsCOMPtr<nsIRunnable> getNextTokenRunnable =
  393. new GetNextTokenRunnable(authChannel,
  394. challenge,
  395. isProxyAuth,
  396. domain,
  397. username,
  398. password,
  399. sessionState,
  400. continuationState,
  401. cancelEvent);
  402. cancelEvent.forget(aCancelable);
  403. nsresult rv;
  404. if (!mNegotiateThread) {
  405. mNegotiateThread =
  406. new mozilla::LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS,
  407. NS_LITERAL_CSTRING("NegotiateAuth"));
  408. NS_ENSURE_TRUE(mNegotiateThread, NS_ERROR_OUT_OF_MEMORY);
  409. }
  410. rv = mNegotiateThread->Dispatch(getNextTokenRunnable, NS_DISPATCH_NORMAL);
  411. NS_ENSURE_SUCCESS(rv, rv);
  412. return NS_OK;
  413. }
  414. //
  415. // GenerateCredentials
  416. //
  417. // This routine is responsible for creating the correct authentication
  418. // blob to pass to the server that requested "Negotiate" authentication.
  419. //
  420. NS_IMETHODIMP
  421. nsHttpNegotiateAuth::GenerateCredentials(nsIHttpAuthenticableChannel *authChannel,
  422. const char *challenge,
  423. bool isProxyAuth,
  424. const char16_t *domain,
  425. const char16_t *username,
  426. const char16_t *password,
  427. nsISupports **sessionState,
  428. nsISupports **continuationState,
  429. uint32_t *flags,
  430. char **creds)
  431. {
  432. // ChallengeReceived must have been called previously.
  433. nsIAuthModule *module = (nsIAuthModule *) *continuationState;
  434. NS_ENSURE_TRUE(module, NS_ERROR_NOT_INITIALIZED);
  435. *flags = USING_INTERNAL_IDENTITY;
  436. LOG(("nsHttpNegotiateAuth::GenerateCredentials() [challenge=%s]\n", challenge));
  437. NS_ASSERTION(creds, "null param");
  438. #ifdef DEBUG
  439. bool isGssapiAuth =
  440. !PL_strncasecmp(challenge, kNegotiate, kNegotiateLen);
  441. NS_ASSERTION(isGssapiAuth, "Unexpected challenge");
  442. #endif
  443. //
  444. // If the "Negotiate:" header had some data associated with it,
  445. // that data should be used as the input to this call. This may
  446. // be a continuation of an earlier call because GSSAPI authentication
  447. // often takes multiple round-trips to complete depending on the
  448. // context flags given. We want to use MUTUAL_AUTHENTICATION which
  449. // generally *does* require multiple round-trips. Don't assume
  450. // auth can be completed in just 1 call.
  451. //
  452. unsigned int len = strlen(challenge);
  453. void *inToken, *outToken;
  454. uint32_t inTokenLen, outTokenLen;
  455. if (len > kNegotiateLen) {
  456. challenge += kNegotiateLen;
  457. while (*challenge == ' ')
  458. challenge++;
  459. len = strlen(challenge);
  460. if (!len)
  461. return NS_ERROR_UNEXPECTED;
  462. // strip off any padding (see bug 230351)
  463. while (len && challenge[len - 1] == '=')
  464. len--;
  465. //
  466. // Decode the response that followed the "Negotiate" token
  467. //
  468. nsresult rv =
  469. Base64Decode(challenge, len, (char**)&inToken, &inTokenLen);
  470. if (NS_FAILED(rv)) {
  471. return rv;
  472. }
  473. }
  474. else {
  475. //
  476. // Initializing, don't use an input token.
  477. //
  478. inToken = nullptr;
  479. inTokenLen = 0;
  480. }
  481. nsresult rv = module->GetNextToken(inToken, inTokenLen, &outToken, &outTokenLen);
  482. free(inToken);
  483. if (NS_FAILED(rv))
  484. return rv;
  485. if (outTokenLen == 0) {
  486. LOG((" No output token to send, exiting"));
  487. return NS_ERROR_FAILURE;
  488. }
  489. //
  490. // base64 encode the output token.
  491. //
  492. char *encoded_token = PL_Base64Encode((char *)outToken, outTokenLen, nullptr);
  493. free(outToken);
  494. if (!encoded_token)
  495. return NS_ERROR_OUT_OF_MEMORY;
  496. LOG((" Sending a token of length %d\n", outTokenLen));
  497. // allocate a buffer sizeof("Negotiate" + " " + b64output_token + "\0")
  498. const int bufsize = kNegotiateLen + 1 + strlen(encoded_token) + 1;
  499. *creds = (char *) moz_xmalloc(bufsize);
  500. if (MOZ_UNLIKELY(!*creds))
  501. rv = NS_ERROR_OUT_OF_MEMORY;
  502. else
  503. snprintf(*creds, bufsize, "%s %s", kNegotiate, encoded_token);
  504. PR_Free(encoded_token);
  505. return rv;
  506. }
  507. bool
  508. nsHttpNegotiateAuth::TestBoolPref(const char *pref)
  509. {
  510. nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  511. if (!prefs)
  512. return false;
  513. bool val;
  514. nsresult rv = prefs->GetBoolPref(pref, &val);
  515. if (NS_FAILED(rv))
  516. return false;
  517. return val;
  518. }
  519. bool
  520. nsHttpNegotiateAuth::TestNonFqdn(nsIURI *uri)
  521. {
  522. nsAutoCString host;
  523. PRNetAddr addr;
  524. if (!TestBoolPref(kNegotiateAuthAllowNonFqdn))
  525. return false;
  526. if (NS_FAILED(uri->GetAsciiHost(host)))
  527. return false;
  528. // return true if host does not contain a dot and is not an ip address
  529. return !host.IsEmpty() && !host.Contains('.') &&
  530. PR_StringToNetAddr(host.BeginReading(), &addr) != PR_SUCCESS;
  531. }
  532. bool
  533. nsHttpNegotiateAuth::TestPref(nsIURI *uri, const char *pref)
  534. {
  535. nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  536. if (!prefs)
  537. return false;
  538. nsAutoCString scheme, host;
  539. int32_t port;
  540. if (NS_FAILED(uri->GetScheme(scheme)))
  541. return false;
  542. if (NS_FAILED(uri->GetAsciiHost(host)))
  543. return false;
  544. if (NS_FAILED(uri->GetPort(&port)))
  545. return false;
  546. char *hostList;
  547. if (NS_FAILED(prefs->GetCharPref(pref, &hostList)) || !hostList)
  548. return false;
  549. // pseudo-BNF
  550. // ----------
  551. //
  552. // url-list base-url ( base-url "," LWS )*
  553. // base-url ( scheme-part | host-part | scheme-part host-part )
  554. // scheme-part scheme "://"
  555. // host-part host [":" port]
  556. //
  557. // for example:
  558. // "https://, http://office.foo.com"
  559. //
  560. char *start = hostList, *end;
  561. for (;;) {
  562. // skip past any whitespace
  563. while (*start == ' ' || *start == '\t')
  564. ++start;
  565. end = strchr(start, ',');
  566. if (!end)
  567. end = start + strlen(start);
  568. if (start == end)
  569. break;
  570. if (MatchesBaseURI(scheme, host, port, start, end))
  571. return true;
  572. if (*end == '\0')
  573. break;
  574. start = end + 1;
  575. }
  576. free(hostList);
  577. return false;
  578. }
  579. bool
  580. nsHttpNegotiateAuth::MatchesBaseURI(const nsCSubstring &matchScheme,
  581. const nsCSubstring &matchHost,
  582. int32_t matchPort,
  583. const char *baseStart,
  584. const char *baseEnd)
  585. {
  586. // check if scheme://host:port matches baseURI
  587. // parse the base URI
  588. const char *hostStart, *schemeEnd = strstr(baseStart, "://");
  589. if (schemeEnd) {
  590. // the given scheme must match the parsed scheme exactly
  591. if (!matchScheme.Equals(Substring(baseStart, schemeEnd)))
  592. return false;
  593. hostStart = schemeEnd + 3;
  594. }
  595. else
  596. hostStart = baseStart;
  597. // XXX this does not work for IPv6-literals
  598. const char *hostEnd = strchr(hostStart, ':');
  599. if (hostEnd && hostEnd < baseEnd) {
  600. // the given port must match the parsed port exactly
  601. int port = atoi(hostEnd + 1);
  602. if (matchPort != (int32_t) port)
  603. return false;
  604. }
  605. else
  606. hostEnd = baseEnd;
  607. // if we didn't parse out a host, then assume we got a match.
  608. if (hostStart == hostEnd)
  609. return true;
  610. uint32_t hostLen = hostEnd - hostStart;
  611. // matchHost must either equal host or be a subdomain of host
  612. if (matchHost.Length() < hostLen)
  613. return false;
  614. const char *end = matchHost.EndReading();
  615. if (PL_strncasecmp(end - hostLen, hostStart, hostLen) == 0) {
  616. // if matchHost ends with host from the base URI, then make sure it is
  617. // either an exact match, or prefixed with a dot. we don't want
  618. // "foobar.com" to match "bar.com"
  619. if (matchHost.Length() == hostLen ||
  620. *(end - hostLen) == '.' ||
  621. *(end - hostLen - 1) == '.')
  622. return true;
  623. }
  624. return false;
  625. }