From fd2ff00a6efb53302d9699aaeaee465f3f7da597 Mon Sep 17 00:00:00 2001
From: downtownallday <downtownallday@gmail.com>
Date: Sat, 29 Jan 2022 15:22:01 -0500
Subject: [PATCH] Use persistent_login plugin's "Auth Token" support for
 Roundcube. The old way was very insecure and is subject to dictionary attack
 of the unsalted encrypted password stored in a browser cookie.

---
 conf/persistent_login-sqlite.sql | 14 ++++++++++++++
 setup/webmail.sh                 | 15 +++++++++++++++
 2 files changed, 29 insertions(+)
 create mode 100644 conf/persistent_login-sqlite.sql

diff --git a/conf/persistent_login-sqlite.sql b/conf/persistent_login-sqlite.sql
new file mode 100644
index 00000000..5bffc9a6
--- /dev/null
+++ b/conf/persistent_login-sqlite.sql
@@ -0,0 +1,14 @@
+PRAGMA foreign_keys = ON;
+
+CREATE TABLE IF NOT EXISTS `auth_tokens` (
+    `token` TEXT NOT NULL,
+    `expires` TEXT NOT NULL,
+    `user_id` INTEGER NOT NULL,
+    `user_name` TEXT NOT NULL,
+    `user_pass` TEXT NOT NULL,
+    `host` TEXT NOT NULL,
+    PRIMARY KEY(`token`),
+    FOREIGN KEY(`user_id`) REFERENCES `users`(`user_id`) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS `user_id_fk_auth_tokens` ON `auth_tokens`(`user_id`);
diff --git a/setup/webmail.sh b/setup/webmail.sh
index 63586d81..1e1740c2 100755
--- a/setup/webmail.sh
+++ b/setup/webmail.sh
@@ -195,6 +195,15 @@ cat > ${RCM_PLUGIN_DIR}/carddav/config.inc.php <<EOF;
 ?>
 EOF
 
+# Configure persistent_login (required database tables are created
+# later in this script)
+cat > ${RCM_PLUGIN_DIR}/persistent_login/config.inc.php <<EOF
+<?php
+/* Do not edit. Written by Mail-in-a-Box. Regenerated on updates. */
+\$rcmail_config['ifpl_use_auth_tokens'] = true;  # enable AuthToken cookies
+?>
+EOF
+
 # Create writable directories.
 mkdir -p /var/log/roundcubemail /var/tmp/roundcubemail $STORAGE_ROOT/mail/roundcube
 chown -R www-data.www-data /var/log/roundcubemail /var/tmp/roundcubemail $STORAGE_ROOT/mail/roundcube
@@ -235,6 +244,12 @@ ${RCM_DIR}/bin/updatedb.sh --dir ${RCM_DIR}/SQL --package roundcube
 chown www-data:www-data $STORAGE_ROOT/mail/roundcube/roundcube.sqlite
 chmod 664 $STORAGE_ROOT/mail/roundcube/roundcube.sqlite
 
+# Create persistent login plugin's database tables
+#   TODO: use sql from this PR if it gets committed (been waiting 2
+#         weeks and counting...):
+#     https://github.com/mfreiholz/persistent_login/pull/63
+sqlite3 $STORAGE_ROOT/mail/roundcube/roundcube.sqlite < conf/persistent_login-sqlite.sql
+
 # Enable PHP modules.
 phpenmod -v php mcrypt imap ldap
 restart_service php7.2-fpm