PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/security/manager/boot/src/nsSecureBrowserUIImpl.cpp

http://github.com/zpao/v8monkey
C++ | 1942 lines | 1363 code | 290 blank | 289 comment | 202 complexity | 8cfa5f8b1a6419a32ef2874d656d2a26 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, AGPL-1.0, LGPL-2.1, BSD-3-Clause, GPL-2.0, JSON, Apache-2.0, 0BSD
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  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 mozilla.org code.
  16. *
  17. * The Initial Developer of the Original Code is
  18. * Netscape Communications Corporation.
  19. * Portions created by the Initial Developer are Copyright (C) 1998-2001
  20. * the Initial Developer. All Rights Reserved.
  21. *
  22. * Contributor(s):
  23. * Hubbie Shaw
  24. * Doug Turner <dougt@netscape.com>
  25. * Stuart Parmenter <pavlov@netscape.com>
  26. * Brian Ryner <bryner@brianryner.com>
  27. * Terry Hayes <thayes@netscape.com>
  28. * Kai Engert <kaie@netscape.com>
  29. *
  30. * Alternatively, the contents of this file may be used under the terms of
  31. * either the GNU General Public License Version 2 or later (the "GPL"), or
  32. * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  33. * in which case the provisions of the GPL or the LGPL are applicable instead
  34. * of those above. If you wish to allow use of your version of this file only
  35. * under the terms of either the GPL or the LGPL, and not to allow others to
  36. * use your version of this file under the terms of the MPL, indicate your
  37. * decision by deleting the provisions above and replace them with the notice
  38. * and other provisions required by the GPL or the LGPL. If you do not delete
  39. * the provisions above, a recipient may use your version of this file under
  40. * the terms of any one of the MPL, the GPL or the LGPL.
  41. *
  42. * ***** END LICENSE BLOCK ***** */
  43. #ifdef MOZ_LOGGING
  44. #define FORCE_PR_LOG
  45. #endif
  46. #include "nspr.h"
  47. #include "prlog.h"
  48. #include "prmem.h"
  49. #include "nsISecureBrowserUI.h"
  50. #include "nsSecureBrowserUIImpl.h"
  51. #include "nsCOMPtr.h"
  52. #include "nsIInterfaceRequestor.h"
  53. #include "nsIInterfaceRequestorUtils.h"
  54. #include "nsIServiceManager.h"
  55. #include "nsIObserverService.h"
  56. #include "nsCURILoader.h"
  57. #include "nsIDocShell.h"
  58. #include "nsIDocument.h"
  59. #include "nsIPrincipal.h"
  60. #include "nsIDOMElement.h"
  61. #include "nsPIDOMWindow.h"
  62. #include "nsIContent.h"
  63. #include "nsIWebProgress.h"
  64. #include "nsIWebProgressListener.h"
  65. #include "nsIChannel.h"
  66. #include "nsIHttpChannel.h"
  67. #include "nsIFileChannel.h"
  68. #include "nsIWyciwygChannel.h"
  69. #include "nsIFTPChannel.h"
  70. #include "nsITransportSecurityInfo.h"
  71. #include "nsISSLStatus.h"
  72. #include "nsIURI.h"
  73. #include "nsISecurityEventSink.h"
  74. #include "nsIPrompt.h"
  75. #include "nsIFormSubmitObserver.h"
  76. #include "nsISecurityWarningDialogs.h"
  77. #include "nsISecurityInfoProvider.h"
  78. #include "imgIRequest.h"
  79. #include "nsThreadUtils.h"
  80. #include "nsNetUtil.h"
  81. #include "nsNetCID.h"
  82. #include "nsCRT.h"
  83. using namespace mozilla;
  84. #define SECURITY_STRING_BUNDLE_URL "chrome://pipnss/locale/security.properties"
  85. #define IS_SECURE(state) ((state & 0xFFFF) == STATE_IS_SECURE)
  86. #if defined(PR_LOGGING)
  87. //
  88. // Log module for nsSecureBrowserUI logging...
  89. //
  90. // To enable logging (see prlog.h for full details):
  91. //
  92. // set NSPR_LOG_MODULES=nsSecureBrowserUI:5
  93. // set NSPR_LOG_FILE=nspr.log
  94. //
  95. // this enables PR_LOG_DEBUG level information and places all output in
  96. // the file nspr.log
  97. //
  98. PRLogModuleInfo* gSecureDocLog = nsnull;
  99. #endif /* PR_LOGGING */
  100. struct RequestHashEntry : PLDHashEntryHdr {
  101. void *r;
  102. };
  103. PR_STATIC_CALLBACK(bool)
  104. RequestMapMatchEntry(PLDHashTable *table, const PLDHashEntryHdr *hdr,
  105. const void *key)
  106. {
  107. const RequestHashEntry *entry = static_cast<const RequestHashEntry*>(hdr);
  108. return entry->r == key;
  109. }
  110. PR_STATIC_CALLBACK(bool)
  111. RequestMapInitEntry(PLDHashTable *table, PLDHashEntryHdr *hdr,
  112. const void *key)
  113. {
  114. RequestHashEntry *entry = static_cast<RequestHashEntry*>(hdr);
  115. entry->r = (void*)key;
  116. return true;
  117. }
  118. static PLDHashTableOps gMapOps = {
  119. PL_DHashAllocTable,
  120. PL_DHashFreeTable,
  121. PL_DHashVoidPtrKeyStub,
  122. RequestMapMatchEntry,
  123. PL_DHashMoveEntryStub,
  124. PL_DHashClearEntryStub,
  125. PL_DHashFinalizeStub,
  126. RequestMapInitEntry
  127. };
  128. #ifdef DEBUG
  129. class nsAutoAtomic {
  130. public:
  131. nsAutoAtomic(PRInt32 &i)
  132. :mI(i) {
  133. PR_ATOMIC_INCREMENT(&mI);
  134. }
  135. ~nsAutoAtomic() {
  136. PR_ATOMIC_DECREMENT(&mI);
  137. }
  138. protected:
  139. PRInt32 &mI;
  140. private:
  141. nsAutoAtomic(); // not accessible
  142. };
  143. #endif
  144. nsSecureBrowserUIImpl::nsSecureBrowserUIImpl()
  145. : mReentrantMonitor("nsSecureBrowserUIImpl.mReentrantMonitor")
  146. , mNotifiedSecurityState(lis_no_security)
  147. , mNotifiedToplevelIsEV(false)
  148. , mNewToplevelSecurityState(STATE_IS_INSECURE)
  149. , mNewToplevelIsEV(false)
  150. , mNewToplevelSecurityStateKnown(true)
  151. , mIsViewSource(false)
  152. , mSubRequestsHighSecurity(0)
  153. , mSubRequestsLowSecurity(0)
  154. , mSubRequestsBrokenSecurity(0)
  155. , mSubRequestsNoSecurity(0)
  156. #ifdef DEBUG
  157. , mOnStateLocationChangeReentranceDetection(0)
  158. #endif
  159. {
  160. mTransferringRequests.ops = nsnull;
  161. ResetStateTracking();
  162. #if defined(PR_LOGGING)
  163. if (!gSecureDocLog)
  164. gSecureDocLog = PR_NewLogModule("nsSecureBrowserUI");
  165. #endif /* PR_LOGGING */
  166. }
  167. nsSecureBrowserUIImpl::~nsSecureBrowserUIImpl()
  168. {
  169. if (mTransferringRequests.ops) {
  170. PL_DHashTableFinish(&mTransferringRequests);
  171. mTransferringRequests.ops = nsnull;
  172. }
  173. }
  174. NS_IMPL_THREADSAFE_ISUPPORTS6(nsSecureBrowserUIImpl,
  175. nsISecureBrowserUI,
  176. nsIWebProgressListener,
  177. nsIFormSubmitObserver,
  178. nsIObserver,
  179. nsISupportsWeakReference,
  180. nsISSLStatusProvider)
  181. NS_IMETHODIMP
  182. nsSecureBrowserUIImpl::Init(nsIDOMWindow *aWindow)
  183. {
  184. #ifdef PR_LOGGING
  185. nsCOMPtr<nsIDOMWindow> window(do_QueryReferent(mWindow));
  186. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  187. ("SecureUI:%p: Init: mWindow: %p, aWindow: %p\n", this,
  188. window.get(), aWindow));
  189. #endif
  190. if (!aWindow) {
  191. NS_WARNING("Null window passed to nsSecureBrowserUIImpl::Init()");
  192. return NS_ERROR_INVALID_ARG;
  193. }
  194. if (mWindow) {
  195. NS_WARNING("Trying to init an nsSecureBrowserUIImpl twice");
  196. return NS_ERROR_ALREADY_INITIALIZED;
  197. }
  198. nsCOMPtr<nsPIDOMWindow> pwin(do_QueryInterface(aWindow));
  199. if (pwin->IsInnerWindow()) {
  200. pwin = pwin->GetOuterWindow();
  201. }
  202. nsresult rv;
  203. mWindow = do_GetWeakReference(pwin, &rv);
  204. NS_ENSURE_SUCCESS(rv, rv);
  205. nsCOMPtr<nsIStringBundleService> service(do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv));
  206. if (NS_FAILED(rv)) return rv;
  207. // We do not need to test for mStringBundle here...
  208. // Anywhere we use it, we will test before using. Some
  209. // embedded users of PSM may want to reuse our
  210. // nsSecureBrowserUIImpl implementation without the
  211. // bundle.
  212. service->CreateBundle(SECURITY_STRING_BUNDLE_URL, getter_AddRefs(mStringBundle));
  213. // hook up to the form post notifications:
  214. nsCOMPtr<nsIObserverService> svc(do_GetService("@mozilla.org/observer-service;1", &rv));
  215. if (NS_SUCCEEDED(rv)) {
  216. rv = svc->AddObserver(this, NS_FORMSUBMIT_SUBJECT, true);
  217. }
  218. nsCOMPtr<nsPIDOMWindow> piwindow(do_QueryInterface(aWindow));
  219. if (!piwindow) return NS_ERROR_FAILURE;
  220. nsIDocShell *docShell = piwindow->GetDocShell();
  221. // The Docshell will own the SecureBrowserUI object
  222. if (!docShell)
  223. return NS_ERROR_FAILURE;
  224. docShell->SetSecurityUI(this);
  225. /* GetWebProgress(mWindow) */
  226. // hook up to the webprogress notifications.
  227. nsCOMPtr<nsIWebProgress> wp(do_GetInterface(docShell));
  228. if (!wp) return NS_ERROR_FAILURE;
  229. /* end GetWebProgress */
  230. wp->AddProgressListener(static_cast<nsIWebProgressListener*>(this),
  231. nsIWebProgress::NOTIFY_STATE_ALL |
  232. nsIWebProgress::NOTIFY_LOCATION |
  233. nsIWebProgress::NOTIFY_SECURITY);
  234. return NS_OK;
  235. }
  236. NS_IMETHODIMP
  237. nsSecureBrowserUIImpl::GetState(PRUint32* aState)
  238. {
  239. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  240. return MapInternalToExternalState(aState, mNotifiedSecurityState, mNotifiedToplevelIsEV);
  241. }
  242. // static
  243. already_AddRefed<nsISupports>
  244. nsSecureBrowserUIImpl::ExtractSecurityInfo(nsIRequest* aRequest)
  245. {
  246. nsISupports *retval = nsnull;
  247. nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
  248. if (channel)
  249. channel->GetSecurityInfo(&retval);
  250. if (!retval) {
  251. nsCOMPtr<nsISecurityInfoProvider> provider(do_QueryInterface(aRequest));
  252. if (provider)
  253. provider->GetSecurityInfo(&retval);
  254. }
  255. return retval;
  256. }
  257. nsresult
  258. nsSecureBrowserUIImpl::MapInternalToExternalState(PRUint32* aState, lockIconState lock, bool ev)
  259. {
  260. NS_ENSURE_ARG(aState);
  261. switch (lock)
  262. {
  263. case lis_broken_security:
  264. *aState = STATE_IS_BROKEN;
  265. break;
  266. case lis_mixed_security:
  267. *aState = STATE_IS_BROKEN;
  268. break;
  269. case lis_low_security:
  270. *aState = STATE_IS_SECURE | STATE_SECURE_LOW;
  271. break;
  272. case lis_high_security:
  273. *aState = STATE_IS_SECURE | STATE_SECURE_HIGH;
  274. break;
  275. default:
  276. case lis_no_security:
  277. *aState = STATE_IS_INSECURE;
  278. break;
  279. }
  280. if (ev && (*aState & STATE_IS_SECURE))
  281. *aState |= nsIWebProgressListener::STATE_IDENTITY_EV_TOPLEVEL;
  282. return NS_OK;
  283. }
  284. NS_IMETHODIMP
  285. nsSecureBrowserUIImpl::GetTooltipText(nsAString& aText)
  286. {
  287. lockIconState state;
  288. nsXPIDLString tooltip;
  289. {
  290. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  291. state = mNotifiedSecurityState;
  292. tooltip = mInfoTooltip;
  293. }
  294. if (state == lis_mixed_security)
  295. {
  296. GetBundleString(NS_LITERAL_STRING("SecurityButtonMixedContentTooltipText").get(),
  297. aText);
  298. }
  299. else if (!tooltip.IsEmpty())
  300. {
  301. aText = tooltip;
  302. }
  303. else
  304. {
  305. GetBundleString(NS_LITERAL_STRING("SecurityButtonTooltipText").get(),
  306. aText);
  307. }
  308. return NS_OK;
  309. }
  310. NS_IMETHODIMP
  311. nsSecureBrowserUIImpl::Observe(nsISupports*, const char*,
  312. const PRUnichar*)
  313. {
  314. return NS_ERROR_NOT_IMPLEMENTED;
  315. }
  316. static nsresult IsChildOfDomWindow(nsIDOMWindow *parent, nsIDOMWindow *child,
  317. bool* value)
  318. {
  319. *value = false;
  320. if (parent == child) {
  321. *value = true;
  322. return NS_OK;
  323. }
  324. nsCOMPtr<nsIDOMWindow> childsParent;
  325. child->GetParent(getter_AddRefs(childsParent));
  326. if (childsParent && childsParent.get() != child)
  327. IsChildOfDomWindow(parent, childsParent, value);
  328. return NS_OK;
  329. }
  330. static PRUint32 GetSecurityStateFromSecurityInfo(nsISupports *info)
  331. {
  332. nsresult res;
  333. PRUint32 securityState;
  334. nsCOMPtr<nsITransportSecurityInfo> psmInfo(do_QueryInterface(info));
  335. if (!psmInfo) {
  336. PR_LOG(gSecureDocLog, PR_LOG_DEBUG, ("SecureUI: GetSecurityState: - no nsITransportSecurityInfo for %p\n",
  337. (nsISupports *)info));
  338. return nsIWebProgressListener::STATE_IS_INSECURE;
  339. }
  340. PR_LOG(gSecureDocLog, PR_LOG_DEBUG, ("SecureUI: GetSecurityState: - info is %p\n",
  341. (nsISupports *)info));
  342. res = psmInfo->GetSecurityState(&securityState);
  343. if (NS_FAILED(res)) {
  344. PR_LOG(gSecureDocLog, PR_LOG_DEBUG, ("SecureUI: GetSecurityState: - GetSecurityState failed: %d\n",
  345. res));
  346. securityState = nsIWebProgressListener::STATE_IS_BROKEN;
  347. }
  348. PR_LOG(gSecureDocLog, PR_LOG_DEBUG, ("SecureUI: GetSecurityState: - Returning %d\n",
  349. securityState));
  350. return securityState;
  351. }
  352. NS_IMETHODIMP
  353. nsSecureBrowserUIImpl::Notify(nsIDOMHTMLFormElement* aDOMForm,
  354. nsIDOMWindow* aWindow, nsIURI* actionURL,
  355. bool* cancelSubmit)
  356. {
  357. // Return NS_OK unless we want to prevent this form from submitting.
  358. *cancelSubmit = false;
  359. if (!aWindow || !actionURL || !aDOMForm)
  360. return NS_OK;
  361. nsCOMPtr<nsIContent> formNode = do_QueryInterface(aDOMForm);
  362. nsCOMPtr<nsIDocument> document = formNode->GetDocument();
  363. if (!document) return NS_OK;
  364. nsIPrincipal *principal = formNode->NodePrincipal();
  365. if (!principal)
  366. {
  367. *cancelSubmit = true;
  368. return NS_OK;
  369. }
  370. nsCOMPtr<nsIURI> formURL;
  371. if (NS_FAILED(principal->GetURI(getter_AddRefs(formURL))) ||
  372. !formURL)
  373. {
  374. formURL = document->GetDocumentURI();
  375. }
  376. nsCOMPtr<nsIDOMWindow> postingWindow =
  377. do_QueryInterface(document->GetWindow());
  378. // We can't find this document's window, cancel it.
  379. if (!postingWindow)
  380. {
  381. NS_WARNING("If you see this and can explain why it should be allowed, note in Bug 332324");
  382. *cancelSubmit = true;
  383. return NS_OK;
  384. }
  385. nsCOMPtr<nsIDOMWindow> window;
  386. {
  387. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  388. window = do_QueryReferent(mWindow);
  389. NS_ASSERTION(window, "Window has gone away?!");
  390. }
  391. bool isChild;
  392. IsChildOfDomWindow(window, postingWindow, &isChild);
  393. // This notify call is not for our window, ignore it.
  394. if (!isChild)
  395. return NS_OK;
  396. bool okayToPost;
  397. nsresult res = CheckPost(formURL, actionURL, &okayToPost);
  398. if (NS_SUCCEEDED(res) && !okayToPost)
  399. *cancelSubmit = true;
  400. return res;
  401. }
  402. // nsIWebProgressListener
  403. NS_IMETHODIMP
  404. nsSecureBrowserUIImpl::OnProgressChange(nsIWebProgress* aWebProgress,
  405. nsIRequest* aRequest,
  406. PRInt32 aCurSelfProgress,
  407. PRInt32 aMaxSelfProgress,
  408. PRInt32 aCurTotalProgress,
  409. PRInt32 aMaxTotalProgress)
  410. {
  411. NS_NOTREACHED("notification excluded in AddProgressListener(...)");
  412. return NS_OK;
  413. }
  414. void nsSecureBrowserUIImpl::ResetStateTracking()
  415. {
  416. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  417. mInfoTooltip.Truncate();
  418. mDocumentRequestsInProgress = 0;
  419. if (mTransferringRequests.ops) {
  420. PL_DHashTableFinish(&mTransferringRequests);
  421. mTransferringRequests.ops = nsnull;
  422. }
  423. PL_DHashTableInit(&mTransferringRequests, &gMapOps, nsnull,
  424. sizeof(RequestHashEntry), 16);
  425. }
  426. nsresult
  427. nsSecureBrowserUIImpl::EvaluateAndUpdateSecurityState(nsIRequest* aRequest, nsISupports *info,
  428. bool withNewLocation)
  429. {
  430. /* I explicitly ignore the camelCase variable naming style here,
  431. I want to make it clear these are temp variables that relate to the
  432. member variables with the same suffix.*/
  433. PRUint32 temp_NewToplevelSecurityState = nsIWebProgressListener::STATE_IS_INSECURE;
  434. bool temp_NewToplevelIsEV = false;
  435. bool updateStatus = false;
  436. nsCOMPtr<nsISSLStatus> temp_SSLStatus;
  437. bool updateTooltip = false;
  438. nsXPIDLString temp_InfoTooltip;
  439. temp_NewToplevelSecurityState = GetSecurityStateFromSecurityInfo(info);
  440. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  441. ("SecureUI:%p: OnStateChange: remember mNewToplevelSecurityState => %x\n", this,
  442. temp_NewToplevelSecurityState));
  443. nsCOMPtr<nsISSLStatusProvider> sp = do_QueryInterface(info);
  444. if (sp) {
  445. // Ignore result
  446. updateStatus = true;
  447. (void) sp->GetSSLStatus(getter_AddRefs(temp_SSLStatus));
  448. if (temp_SSLStatus) {
  449. bool aTemp;
  450. if (NS_SUCCEEDED(temp_SSLStatus->GetIsExtendedValidation(&aTemp))) {
  451. temp_NewToplevelIsEV = aTemp;
  452. }
  453. }
  454. }
  455. if (info) {
  456. nsCOMPtr<nsITransportSecurityInfo> secInfo(do_QueryInterface(info));
  457. if (secInfo) {
  458. updateTooltip = true;
  459. secInfo->GetShortSecurityDescription(getter_Copies(temp_InfoTooltip));
  460. }
  461. }
  462. // assume temp_NewToplevelSecurityState was set in this scope!
  463. // see code that is directly above
  464. {
  465. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  466. mNewToplevelSecurityStateKnown = true;
  467. mNewToplevelSecurityState = temp_NewToplevelSecurityState;
  468. mNewToplevelIsEV = temp_NewToplevelIsEV;
  469. if (updateStatus) {
  470. mSSLStatus = temp_SSLStatus;
  471. }
  472. if (updateTooltip) {
  473. mInfoTooltip = temp_InfoTooltip;
  474. }
  475. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  476. ("SecureUI:%p: remember securityInfo %p\n", this,
  477. info));
  478. nsCOMPtr<nsIAssociatedContentSecurity> associatedContentSecurityFromRequest =
  479. do_QueryInterface(aRequest);
  480. if (associatedContentSecurityFromRequest)
  481. mCurrentToplevelSecurityInfo = aRequest;
  482. else
  483. mCurrentToplevelSecurityInfo = info;
  484. }
  485. return UpdateSecurityState(aRequest, withNewLocation,
  486. updateStatus, updateTooltip);
  487. }
  488. void
  489. nsSecureBrowserUIImpl::UpdateSubrequestMembers(nsISupports *securityInfo)
  490. {
  491. // For wyciwyg channels in subdocuments we only update our
  492. // subrequest state members.
  493. PRUint32 reqState = GetSecurityStateFromSecurityInfo(securityInfo);
  494. // the code above this line should run without a lock
  495. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  496. if (reqState & STATE_IS_SECURE) {
  497. if (reqState & STATE_SECURE_LOW || reqState & STATE_SECURE_MED) {
  498. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  499. ("SecureUI:%p: OnStateChange: subreq LOW\n", this));
  500. ++mSubRequestsLowSecurity;
  501. } else {
  502. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  503. ("SecureUI:%p: OnStateChange: subreq HIGH\n", this));
  504. ++mSubRequestsHighSecurity;
  505. }
  506. } else if (reqState & STATE_IS_BROKEN) {
  507. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  508. ("SecureUI:%p: OnStateChange: subreq BROKEN\n", this));
  509. ++mSubRequestsBrokenSecurity;
  510. } else {
  511. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  512. ("SecureUI:%p: OnStateChange: subreq INSECURE\n", this));
  513. ++mSubRequestsNoSecurity;
  514. }
  515. }
  516. NS_IMETHODIMP
  517. nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress,
  518. nsIRequest* aRequest,
  519. PRUint32 aProgressStateFlags,
  520. nsresult aStatus)
  521. {
  522. #ifdef DEBUG
  523. nsAutoAtomic atomic(mOnStateLocationChangeReentranceDetection);
  524. NS_ASSERTION(mOnStateLocationChangeReentranceDetection == 1,
  525. "unexpected parallel nsIWebProgress OnStateChange and/or OnLocationChange notification");
  526. #endif
  527. /*
  528. All discussion, unless otherwise mentioned, only refers to
  529. http, https, file or wyciwig requests.
  530. Redirects are evil, well, some of them.
  531. There are multiple forms of redirects.
  532. Redirects caused by http refresh content are ok, because experiments show,
  533. with those redirects, the old page contents and their requests will come to STOP
  534. completely, before any progress from new refreshed page content is reported.
  535. So we can safely treat them as separate page loading transactions.
  536. Evil are redirects at the http protocol level, like code 302.
  537. If the toplevel documents gets replaced, i.e. redirected with 302, we do not care for the
  538. security state of the initial transaction, which has now been redirected,
  539. we only care for the new page load.
  540. For the implementation of the security UI, we make an assumption, that is hopefully true.
  541. Imagine, the received page that was delivered with the 302 redirection answer,
  542. also delivered html content.
  543. What happens if the parser starts to analyze the content and tries to load contained sub objects?
  544. In that case we would see start and stop requests for subdocuments, some for the previous document,
  545. some for the new target document. And only those for the new toplevel document may be
  546. taken into consideration, when deciding about the security state of the next toplevel document.
  547. Because security state is being looked at, when loading stops for (sub)documents, this
  548. could cause real confusion, because we have to decide, whether an incoming progress
  549. belongs to the new toplevel page, or the previous, already redirected page.
  550. Can we simplify here?
  551. If a redirect at the http protocol level is seen, can we safely assume, its html content
  552. will not be parsed, anylzed, and no embedded objects will get loaded (css, js, images),
  553. because the redirect is already happening?
  554. If we can assume that, this really simplify things. Because we will never see notification
  555. for sub requests that need to get ignored.
  556. I would like to make this assumption for now, but please let me (kaie) know if I'm wrong.
  557. Excurse:
  558. If my assumption is wrong, then we would require more tracking information.
  559. We need to keep lists of all pointers to request object that had been seen since the
  560. last toplevel start event.
  561. If the start for a redirected page is seen, the list of releveant object must be cleared,
  562. and only progress for requests which start after it must be analyzed.
  563. All other events must be ignored, as they belong to now irrelevant previous top level documents.
  564. Frames are also evil.
  565. First we need a decision.
  566. kaie thinks:
  567. Only if the toplevel frame is secure, we should try to display secure lock icons.
  568. If some of the inner contents are insecure, we display mixed mode.
  569. But if the top level frame is not secure, why indicate a mixed lock icon at all?
  570. I think we should always display an open lock icon, if the top level frameset is insecure.
  571. That's the way Netscape Communicator behaves, and I think we should do the same.
  572. The user will not know which parts are secure and which are not,
  573. and any certificate information, displayed in the tooltip or in the "page info"
  574. will only be relevant for some subframe(s), and the user will not know which ones,
  575. so we shouldn't display it as a general attribute of the displayed page.
  576. Why are frames evil?
  577. Because the progress for the toplevel frame document is not easily distinguishable
  578. from subframes. The same STATE bits are reported.
  579. While at first sight, when a new page load happens,
  580. the toplevel frameset document has also the STATE_IS_NETWORK bit in it.
  581. But this can't really be used. Because in case that document causes a http 302 redirect,
  582. the real top level frameset will no longer have that bit.
  583. But we need some way to distinguish top level frames from inner frames.
  584. I saw that the web progress we get delivered has a reference to the toplevel DOM window.
  585. I suggest, we look at all incoming requests.
  586. If a request is NOT for the toplevel DOM window, we will always treat it as a subdocument request,
  587. regardless of whether the load flags indicate a top level document.
  588. */
  589. nsCOMPtr<nsIDOMWindow> windowForProgress;
  590. aWebProgress->GetDOMWindow(getter_AddRefs(windowForProgress));
  591. nsCOMPtr<nsIDOMWindow> window;
  592. bool isViewSource;
  593. nsCOMPtr<nsINetUtil> ioService;
  594. {
  595. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  596. window = do_QueryReferent(mWindow);
  597. NS_ASSERTION(window, "Window has gone away?!");
  598. isViewSource = mIsViewSource;
  599. ioService = mIOService;
  600. }
  601. if (!ioService)
  602. {
  603. ioService = do_GetService(NS_IOSERVICE_CONTRACTID);
  604. if (ioService)
  605. {
  606. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  607. mIOService = ioService;
  608. }
  609. }
  610. bool isNoContentResponse = false;
  611. nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest);
  612. if (httpChannel)
  613. {
  614. PRUint32 response;
  615. isNoContentResponse = NS_SUCCEEDED(httpChannel->GetResponseStatus(&response)) &&
  616. (response == 204 || response == 205);
  617. }
  618. const bool isToplevelProgress = (windowForProgress.get() == window.get()) && !isNoContentResponse;
  619. #ifdef PR_LOGGING
  620. if (windowForProgress)
  621. {
  622. if (isToplevelProgress)
  623. {
  624. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  625. ("SecureUI:%p: OnStateChange: progress: for toplevel\n", this));
  626. }
  627. else
  628. {
  629. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  630. ("SecureUI:%p: OnStateChange: progress: for something else\n", this));
  631. }
  632. }
  633. else
  634. {
  635. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  636. ("SecureUI:%p: OnStateChange: progress: no window known\n", this));
  637. }
  638. #endif
  639. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  640. ("SecureUI:%p: OnStateChange\n", this));
  641. if (isViewSource)
  642. return NS_OK;
  643. if (!aRequest)
  644. {
  645. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  646. ("SecureUI:%p: OnStateChange with null request\n", this));
  647. return NS_ERROR_NULL_POINTER;
  648. }
  649. #ifdef PR_LOGGING
  650. if (PR_LOG_TEST(gSecureDocLog, PR_LOG_DEBUG)) {
  651. nsXPIDLCString reqname;
  652. aRequest->GetName(reqname);
  653. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  654. ("SecureUI:%p: %p %p OnStateChange %x %s\n", this, aWebProgress,
  655. aRequest, aProgressStateFlags, reqname.get()));
  656. }
  657. #endif
  658. nsCOMPtr<nsISupports> securityInfo(ExtractSecurityInfo(aRequest));
  659. nsCOMPtr<nsIURI> uri;
  660. nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
  661. if (channel)
  662. {
  663. channel->GetURI(getter_AddRefs(uri));
  664. if (uri)
  665. {
  666. bool vs;
  667. if (NS_SUCCEEDED(uri->SchemeIs("javascript", &vs)) && vs)
  668. {
  669. // We ignore the progress events for javascript URLs.
  670. // If a document loading gets triggered, we will see more events.
  671. return NS_OK;
  672. }
  673. }
  674. }
  675. PRUint32 loadFlags = 0;
  676. aRequest->GetLoadFlags(&loadFlags);
  677. #ifdef PR_LOGGING
  678. if (aProgressStateFlags & STATE_START
  679. &&
  680. aProgressStateFlags & STATE_IS_REQUEST
  681. &&
  682. isToplevelProgress
  683. &&
  684. loadFlags & nsIChannel::LOAD_DOCUMENT_URI)
  685. {
  686. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  687. ("SecureUI:%p: OnStateChange: SOMETHING STARTS FOR TOPMOST DOCUMENT\n", this));
  688. }
  689. if (aProgressStateFlags & STATE_STOP
  690. &&
  691. aProgressStateFlags & STATE_IS_REQUEST
  692. &&
  693. isToplevelProgress
  694. &&
  695. loadFlags & nsIChannel::LOAD_DOCUMENT_URI)
  696. {
  697. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  698. ("SecureUI:%p: OnStateChange: SOMETHING STOPS FOR TOPMOST DOCUMENT\n", this));
  699. }
  700. #endif
  701. bool isSubDocumentRelevant = true;
  702. // We are only interested in requests that load in the browser window...
  703. nsCOMPtr<imgIRequest> imgRequest(do_QueryInterface(aRequest));
  704. if (imgRequest) {
  705. // for image requests, we get the URI from here
  706. imgRequest->GetURI(getter_AddRefs(uri));
  707. } else { // is not imgRequest
  708. nsCOMPtr<nsIHttpChannel> httpRequest(do_QueryInterface(aRequest));
  709. if (!httpRequest) {
  710. nsCOMPtr<nsIFileChannel> fileRequest(do_QueryInterface(aRequest));
  711. if (!fileRequest) {
  712. nsCOMPtr<nsIWyciwygChannel> wyciwygRequest(do_QueryInterface(aRequest));
  713. if (!wyciwygRequest) {
  714. nsCOMPtr<nsIFTPChannel> ftpRequest(do_QueryInterface(aRequest));
  715. if (!ftpRequest) {
  716. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  717. ("SecureUI:%p: OnStateChange: not relevant for sub content\n", this));
  718. isSubDocumentRelevant = false;
  719. }
  720. }
  721. }
  722. }
  723. }
  724. // This will ignore all resource, chrome, data, file, moz-icon, and anno
  725. // protocols. Local resources are treated as trusted.
  726. if (uri && ioService) {
  727. bool hasFlag;
  728. nsresult rv =
  729. ioService->URIChainHasFlags(uri,
  730. nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
  731. &hasFlag);
  732. if (NS_SUCCEEDED(rv) && hasFlag) {
  733. isSubDocumentRelevant = false;
  734. }
  735. }
  736. #if defined(DEBUG)
  737. nsCString info2;
  738. PRUint32 testFlags = loadFlags;
  739. if (testFlags & nsIChannel::LOAD_DOCUMENT_URI)
  740. {
  741. testFlags -= nsIChannel::LOAD_DOCUMENT_URI;
  742. info2.Append("LOAD_DOCUMENT_URI ");
  743. }
  744. if (testFlags & nsIChannel::LOAD_RETARGETED_DOCUMENT_URI)
  745. {
  746. testFlags -= nsIChannel::LOAD_RETARGETED_DOCUMENT_URI;
  747. info2.Append("LOAD_RETARGETED_DOCUMENT_URI ");
  748. }
  749. if (testFlags & nsIChannel::LOAD_REPLACE)
  750. {
  751. testFlags -= nsIChannel::LOAD_REPLACE;
  752. info2.Append("LOAD_REPLACE ");
  753. }
  754. const char *_status = NS_SUCCEEDED(aStatus) ? "1" : "0";
  755. nsCString info;
  756. PRUint32 f = aProgressStateFlags;
  757. if (f & nsIWebProgressListener::STATE_START)
  758. {
  759. f -= nsIWebProgressListener::STATE_START;
  760. info.Append("START ");
  761. }
  762. if (f & nsIWebProgressListener::STATE_REDIRECTING)
  763. {
  764. f -= nsIWebProgressListener::STATE_REDIRECTING;
  765. info.Append("REDIRECTING ");
  766. }
  767. if (f & nsIWebProgressListener::STATE_TRANSFERRING)
  768. {
  769. f -= nsIWebProgressListener::STATE_TRANSFERRING;
  770. info.Append("TRANSFERRING ");
  771. }
  772. if (f & nsIWebProgressListener::STATE_NEGOTIATING)
  773. {
  774. f -= nsIWebProgressListener::STATE_NEGOTIATING;
  775. info.Append("NEGOTIATING ");
  776. }
  777. if (f & nsIWebProgressListener::STATE_STOP)
  778. {
  779. f -= nsIWebProgressListener::STATE_STOP;
  780. info.Append("STOP ");
  781. }
  782. if (f & nsIWebProgressListener::STATE_IS_REQUEST)
  783. {
  784. f -= nsIWebProgressListener::STATE_IS_REQUEST;
  785. info.Append("IS_REQUEST ");
  786. }
  787. if (f & nsIWebProgressListener::STATE_IS_DOCUMENT)
  788. {
  789. f -= nsIWebProgressListener::STATE_IS_DOCUMENT;
  790. info.Append("IS_DOCUMENT ");
  791. }
  792. if (f & nsIWebProgressListener::STATE_IS_NETWORK)
  793. {
  794. f -= nsIWebProgressListener::STATE_IS_NETWORK;
  795. info.Append("IS_NETWORK ");
  796. }
  797. if (f & nsIWebProgressListener::STATE_IS_WINDOW)
  798. {
  799. f -= nsIWebProgressListener::STATE_IS_WINDOW;
  800. info.Append("IS_WINDOW ");
  801. }
  802. if (f & nsIWebProgressListener::STATE_IS_INSECURE)
  803. {
  804. f -= nsIWebProgressListener::STATE_IS_INSECURE;
  805. info.Append("IS_INSECURE ");
  806. }
  807. if (f & nsIWebProgressListener::STATE_IS_BROKEN)
  808. {
  809. f -= nsIWebProgressListener::STATE_IS_BROKEN;
  810. info.Append("IS_BROKEN ");
  811. }
  812. if (f & nsIWebProgressListener::STATE_IS_SECURE)
  813. {
  814. f -= nsIWebProgressListener::STATE_IS_SECURE;
  815. info.Append("IS_SECURE ");
  816. }
  817. if (f & nsIWebProgressListener::STATE_SECURE_HIGH)
  818. {
  819. f -= nsIWebProgressListener::STATE_SECURE_HIGH;
  820. info.Append("SECURE_HIGH ");
  821. }
  822. if (f & nsIWebProgressListener::STATE_SECURE_MED)
  823. {
  824. f -= nsIWebProgressListener::STATE_SECURE_MED;
  825. info.Append("SECURE_MED ");
  826. }
  827. if (f & nsIWebProgressListener::STATE_SECURE_LOW)
  828. {
  829. f -= nsIWebProgressListener::STATE_SECURE_LOW;
  830. info.Append("SECURE_LOW ");
  831. }
  832. if (f & nsIWebProgressListener::STATE_RESTORING)
  833. {
  834. f -= nsIWebProgressListener::STATE_RESTORING;
  835. info.Append("STATE_RESTORING ");
  836. }
  837. if (f > 0)
  838. {
  839. info.Append("f contains unknown flag!");
  840. }
  841. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  842. ("SecureUI:%p: OnStateChange: %s %s -- %s\n", this, _status,
  843. info.get(), info2.get()));
  844. if (aProgressStateFlags & STATE_STOP
  845. &&
  846. channel)
  847. {
  848. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  849. ("SecureUI:%p: OnStateChange: seeing STOP with security state: %d\n", this,
  850. GetSecurityStateFromSecurityInfo(securityInfo)
  851. ));
  852. }
  853. #endif
  854. if (aProgressStateFlags & STATE_TRANSFERRING
  855. &&
  856. aProgressStateFlags & STATE_IS_REQUEST)
  857. {
  858. // The listing of a request in mTransferringRequests
  859. // means, there has already been data transfered.
  860. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  861. PL_DHashTableOperate(&mTransferringRequests, aRequest, PL_DHASH_ADD);
  862. return NS_OK;
  863. }
  864. bool requestHasTransferedData = false;
  865. if (aProgressStateFlags & STATE_STOP
  866. &&
  867. aProgressStateFlags & STATE_IS_REQUEST)
  868. {
  869. { /* scope for the ReentrantMonitorAutoEnter */
  870. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  871. PLDHashEntryHdr *entry = PL_DHashTableOperate(&mTransferringRequests, aRequest, PL_DHASH_LOOKUP);
  872. if (PL_DHASH_ENTRY_IS_BUSY(entry))
  873. {
  874. PL_DHashTableOperate(&mTransferringRequests, aRequest, PL_DHASH_REMOVE);
  875. requestHasTransferedData = true;
  876. }
  877. }
  878. if (!requestHasTransferedData) {
  879. // Because image loads doesn't support any TRANSFERRING notifications but
  880. // only START and STOP we must ask them directly whether content was
  881. // transferred. See bug 432685 for details.
  882. nsCOMPtr<nsISecurityInfoProvider> securityInfoProvider =
  883. do_QueryInterface(aRequest);
  884. // Guess true in all failure cases to be safe. But if we're not
  885. // an nsISecurityInfoProvider, then we just haven't transferred
  886. // any data.
  887. bool hasTransferred;
  888. requestHasTransferedData =
  889. securityInfoProvider &&
  890. (NS_FAILED(securityInfoProvider->GetHasTransferredData(&hasTransferred)) ||
  891. hasTransferred);
  892. }
  893. }
  894. bool allowSecurityStateChange = true;
  895. if (loadFlags & nsIChannel::LOAD_RETARGETED_DOCUMENT_URI)
  896. {
  897. // The original consumer (this) is no longer the target of the load.
  898. // Ignore any events with this flag, do not allow them to update
  899. // our secure UI state.
  900. allowSecurityStateChange = false;
  901. }
  902. if (aProgressStateFlags & STATE_START
  903. &&
  904. aProgressStateFlags & STATE_IS_REQUEST
  905. &&
  906. isToplevelProgress
  907. &&
  908. loadFlags & nsIChannel::LOAD_DOCUMENT_URI)
  909. {
  910. bool inProgress;
  911. PRInt32 saveSubHigh;
  912. PRInt32 saveSubLow;
  913. PRInt32 saveSubBroken;
  914. PRInt32 saveSubNo;
  915. nsCOMPtr<nsIAssociatedContentSecurity> prevContentSecurity;
  916. PRInt32 newSubHigh = 0;
  917. PRInt32 newSubLow = 0;
  918. PRInt32 newSubBroken = 0;
  919. PRInt32 newSubNo = 0;
  920. {
  921. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  922. inProgress = (mDocumentRequestsInProgress!=0);
  923. if (allowSecurityStateChange && !inProgress)
  924. {
  925. saveSubHigh = mSubRequestsHighSecurity;
  926. saveSubLow = mSubRequestsLowSecurity;
  927. saveSubBroken = mSubRequestsBrokenSecurity;
  928. saveSubNo = mSubRequestsNoSecurity;
  929. prevContentSecurity = do_QueryInterface(mCurrentToplevelSecurityInfo);
  930. }
  931. }
  932. if (allowSecurityStateChange && !inProgress)
  933. {
  934. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  935. ("SecureUI:%p: OnStateChange: start for toplevel document\n", this
  936. ));
  937. if (prevContentSecurity)
  938. {
  939. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  940. ("SecureUI:%p: OnStateChange: start, saving current sub state\n", this
  941. ));
  942. // before resetting our state, let's save information about
  943. // sub element loads, so we can restore it later
  944. prevContentSecurity->SetCountSubRequestsHighSecurity(saveSubHigh);
  945. prevContentSecurity->SetCountSubRequestsLowSecurity(saveSubLow);
  946. prevContentSecurity->SetCountSubRequestsBrokenSecurity(saveSubBroken);
  947. prevContentSecurity->SetCountSubRequestsNoSecurity(saveSubNo);
  948. prevContentSecurity->Flush();
  949. }
  950. bool retrieveAssociatedState = false;
  951. if (securityInfo &&
  952. (aProgressStateFlags & nsIWebProgressListener::STATE_RESTORING) != 0) {
  953. retrieveAssociatedState = true;
  954. } else {
  955. nsCOMPtr<nsIWyciwygChannel> wyciwygRequest(do_QueryInterface(aRequest));
  956. if (wyciwygRequest) {
  957. retrieveAssociatedState = true;
  958. }
  959. }
  960. if (retrieveAssociatedState)
  961. {
  962. // When restoring from bfcache, we will not get events for the
  963. // page's sub elements, so let's load the state of sub elements
  964. // from the cache.
  965. nsCOMPtr<nsIAssociatedContentSecurity>
  966. newContentSecurity(do_QueryInterface(securityInfo));
  967. if (newContentSecurity)
  968. {
  969. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  970. ("SecureUI:%p: OnStateChange: start, loading old sub state\n", this
  971. ));
  972. newContentSecurity->GetCountSubRequestsHighSecurity(&newSubHigh);
  973. newContentSecurity->GetCountSubRequestsLowSecurity(&newSubLow);
  974. newContentSecurity->GetCountSubRequestsBrokenSecurity(&newSubBroken);
  975. newContentSecurity->GetCountSubRequestsNoSecurity(&newSubNo);
  976. }
  977. }
  978. }
  979. {
  980. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  981. if (allowSecurityStateChange && !inProgress)
  982. {
  983. ResetStateTracking();
  984. mSubRequestsHighSecurity = newSubHigh;
  985. mSubRequestsLowSecurity = newSubLow;
  986. mSubRequestsBrokenSecurity = newSubBroken;
  987. mSubRequestsNoSecurity = newSubNo;
  988. mNewToplevelSecurityStateKnown = false;
  989. }
  990. // By using a counter, this code also works when the toplevel
  991. // document get's redirected, but the STOP request for the
  992. // previous toplevel document has not yet have been received.
  993. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  994. ("SecureUI:%p: OnStateChange: ++mDocumentRequestsInProgress\n", this
  995. ));
  996. ++mDocumentRequestsInProgress;
  997. }
  998. return NS_OK;
  999. }
  1000. if (aProgressStateFlags & STATE_STOP
  1001. &&
  1002. aProgressStateFlags & STATE_IS_REQUEST
  1003. &&
  1004. isToplevelProgress
  1005. &&
  1006. loadFlags & nsIChannel::LOAD_DOCUMENT_URI)
  1007. {
  1008. PRInt32 temp_DocumentRequestsInProgress;
  1009. nsCOMPtr<nsISecurityEventSink> temp_ToplevelEventSink;
  1010. {
  1011. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1012. temp_DocumentRequestsInProgress = mDocumentRequestsInProgress;
  1013. if (allowSecurityStateChange)
  1014. {
  1015. temp_ToplevelEventSink = mToplevelEventSink;
  1016. }
  1017. }
  1018. if (temp_DocumentRequestsInProgress <= 0)
  1019. {
  1020. // Ignore stop requests unless a document load is in progress
  1021. // Unfortunately on application start, see some stops without having seen any starts...
  1022. return NS_OK;
  1023. }
  1024. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  1025. ("SecureUI:%p: OnStateChange: --mDocumentRequestsInProgress\n", this
  1026. ));
  1027. if (!temp_ToplevelEventSink && channel)
  1028. {
  1029. if (allowSecurityStateChange)
  1030. {
  1031. ObtainEventSink(channel, temp_ToplevelEventSink);
  1032. }
  1033. }
  1034. {
  1035. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1036. if (allowSecurityStateChange)
  1037. {
  1038. mToplevelEventSink = temp_ToplevelEventSink;
  1039. }
  1040. --mDocumentRequestsInProgress;
  1041. }
  1042. if (allowSecurityStateChange && requestHasTransferedData) {
  1043. // Data has been transferred for the single toplevel
  1044. // request. Evaluate the security state.
  1045. return EvaluateAndUpdateSecurityState(aRequest, securityInfo, false);
  1046. }
  1047. return NS_OK;
  1048. }
  1049. if (aProgressStateFlags & STATE_STOP
  1050. &&
  1051. aProgressStateFlags & STATE_IS_REQUEST)
  1052. {
  1053. if (!isSubDocumentRelevant)
  1054. return NS_OK;
  1055. // if we arrive here, LOAD_DOCUMENT_URI is not set
  1056. // We only care for the security state of sub requests which have actually transfered data.
  1057. if (allowSecurityStateChange && requestHasTransferedData)
  1058. {
  1059. UpdateSubrequestMembers(securityInfo);
  1060. // Care for the following scenario:
  1061. // A new top level document load might have already started,
  1062. // but the security state of the new top level document might not yet been known.
  1063. //
  1064. // At this point, we are learning about the security state of a sub-document.
  1065. // We must not update the security state based on the sub content,
  1066. // if the new top level state is not yet known.
  1067. //
  1068. // We skip updating the security state in this case.
  1069. bool temp_NewToplevelSecurityStateKnown;
  1070. {
  1071. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1072. temp_NewToplevelSecurityStateKnown = mNewToplevelSecurityStateKnown;
  1073. }
  1074. if (temp_NewToplevelSecurityStateKnown)
  1075. return UpdateSecurityState(aRequest, false, false, false);
  1076. }
  1077. return NS_OK;
  1078. }
  1079. return NS_OK;
  1080. }
  1081. // I'm keeping this as a separate function, in order to simplify the review
  1082. // for bug 412456. We should inline this in a follow up patch.
  1083. void nsSecureBrowserUIImpl::ObtainEventSink(nsIChannel *channel,
  1084. nsCOMPtr<nsISecurityEventSink> &sink)
  1085. {
  1086. if (!sink)
  1087. NS_QueryNotificationCallbacks(channel, sink);
  1088. }
  1089. nsresult nsSecureBrowserUIImpl::UpdateSecurityState(nsIRequest* aRequest,
  1090. bool withNewLocation,
  1091. bool withUpdateStatus,
  1092. bool withUpdateTooltip)
  1093. {
  1094. lockIconState warnSecurityState = lis_no_security;
  1095. bool showWarning = false;
  1096. nsresult rv = NS_OK;
  1097. // both parameters are both input and outout
  1098. bool flagsChanged = UpdateMyFlags(showWarning, warnSecurityState);
  1099. if (flagsChanged || withNewLocation || withUpdateStatus || withUpdateTooltip)
  1100. rv = TellTheWorld(showWarning, warnSecurityState, aRequest);
  1101. return rv;
  1102. }
  1103. // must not fail, by definition, only trivial assignments
  1104. // or string operations are allowed
  1105. // returns true if our overall state has changed and we must send out notifications
  1106. bool nsSecureBrowserUIImpl::UpdateMyFlags(bool &showWarning, lockIconState &warnSecurityState)
  1107. {
  1108. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1109. bool mustTellTheWorld = false;
  1110. lockIconState newSecurityState;
  1111. if (mNewToplevelSecurityState & STATE_IS_SECURE)
  1112. {
  1113. if (mNewToplevelSecurityState & STATE_SECURE_LOW
  1114. ||
  1115. mNewToplevelSecurityState & STATE_SECURE_MED)
  1116. {
  1117. if (mSubRequestsBrokenSecurity
  1118. ||
  1119. mSubRequestsNoSecurity)
  1120. {
  1121. newSecurityState = lis_mixed_security;
  1122. }
  1123. else
  1124. {
  1125. newSecurityState = lis_low_security;
  1126. }
  1127. }
  1128. else
  1129. {
  1130. // toplevel is high security
  1131. if (mSubRequestsBrokenSecurity
  1132. ||
  1133. mSubRequestsNoSecurity)
  1134. {
  1135. newSecurityState = lis_mixed_security;
  1136. }
  1137. else if (mSubRequestsLowSecurity)
  1138. {
  1139. newSecurityState = lis_low_security;
  1140. }
  1141. else
  1142. {
  1143. newSecurityState = lis_high_security;
  1144. }
  1145. }
  1146. }
  1147. else
  1148. if (mNewToplevelSecurityState & STATE_IS_BROKEN)
  1149. {
  1150. // indicating BROKEN is more important than MIXED.
  1151. newSecurityState = lis_broken_security;
  1152. }
  1153. else
  1154. {
  1155. newSecurityState = lis_no_security;
  1156. }
  1157. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  1158. ("SecureUI:%p: UpdateSecurityState: old-new %d - %d\n", this,
  1159. mNotifiedSecurityState, newSecurityState
  1160. ));
  1161. if (mNotifiedSecurityState != newSecurityState)
  1162. {
  1163. mustTellTheWorld = true;
  1164. // we'll treat "broken" exactly like "insecure",
  1165. // i.e. we do not show alerts when switching between broken and insecure
  1166. /*
  1167. from to shows alert
  1168. ------------------------------ ---------------
  1169. no or broken -> no or broken => <NOTHING SHOWN>
  1170. no or broken -> mixed => mixed alert
  1171. no or broken -> low => low alert
  1172. no or broken -> high => high alert
  1173. mixed, high, low -> no, broken => leaving secure
  1174. mixed -> low => low alert
  1175. mixed -> high => high alert
  1176. high -> low => low alert
  1177. high -> mixed => mixed
  1178. low -> high => high
  1179. low -> mixed => mixed
  1180. security icon
  1181. ----------------
  1182. no open
  1183. mixed broken
  1184. broken broken
  1185. low low
  1186. high high
  1187. */
  1188. showWarning = true;
  1189. switch (mNotifiedSecurityState)
  1190. {
  1191. case lis_no_security:
  1192. case lis_broken_security:
  1193. switch (newSecurityState)
  1194. {
  1195. case lis_no_security:
  1196. case lis_broken_security:
  1197. showWarning = false;
  1198. break;
  1199. default:
  1200. break;
  1201. }
  1202. default:
  1203. break;
  1204. }
  1205. if (showWarning)
  1206. {
  1207. warnSecurityState = newSecurityState;
  1208. }
  1209. mNotifiedSecurityState = newSecurityState;
  1210. if (lis_no_security == newSecurityState)
  1211. {
  1212. mSSLStatus = nsnull;
  1213. mInfoTooltip.Truncate();
  1214. }
  1215. }
  1216. if (mNotifiedToplevelIsEV != mNewToplevelIsEV) {
  1217. mustTellTheWorld = true;
  1218. mNotifiedToplevelIsEV = mNewToplevelIsEV;
  1219. }
  1220. return mustTellTheWorld;
  1221. }
  1222. nsresult nsSecureBrowserUIImpl::TellTheWorld(bool showWarning,
  1223. lockIconState warnSecurityState,
  1224. nsIRequest* aRequest)
  1225. {
  1226. nsCOMPtr<nsISecurityEventSink> temp_ToplevelEventSink;
  1227. lockIconState temp_NotifiedSecurityState;
  1228. bool temp_NotifiedToplevelIsEV;
  1229. {
  1230. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1231. temp_ToplevelEventSink = mToplevelEventSink;
  1232. temp_NotifiedSecurityState = mNotifiedSecurityState;
  1233. temp_NotifiedToplevelIsEV = mNotifiedToplevelIsEV;
  1234. }
  1235. if (temp_ToplevelEventSink)
  1236. {
  1237. PRUint32 newState = STATE_IS_INSECURE;
  1238. MapInternalToExternalState(&newState,
  1239. temp_NotifiedSecurityState,
  1240. temp_NotifiedToplevelIsEV);
  1241. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  1242. ("SecureUI:%p: UpdateSecurityState: calling OnSecurityChange\n", this
  1243. ));
  1244. temp_ToplevelEventSink->OnSecurityChange(aRequest, newState);
  1245. }
  1246. else
  1247. {
  1248. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  1249. ("SecureUI:%p: UpdateSecurityState: NO mToplevelEventSink!\n", this
  1250. ));
  1251. }
  1252. if (showWarning)
  1253. {
  1254. switch (warnSecurityState)
  1255. {
  1256. case lis_no_security:
  1257. case lis_broken_security:
  1258. ConfirmLeavingSecure();
  1259. break;
  1260. case lis_mixed_security:
  1261. ConfirmMixedMode();
  1262. break;
  1263. case lis_low_security:
  1264. ConfirmEnteringWeak();
  1265. break;
  1266. case lis_high_security:
  1267. ConfirmEnteringSecure();
  1268. break;
  1269. }
  1270. }
  1271. return NS_OK;
  1272. }
  1273. NS_IMETHODIMP
  1274. nsSecureBrowserUIImpl::OnLocationChange(nsIWebProgress* aWebProgress,
  1275. nsIRequest* aRequest,
  1276. nsIURI* aLocation,
  1277. PRUint32 aFlags)
  1278. {
  1279. #ifdef DEBUG
  1280. nsAutoAtomic atomic(mOnStateLocationChangeReentranceDetection);
  1281. NS_ASSERTION(mOnStateLocationChangeReentranceDetection == 1,
  1282. "unexpected parallel nsIWebProgress OnStateChange and/or OnLocationChange notification");
  1283. #endif
  1284. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  1285. ("SecureUI:%p: OnLocationChange\n", this));
  1286. bool updateIsViewSource = false;
  1287. bool temp_IsViewSource = false;
  1288. nsCOMPtr<nsIDOMWindow> window;
  1289. if (aLocation)
  1290. {
  1291. bool vs;
  1292. nsresult rv = aLocation->SchemeIs("view-source", &vs);
  1293. NS_ENSURE_SUCCESS(rv, rv);
  1294. if (vs) {
  1295. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  1296. ("SecureUI:%p: OnLocationChange: view-source\n", this));
  1297. }
  1298. updateIsViewSource = true;
  1299. temp_IsViewSource = vs;
  1300. }
  1301. {
  1302. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1303. if (updateIsViewSource) {
  1304. mIsViewSource = temp_IsViewSource;
  1305. }
  1306. mCurrentURI = aLocation;
  1307. window = do_QueryReferent(mWindow);
  1308. NS_ASSERTION(window, "Window has gone away?!");
  1309. }
  1310. // When |aRequest| is null, basically we don't trust that document. But if
  1311. // docshell insists that the document has not changed at all, we will reuse
  1312. // the previous security state, no matter what |aRequest| may be.
  1313. if (aFlags & LOCATION_CHANGE_SAME_DOCUMENT)
  1314. return NS_OK;
  1315. // The location bar has changed, so we must update the security state. The
  1316. // only concern with doing this here is that a page may transition from being
  1317. // reported as completely secure to being reported as partially secure
  1318. // (mixed). This may be confusing for users, and it may bother users who
  1319. // like seeing security dialogs. However, it seems prudent given that page
  1320. // loading may never end in some edge cases (perhaps by a site with malicious
  1321. // intent).
  1322. nsCOMPtr<nsIDOMWindow> windowForProgress;
  1323. aWebProgress->GetDOMWindow(getter_AddRefs(windowForProgress));
  1324. nsCOMPtr<nsISupports> securityInfo(ExtractSecurityInfo(aRequest));
  1325. if (windowForProgress.get() == window.get()) {
  1326. // For toplevel channels, update the security state right away.
  1327. return EvaluateAndUpdateSecurityState(aRequest, securityInfo, true);
  1328. }
  1329. // For channels in subdocuments we only update our subrequest state members.
  1330. UpdateSubrequestMembers(securityInfo);
  1331. // Care for the following scenario:
  1332. // A new toplevel document load might have already started, but the security
  1333. // state of the new toplevel document might not yet be known.
  1334. //
  1335. // At this point, we are learning about the security state of a sub-document.
  1336. // We must not update the security state based on the sub content, if the new
  1337. // top level state is not yet known.
  1338. //
  1339. // We skip updating the security state in this case.
  1340. bool temp_NewToplevelSecurityStateKnown;
  1341. {
  1342. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1343. temp_NewToplevelSecurityStateKnown = mNewToplevelSecurityStateKnown;
  1344. }
  1345. if (temp_NewToplevelSecurityStateKnown)
  1346. return UpdateSecurityState(aRequest, true, false, false);
  1347. return NS_OK;
  1348. }
  1349. NS_IMETHODIMP
  1350. nsSecureBrowserUIImpl::OnStatusChange(nsIWebProgress* aWebProgress,
  1351. nsIRequest* aRequest,
  1352. nsresult aStatus,
  1353. const PRUnichar* aMessage)
  1354. {
  1355. NS_NOTREACHED("notification excluded in AddProgressListener(...)");
  1356. return NS_OK;
  1357. }
  1358. nsresult
  1359. nsSecureBrowserUIImpl::OnSecurityChange(nsIWebProgress *aWebProgress,
  1360. nsIRequest *aRequest,
  1361. PRUint32 state)
  1362. {
  1363. #if defined(DEBUG)
  1364. nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
  1365. if (!channel)
  1366. return NS_OK;
  1367. nsCOMPtr<nsIURI> aURI;
  1368. channel->GetURI(getter_AddRefs(aURI));
  1369. if (aURI) {
  1370. nsCAutoString temp;
  1371. aURI->GetSpec(temp);
  1372. PR_LOG(gSecureDocLog, PR_LOG_DEBUG,
  1373. ("SecureUI:%p: OnSecurityChange: (%x) %s\n", this,
  1374. state, temp.get()));
  1375. }
  1376. #endif
  1377. return NS_OK;
  1378. }
  1379. // nsISSLStatusProvider methods
  1380. NS_IMETHODIMP
  1381. nsSecureBrowserUIImpl::GetSSLStatus(nsISSLStatus** _result)
  1382. {
  1383. NS_ENSURE_ARG_POINTER(_result);
  1384. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1385. switch (mNotifiedSecurityState)
  1386. {
  1387. case lis_mixed_security:
  1388. case lis_low_security:
  1389. case lis_high_security:
  1390. break;
  1391. default:
  1392. NS_NOTREACHED("if this is reached you must add more entries to the switch");
  1393. case lis_no_security:
  1394. case lis_broken_security:
  1395. *_result = nsnull;
  1396. return NS_OK;
  1397. }
  1398. *_result = mSSLStatus;
  1399. NS_IF_ADDREF(*_result);
  1400. return NS_OK;
  1401. }
  1402. nsresult
  1403. nsSecureBrowserUIImpl::IsURLHTTPS(nsIURI* aURL, bool* value)
  1404. {
  1405. *value = false;
  1406. if (!aURL)
  1407. return NS_OK;
  1408. return aURL->SchemeIs("https", value);
  1409. }
  1410. nsresult
  1411. nsSecureBrowserUIImpl::IsURLJavaScript(nsIURI* aURL, bool* value)
  1412. {
  1413. *value = false;
  1414. if (!aURL)
  1415. return NS_OK;
  1416. return aURL->SchemeIs("javascript", value);
  1417. }
  1418. void
  1419. nsSecureBrowserUIImpl::GetBundleString(const PRUnichar* name,
  1420. nsAString &outString)
  1421. {
  1422. nsCOMPtr<nsIStringBundle> temp_StringBundle;
  1423. {
  1424. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1425. temp_StringBundle = mStringBundle;
  1426. }
  1427. if (temp_StringBundle && name) {
  1428. PRUnichar *ptrv = nsnull;
  1429. if (NS_SUCCEEDED(temp_StringBundle->GetStringFromName(name,
  1430. &ptrv)))
  1431. outString = ptrv;
  1432. else
  1433. outString.SetLength(0);
  1434. nsMemory::Free(ptrv);
  1435. } else {
  1436. outString.SetLength(0);
  1437. }
  1438. }
  1439. nsresult
  1440. nsSecureBrowserUIImpl::CheckPost(nsIURI *formURL, nsIURI *actionURL, bool *okayToPost)
  1441. {
  1442. bool formSecure, actionSecure, actionJavaScript;
  1443. *okayToPost = true;
  1444. nsresult rv = IsURLHTTPS(formURL, &formSecure);
  1445. if (NS_FAILED(rv))
  1446. return rv;
  1447. rv = IsURLHTTPS(actionURL, &actionSecure);
  1448. if (NS_FAILED(rv))
  1449. return rv;
  1450. rv = IsURLJavaScript(actionURL, &actionJavaScript);
  1451. if (NS_FAILED(rv))
  1452. return rv;
  1453. // If we are posting to a secure link, all is okay.
  1454. // It doesn't matter whether the currently viewed page is secure or not,
  1455. // because the data will be sent to a secure URL.
  1456. if (actionSecure) {
  1457. return NS_OK;
  1458. }
  1459. // Action is a JavaScript call, not an actual post. That's okay too.
  1460. if (actionJavaScript) {
  1461. return NS_OK;
  1462. }
  1463. // posting to insecure webpage from a secure webpage.
  1464. if (formSecure) {
  1465. *okayToPost = ConfirmPostToInsecureFromSecure();
  1466. } else {
  1467. *okayToPost = ConfirmPostToInsecure();
  1468. }
  1469. return NS_OK;
  1470. }
  1471. //
  1472. // Implementation of an nsIInterfaceRequestor for use
  1473. // as context for NSS calls
  1474. //
  1475. class nsUIContext : public nsIInterfaceRequestor
  1476. {
  1477. public:
  1478. NS_DECL_ISUPPORTS
  1479. NS_DECL_NSIINTERFACEREQUESTOR
  1480. nsUIContext(nsIDOMWindow *window);
  1481. virtual ~nsUIContext();
  1482. private:
  1483. nsCOMPtr<nsIDOMWindow> mWindow;
  1484. };
  1485. NS_IMPL_ISUPPORTS1(nsUIContext, nsIInterfaceRequestor)
  1486. nsUIContext::nsUIContext(nsIDOMWindow *aWindow)
  1487. : mWindow(aWindow)
  1488. {
  1489. }
  1490. nsUIContext::~nsUIContext()
  1491. {
  1492. }
  1493. /* void getInterface (in nsIIDRef uuid, [iid_is (uuid), retval] out nsQIResult result); */
  1494. NS_IMETHODIMP nsUIContext::GetInterface(const nsIID & uuid, void * *result)
  1495. {
  1496. NS_ENSURE_TRUE(mWindow, NS_ERROR_FAILURE);
  1497. nsresult rv;
  1498. if (uuid.Equals(NS_GET_IID(nsIPrompt))) {
  1499. nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(mWindow, &rv);
  1500. if (NS_FAILED(rv)) return rv;
  1501. nsIPrompt *prompt;
  1502. rv = window->GetPrompter(&prompt);
  1503. *result = prompt;
  1504. } else if (uuid.Equals(NS_GET_IID(nsIDOMWindow))) {
  1505. *result = mWindow;
  1506. NS_ADDREF ((nsISupports*) *result);
  1507. rv = NS_OK;
  1508. } else {
  1509. rv = NS_ERROR_NO_INTERFACE;
  1510. }
  1511. return rv;
  1512. }
  1513. bool
  1514. nsSecureBrowserUIImpl::GetNSSDialogs(nsCOMPtr<nsISecurityWarningDialogs> & dialogs,
  1515. nsCOMPtr<nsIInterfaceRequestor> & ctx)
  1516. {
  1517. if (!NS_IsMainThread()) {
  1518. NS_ERROR("nsSecureBrowserUIImpl::GetNSSDialogs called off the main thread");
  1519. return false;
  1520. }
  1521. dialogs = do_GetService(NS_SECURITYWARNINGDIALOGS_CONTRACTID);
  1522. if (!dialogs)
  1523. return false;
  1524. nsCOMPtr<nsIDOMWindow> window;
  1525. {
  1526. ReentrantMonitorAutoEnter lock(mReentrantMonitor);
  1527. window = do_QueryReferent(mWindow);
  1528. NS_ASSERTION(window, "Window has gone away?!");
  1529. }
  1530. ctx = new nsUIContext(window);
  1531. return true;
  1532. }
  1533. bool nsSecureBrowserUIImpl::
  1534. ConfirmEnteringSecure()
  1535. {
  1536. nsCOMPtr<nsISecurityWarningDialogs> dialogs;
  1537. nsCOMPtr<nsIInterfaceRequestor> ctx;
  1538. if (!GetNSSDialogs(dialogs, ctx)) {
  1539. return false; // Should this allow true for unimplemented?
  1540. }
  1541. bool confirms;
  1542. dialogs->ConfirmEnteringSecure(ctx, &confirms);
  1543. return confirms;
  1544. }
  1545. bool nsSecureBrowserUIImpl::
  1546. ConfirmEnteringWeak()
  1547. {
  1548. nsCOMPtr<nsISecurityWarningDialogs> dialogs;
  1549. nsCOMPtr<nsIInterfaceRequestor> ctx;
  1550. if (!GetNSSDialogs(dialogs, ctx)) {
  1551. return false; // Should this allow true for unimplemented?
  1552. }
  1553. bool confirms;
  1554. dialogs->ConfirmEnteringWeak(ctx, &confirms);
  1555. return confirms;
  1556. }
  1557. bool nsSecureBrowserUIImpl::
  1558. ConfirmLeavingSecure()
  1559. {
  1560. nsCOMPtr<nsISecurityWarningDialogs> dialogs;
  1561. nsCOMPtr<nsIInterfaceRequestor> ctx;
  1562. if (!GetNSSDialogs(dialogs, ctx)) {
  1563. return false; // Should this allow true for unimplemented?
  1564. }
  1565. bool confirms;
  1566. dialogs->ConfirmLeavingSecure(ctx, &confirms);
  1567. return confirms;
  1568. }
  1569. bool nsSecureBrowserUIImpl::
  1570. ConfirmMixedMode()
  1571. {
  1572. nsCOMPtr<nsISecurityWarningDialogs> dialogs;
  1573. nsCOMPtr<nsIInterfaceRequestor> ctx;
  1574. if (!GetNSSDialogs(dialogs, ctx)) {
  1575. return false; // Should this allow true for unimplemented?
  1576. }
  1577. bool confirms;
  1578. dialogs->ConfirmMixedMode(ctx, &confirms);
  1579. return confirms;
  1580. }
  1581. /**
  1582. * ConfirmPostToInsecure - returns true if
  1583. * the user approves the submit (or doesn't care).
  1584. * returns false on errors.
  1585. */
  1586. bool nsSecureBrowserUIImpl::
  1587. ConfirmPostToInsecure()
  1588. {
  1589. nsCOMPtr<nsISecurityWarningDialogs> dialogs;
  1590. nsCOMPtr<nsIInterfaceRequestor> ctx;
  1591. if (!GetNSSDialogs(dialogs, ctx)) {
  1592. return false; // Should this allow true for unimplemented?
  1593. }
  1594. bool result;
  1595. nsresult rv = dialogs->ConfirmPostToInsecure(ctx, &result);
  1596. if (NS_FAILED(rv)) return false;
  1597. return result;
  1598. }
  1599. /**
  1600. * ConfirmPostToInsecureFromSecure - returns true if
  1601. * the user approves the submit (or doesn't care).
  1602. * returns false on errors.
  1603. */
  1604. bool nsSecureBrowserUIImpl::
  1605. ConfirmPostToInsecureFromSecure()
  1606. {
  1607. nsCOMPtr<nsISecurityWarningDialogs> dialogs;
  1608. nsCOMPtr<nsIInterfaceRequestor> ctx;
  1609. if (!GetNSSDialogs(dialogs, ctx)) {
  1610. return false; // Should this allow true for unimplemented?
  1611. }
  1612. bool result;
  1613. nsresult rv = dialogs->ConfirmPostToInsecureFromSecure(ctx, &result);
  1614. if (NS_FAILED(rv)) return false;
  1615. return result;
  1616. }