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