332c93
diff --git a/security/manager/ssl/nsNSSComponent.cpp b/security/manager/ssl/nsNSSComponent.cpp
332c93
--- a/security/manager/ssl/nsNSSComponent.cpp
332c93
+++ b/security/manager/ssl/nsNSSComponent.cpp
332c93
@@ -1654,6 +1654,51 @@
332c93
   }
332c93
   return AttemptToRenamePKCS11ModuleDB(profilePath, sqlModuleDBFilename);
332c93
 }
332c93
+
332c93
+// When we changed from the old dbm database format to the newer sqlite
332c93
+// implementation, the upgrade process left behind the existing files. Suppose a
332c93
+// user had not set a password for the old key3.db (which is about 99% of
332c93
+// users). After upgrading, both the old database and the new database are
332c93
+// unprotected. If the user then sets a password for the new database, the old
332c93
+// one will not be protected. In this scenario, we should probably just remove
332c93
+// the old database (it would only be relevant if the user downgraded to a
332c93
+// version of Firefox before 58, but we have to trade this off against the
332c93
+// user's old private keys being unexpectedly unprotected after setting a
332c93
+// password).
332c93
+// This was never an issue on Android because we always used the new
332c93
+// implementation.
332c93
+static void
332c93
+MaybeCleanUpOldNSSFiles(const nsACString& profilePath)
332c93
+{
332c93
+  UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
332c93
+  if (!slot) {
332c93
+    return;
332c93
+  }
332c93
+  // Unfortunately we can't now tell the difference between "there already was a
332c93
+  // password when the upgrade happened" and "there was not a password but then
332c93
+  // the user added one after upgrading".
332c93
+  bool hasPassword = PK11_NeedLogin(slot.get()) &&
332c93
+                     !PK11_NeedUserInit(slot.get());
332c93
+  if (!hasPassword) {
332c93
+    return;
332c93
+  }
332c93
+  nsCOMPtr<nsIFile> dbFile = do_CreateInstance("@mozilla.org/file/local;1");
332c93
+  if (!dbFile) {
332c93
+    return;
332c93
+  }
332c93
+  nsresult rv = dbFile->InitWithNativePath(profilePath);
332c93
+  if (NS_FAILED(rv)) {
332c93
+    return;
332c93
+  }
332c93
+  NS_NAMED_LITERAL_CSTRING(keyDBFilename, "key3.db");
332c93
+  rv = dbFile->AppendNative(keyDBFilename);
332c93
+  if (NS_FAILED(rv)) {
332c93
+    return;
332c93
+  }
332c93
+  // Since this isn't a directory, the `recursive` argument to `Remove` is
332c93
+  // irrelevant.
332c93
+  Unused << dbFile->Remove(false);
332c93
+}
332c93
 #endif // ifndef ANDROID
332c93
 
332c93
 // Given a profile directory, attempt to initialize NSS. If nocertdb is true,
332c93
@@ -1685,6 +1730,9 @@
332c93
   SECStatus srv = ::mozilla::psm::InitializeNSS(profilePath, false, !safeMode);
332c93
   if (srv == SECSuccess) {
332c93
     MOZ_LOG(gPIPNSSLog, LogLevel::Debug, ("initialized NSS in r/w mode"));
332c93
+#ifndef ANDROID
332c93
+    MaybeCleanUpOldNSSFiles(profilePath);
332c93
+#endif // ifndef ANDROID
332c93
     return NS_OK;
332c93
   }
332c93
 #ifndef ANDROID
332c93