From 23fc7b3fe628252d1969df7bd72ab125a7792e28 Mon Sep 17 00:00:00 2001 From: Daniel Winzen Date: Sun, 11 Oct 2026 18:23:31 +0200 Subject: [PATCH] Add TOTP 2FA --- common_config.php | 96 +++++++++++++++++++++++++++++-- composer.json | 4 +- setup.php | 14 +++-- www/admin.php | 118 +++++++++++++++++++++++++++++++++++---- www/manage_account.php | 124 ++++++++++++++++++++++++++++++++++++----- 5 files changed, 322 insertions(+), 34 deletions(-) diff --git a/common_config.php b/common_config.php index 34d53bd..02ac4f7 100644 --- a/common_config.php +++ b/common_config.php @@ -9,7 +9,7 @@ const DBHOST = 'localhost'; // Database host const DBUSER = 'postfix'; // Database user const DBPASS = 'YOUR_PASSWORD'; // Database password const DBNAME = 'postfix'; // Database -const DBVERSION = 2; // Database schema version +const DBVERSION = 3; // Database schema version const PERSISTENT = true; // persistent database connection const CAPTCHA_DIFFICULTY = 1; // captcha difficulty from 0 to 4 const RESERVED_USERNAMES = ['about', 'abuse', 'admin', 'administrator', 'billing', 'contact', 'daemon', 'ftp', 'help', 'hostmaster', 'info', 'legal', 'list', 'list-request', 'lists', 'maildaemon', 'mailerdaemon', 'mailer-daemon', 'marketing', 'media', 'news', 'newsletter', 'nobody', 'noc', 'noreply', 'no-reply', 'notification', 'notifications', 'notify', 'offer', 'offers', 'office', 'official', 'order', 'orders', 'phish', 'phishing', 'postmaster', 'root', 'sale', 'sales', 'security', 'service', 'services', 'shop', 'shopping', 'spam', 'staff', 'support', 'survey', 'system', 'team', 'teams', 'unsbubscribe', 'uucp', 'usenet', 'user', 'username', 'users', 'web', 'webmail', 'webmaster', 'webmasters', 'welcome', 'www']; // list of reserved usernames that can mot be used on public registration @@ -127,6 +127,97 @@ function z_base32_encode( string $input ): string return $base32; } +function totp_base32_encode( string $input ): string +{ + $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + $encoded = ''; + $buffer = 0; + $bits = 0; + for ( $i = 0, $length = strlen( $input ); $i < $length; ++$i ) { + $buffer = ( $buffer << 8 ) | ord( $input[ $i ] ); + $bits += 8; + while ( $bits >= 5 ) { + $bits -= 5; + $encoded .= $alphabet[ ( $buffer >> $bits ) & 31 ]; + } + $buffer &= ( 1 << $bits ) - 1; + } + if ( $bits > 0 ) { + $encoded .= $alphabet[ ( $buffer << ( 5 - $bits ) ) & 31 ]; + } + return $encoded; +} + +function totp_base32_decode( string $input ): string|false +{ + $input = strtoupper( rtrim( $input, '=' ) ); + if ( $input === '' || ! preg_match( '/^[A-Z2-7]+$/', $input ) ) { + return false; + } + $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + $decoded = ''; + $buffer = 0; + $bits = 0; + for ( $i = 0, $length = strlen( $input ); $i < $length; ++$i ) { + $buffer = ( $buffer << 5 ) | strpos( $alphabet, $input[ $i ] ); + $bits += 5; + if ( $bits >= 8 ) { + $bits -= 8; + $decoded .= chr( ( $buffer >> $bits ) & 255 ); + } + $buffer &= ( 1 << $bits ) - 1; + } + return $decoded === '' ? false : $decoded; +} + +function generate_totp_secret(): string +{ + return totp_base32_encode( random_bytes( 20 ) ); +} + +function get_totp_provisioning_uri( string $account, string $secret ): string +{ + $issuer = 'Mail Hosting'; + $label = rawurlencode( "$issuer:$account" ); + return "otpauth://totp/$label?secret=" . rawurlencode( $secret ) . '&issuer=' . rawurlencode( $issuer ) . '&algorithm=SHA1&digits=6&period=30'; +} + +function get_totp_qr_data_uri( string $totp_uri ): string +{ + $qrCode = \Endroid\QrCode\QrCode::create( $totp_uri ) + ->setSize( 220 ) + ->setMargin( 8 ); + return ( new \Endroid\QrCode\Writer\PngWriter() )->write( $qrCode )->getDataUri(); +} + +function verify_totp_code( string $secret, mixed $code, ?int $time = null ): bool +{ + if ( ! is_string( $code ) || ! preg_match( '/^[0-9]{6}$/', $code ) ) { + return false; + } + $key = totp_base32_decode( $secret ); + if ( $key === false ) { + return false; + } + $time ??= time(); + $counter = intdiv( $time, 30 ); + for ( $offset = -1; $offset <= 1; ++$offset ) { + $step = $counter + $offset; + $counter_bytes = pack( 'N2', ( $step >> 32 ) & 0xffffffff, $step & 0xffffffff ); + $hash = hash_hmac( 'sha1', $counter_bytes, $key, true ); + $offset_byte = ord( $hash[ 19 ] ) & 0x0f; + $binary = ( ( ord( $hash[ $offset_byte ] ) & 0x7f ) << 24 ) + | ( ( ord( $hash[ $offset_byte + 1 ] ) & 0xff ) << 16 ) + | ( ( ord( $hash[ $offset_byte + 2 ] ) & 0xff ) << 8 ) + | ( ord( $hash[ $offset_byte + 3 ] ) & 0xff ); + $expected = str_pad( (string) ( $binary % 1000000 ), 6, '0', STR_PAD_LEFT ); + if ( hash_equals( $expected, $code ) ) { + return true; + } + } + return false; +} + function send_captcha(): void { if ( CAPTCHA_DIFFICULTY === 0 || ! extension_loaded( 'gd' ) ) { @@ -195,7 +286,6 @@ function send_captcha(): void $im = imagerotate($im, $deg, $bg); $im = imagecrop($im, array('x'=>0, 'y'=>0, 'width'=>120, 'height'=>80)); imagecopy($background, $im, 0, 0, 0, 0, 110, 80); - imagedestroy($im); $im = $background; for($i=0; $i<1000; ++$i){ @@ -203,7 +293,6 @@ function send_captcha(): void $dots = imagecolorallocate($im, $c, $c, $c); imagesetpixel($im, mt_rand(0, 120), mt_rand(0, 80), $dots); } - imagedestroy($char); echo ''; echo '
'; } diff --git a/composer.json b/composer.json index dfb7451..db1dfb1 100644 --- a/composer.json +++ b/composer.json @@ -5,6 +5,8 @@ "ext-pdo": "*", "ext-gnupg": "*", "ext-gettext": "*", - "ext-intl": "*" + "ext-intl": "*", + "endroid/qr-code": "^5.0", + "ext-gd": "*" } } diff --git a/setup.php b/setup.php index c7ea5b4..0241fc6 100644 --- a/setup.php +++ b/setup.php @@ -24,7 +24,7 @@ try{ } } $createTableStatements = [ - 'admin' => "CREATE TABLE IF NOT EXISTS `admin` (`username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `superadmin` tinyint(1) NOT NULL DEFAULT 0, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `password_hash_type` varchar(20) NOT NULL DEFAULT '{MD5-CRYPT}', PRIMARY KEY (`username`), KEY `active` (`active`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", + 'admin' => "CREATE TABLE IF NOT EXISTS `admin` (`username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `superadmin` tinyint(1) NOT NULL DEFAULT 0, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `password_hash_type` varchar(20) NOT NULL DEFAULT '{MD5-CRYPT}', `totp_secret` varchar(64) DEFAULT NULL, PRIMARY KEY (`username`), KEY `active` (`active`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'domain' => "CREATE TABLE IF NOT EXISTS `domain` (`domain` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`domain`), KEY `active` (`active`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'alias' => "CREATE TABLE IF NOT EXISTS `alias` (`address` varchar(255) NOT NULL, `goto` text NOT NULL, `domain` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `enforce_tls_in` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`address`), KEY `domain` (`domain`), KEY `active` (`active`), CONSTRAINT `alias_ibfk_1` FOREIGN KEY (`domain`) REFERENCES `domain` (`domain`) ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'alias_domain' => "CREATE TABLE IF NOT EXISTS `alias_domain` (`alias_domain` varchar(255) NOT NULL DEFAULT '', `target_domain` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`alias_domain`), KEY `active` (`active`), KEY `target_domain` (`target_domain`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", @@ -36,7 +36,7 @@ $createTableStatements = [ 'dmarc_report_record_reason' => "CREATE TABLE IF NOT EXISTS `dmarc_report_record_reason` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `record_id` bigint(20) unsigned NOT NULL, `type` varchar(255) NOT NULL, `comment` varchar(255) NOT NULL, PRIMARY KEY (`id`), KEY `record_id` (`record_id`), CONSTRAINT `dmarc_report_record_reason_ibfk_1` FOREIGN KEY (`record_id`) REFERENCES `dmarc_report_records` (`id`) ON DELETE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'dmarc_report_record_spf_result' => "CREATE TABLE IF NOT EXISTS `dmarc_report_record_spf_result` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `record_id` bigint(20) unsigned NOT NULL, `domain` varchar(255) NOT NULL, `result` varchar(255) NOT NULL, `scope` varchar(255) NOT NULL, PRIMARY KEY (`id`), KEY `record_id` (`record_id`), CONSTRAINT `dmarc_report_record_spf_result_ibfk_2` FOREIGN KEY (`record_id`) REFERENCES `dmarc_report_records` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;", 'domain_admins' => "CREATE TABLE IF NOT EXISTS `domain_admins` (`username` varchar(255) NOT NULL, `domain` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `id` bigint(20) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`), KEY `username` (`username`), KEY `active` (`active`), KEY `domain` (`domain`), CONSTRAINT `domain_admins_ibfk_1` FOREIGN KEY (`domain`) REFERENCES `domain` (`domain`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `domain_admins_ibfk_2` FOREIGN KEY (`username`) REFERENCES `admin` (`username`) ON DELETE CASCADE ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", - 'mailbox' => "CREATE TABLE IF NOT EXISTS `mailbox` (`username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL DEFAULT '', `quota` bigint(20) NOT NULL DEFAULT 0, `local_part` varchar(255) NOT NULL DEFAULT '', `domain` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL DEFAULT current_timestamp(), `modified` datetime NOT NULL DEFAULT current_timestamp(), `active` tinyint(1) NOT NULL DEFAULT 1, `password_hash_type` varchar(20) NOT NULL DEFAULT '', `openpgpkey_wkd` char(32) NOT NULL DEFAULT '', `pgp_key` text DEFAULT NULL, `pgp_verified` tinyint(1) NOT NULL DEFAULT 0, `tfa` tinyint(1) NOT NULL DEFAULT 0, `last_login` bigint(20) unsigned DEFAULT NULL, `enforce_tls_in` tinyint(1) NOT NULL DEFAULT 1, `enforce_tls_out` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`username`), KEY `domain` (`domain`), KEY `active` (`active`), KEY `openpgpkey_wkd` (`openpgpkey_wkd`), CONSTRAINT `mailbox_ibfk_2` FOREIGN KEY (`domain`) REFERENCES `domain` (`domain`) ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", + 'mailbox' => "CREATE TABLE IF NOT EXISTS `mailbox` (`username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL DEFAULT '', `quota` bigint(20) NOT NULL DEFAULT 0, `local_part` varchar(255) NOT NULL DEFAULT '', `domain` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL DEFAULT current_timestamp(), `modified` datetime NOT NULL DEFAULT current_timestamp(), `active` tinyint(1) NOT NULL DEFAULT 1, `password_hash_type` varchar(20) NOT NULL DEFAULT '', `openpgpkey_wkd` char(32) NOT NULL DEFAULT '', `pgp_key` text DEFAULT NULL, `pgp_verified` tinyint(1) NOT NULL DEFAULT 0, `tfa` tinyint(1) NOT NULL DEFAULT 0, `totp_secret` varchar(64) DEFAULT NULL, `last_login` bigint(20) unsigned DEFAULT NULL, `enforce_tls_in` tinyint(1) NOT NULL DEFAULT 1, `enforce_tls_out` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`username`), KEY `domain` (`domain`), KEY `active` (`active`), KEY `openpgpkey_wkd` (`openpgpkey_wkd`), CONSTRAINT `mailbox_ibfk_2` FOREIGN KEY (`domain`) REFERENCES `domain` (`domain`) ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'monitored_mailboxes' => "CREATE TABLE IF NOT EXISTS `monitored_mailboxes` (`username` varchar(255) NOT NULL, `last_login` int(11) NOT NULL, PRIMARY KEY (`username`), KEY `lastlogin` (`last_login`), CONSTRAINT `monitored_mailboxes_ibfk_1` FOREIGN KEY (`username`) REFERENCES `mailbox` (`username`) ON DELETE CASCADE ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'tls_report' => "CREATE TABLE IF NOT EXISTS `tls_report` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `report_id` varchar(255) NOT NULL, `organization` varchar(255) NOT NULL, `contact` varchar(255) NOT NULL, `start` datetime NOT NULL, `end` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `report_id_organization` (`report_id`,`organization`), KEY `start_end` (`start`,`end`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'tls_report_policy' => "CREATE TABLE IF NOT EXISTS `tls_report_policy` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `report_id` bigint(20) unsigned NOT NULL, `policy_type` varchar(255) NOT NULL, `policy_string` text NOT NULL, `policy_domain` varchar(255) NOT NULL, `mx_host` text NOT NULL, `success` int(11) NOT NULL, `failure` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `report_id` (`report_id`), KEY `policy_domain` (`policy_domain`), CONSTRAINT `tls_report_policy_ibfk_1` FOREIGN KEY (`report_id`) REFERENCES `tls_report` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `tls_report_policy_ibfk_3` FOREIGN KEY (`policy_domain`) REFERENCES `domain` (`domain`) ON DELETE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", @@ -49,8 +49,14 @@ try{ $version=$stmt->fetch(PDO::FETCH_NUM)[0]; try { foreach($createTableStatements as $tableName => $statement){ - if ($tableName !== 'settings') { - $db->exec($statement); + $db->exec($statement); + } + if ( (int) $version < 3 ) { + foreach ( [ 'admin', 'mailbox' ] as $tableName ) { + $stmt = $db->query( "SHOW COLUMNS FROM `$tableName` LIKE 'totp_secret';" ); + if ( ! $stmt->fetch() ) { + $db->exec( "ALTER TABLE `$tableName` ADD COLUMN `totp_secret` varchar(64) DEFAULT NULL;" ); + } } } $db->beginTransaction(); diff --git a/www/admin.php b/www/admin.php index dec9c34..29629bb 100644 --- a/www/admin.php +++ b/www/admin.php @@ -26,7 +26,23 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { if ( $_SESSION[ 'csrf_token' ] !== $_POST[ 'csrf_token' ] ?? '' ) { die( 'Invalid CSRF token' ); } - if ( $_POST[ 'action' ] === 'logout' ) { + if ( ! empty( $_SESSION[ 'admin_totp_pending' ] ) ) { + $stmt = $db->prepare( 'SELECT username, superadmin, totp_secret FROM admin WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'admin_totp_pending' ] ] ); + $pending = $stmt->fetch( PDO::FETCH_ASSOC ); + if ( $pending && ! empty( $pending[ 'totp_secret' ] ) && verify_totp_code( $pending[ 'totp_secret' ], $_POST[ 'totp_code' ] ?? '' ) ) { + unset( $_SESSION[ 'admin_totp_pending' ] ); + session_regenerate_id( true ); + $_SESSION[ 'csrf_token' ] = sha1( uniqid() ); + $_SESSION[ 'email_admin_user' ] = $pending[ 'username' ]; + $_SESSION[ 'email_admin_superadmin' ] = (bool) $pending[ 'superadmin' ]; + } elseif ( ! $pending || empty( $pending[ 'totp_secret' ] ) ) { + unset( $_SESSION[ 'admin_totp_pending' ] ); + $msg .= ''; + } else { + $msg .= ''; + } + } elseif ( $_POST[ 'action' ] === 'logout' ) { $_SESSION = []; session_regenerate_id( true ); $_SESSION[ 'csrf_token' ] = sha1( uniqid() ); @@ -42,25 +58,55 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $msg .= ''; } if ( $ok ) { - $stmt = $db->prepare( 'SELECT username, password, password_hash_type, superadmin FROM admin WHERE username = ? AND active = 1;' ); + $stmt = $db->prepare( 'SELECT username, password, password_hash_type, superadmin, totp_secret FROM admin WHERE username = ? AND active = 1;' ); $stmt->execute( [ $_POST[ 'user' ] ] ); if ( $tmp = $stmt->fetch( PDO::FETCH_ASSOC ) ) { if ( empty( $_POST[ 'pwd' ] ) || ! password_verify( $_POST[ 'pwd' ], $tmp[ 'password' ] ) ) { $msg .= ''; } else { - $_SESSION[ 'email_admin_user' ] = $tmp[ 'username' ]; - $_SESSION[ 'email_admin_superadmin' ] = (bool) $tmp[ 'superadmin' ]; // update password hash if it's using an old hashing algorithm if ( $tmp[ 'password_hash_type' ] !== '{ARGON2ID}' ) { $hash = password_hash( $_POST[ 'pwd' ], PASSWORD_ARGON2ID ); $stmt = $db->prepare( 'UPDATE admin SET password_hash_type = "{ARGON2ID}", password = ? WHERE username = ? AND active = 1;' ); - $stmt->execute( [ $hash, $_SESSION[ 'email_admin_user' ] ] ); + $stmt->execute( [ $hash, $tmp[ 'username' ] ] ); + } + if ( ! empty( $tmp[ 'totp_secret' ] ) ) { + unset( $_SESSION[ 'email_admin_user' ], $_SESSION[ 'email_admin_superadmin' ] ); + session_regenerate_id( true ); + $_SESSION[ 'csrf_token' ] = sha1( uniqid() ); + $_SESSION[ 'admin_totp_pending' ] = $tmp[ 'username' ]; + } else { + $_SESSION[ 'email_admin_user' ] = $tmp[ 'username' ]; + $_SESSION[ 'email_admin_superadmin' ] = (bool) $tmp[ 'superadmin' ]; } } } else { $msg .= ''; } } + } elseif ( ! empty( $_SESSION[ 'email_admin_user' ] ) && $_POST[ 'action' ] === 'start_admin_totp_setup' ) { + $_SESSION[ 'admin_totp_setup' ] = generate_totp_secret(); + } elseif ( ! empty( $_SESSION[ 'email_admin_user' ] ) && $_POST[ 'action' ] === 'enable_admin_totp' && ! empty( $_SESSION[ 'admin_totp_setup' ] ) ) { + if ( verify_totp_code( $_SESSION[ 'admin_totp_setup' ], $_POST[ 'totp_code' ] ?? '' ) ) { + $stmt = $db->prepare( 'UPDATE admin SET totp_secret = ? WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'admin_totp_setup' ], $_SESSION[ 'email_admin_user' ] ] ); + unset( $_SESSION[ 'admin_totp_setup' ] ); + $msg .= ''; + } else { + $msg .= ''; + } + } elseif ( ! empty( $_SESSION[ 'email_admin_user' ] ) && $_POST[ 'action' ] === 'disable_admin_totp' ) { + $stmt = $db->prepare( 'SELECT totp_secret FROM admin WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'email_admin_user' ] ] ); + $totp_secret = $stmt->fetchColumn(); + if ( is_string( $totp_secret ) && verify_totp_code( $totp_secret, $_POST[ 'totp_code' ] ?? '' ) ) { + $stmt = $db->prepare( 'UPDATE admin SET totp_secret = NULL WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'email_admin_user' ] ] ); + unset( $_SESSION[ 'admin_totp_setup' ] ); + $msg .= ''; + } else { + $msg .= ''; + } } elseif ( ! empty( $_SESSION[ 'email_admin_user' ] ) ) { if ( $_POST[ 'action' ] === 'update_alias' ) { $alias_goto = ''; @@ -359,7 +405,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $ok = check_domain_access( $_POST[ 'user' ], $msg ); } if ( $ok ) { - $stmt = $db->prepare( 'UPDATE mailbox SET tfa = 0 WHERE username = ?;' ); + $stmt = $db->prepare( 'UPDATE mailbox SET tfa = 0, totp_secret = NULL WHERE username = ?;' ); $stmt->execute( [ $_POST[ 'user' ] ] ); $msg .= ''; } @@ -396,16 +442,26 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { if ( $_SESSION[ 'email_admin_superadmin' ] ) { ?> | | | | | | |

$msg

"; - if ( empty( $_SESSION[ 'email_admin_user' ] ) ) { ?> + if ( ! empty( $_SESSION[ 'admin_totp_pending' ] ) ) { ?> +

+
+ + +
+
+
+
+ +
+
@@ -424,7 +480,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) {

prepare( 'SELECT username, superadmin, active FROM admin WHERE username = ?;' ); + $stmt = $db->prepare( 'SELECT username, superadmin, active, totp_secret FROM admin WHERE username = ?;' ); $stmt->execute( [ $admin ] ); if ( $admin = $stmt->fetch( PDO::FETCH_ASSOC ) ) { ?> @@ -608,6 +664,44 @@ function send_edit_admin(): void + +

+ +

+
+ + +
+
+
+
+ +
+ +

+

<?php echo htmlspecialchars(_('TOTP setup QR code')); ?>

+

+

+
+ + +
+
+
+
+ +
+ +
+ + + +
+ + '.htmlspecialchars(_('Oops, this admin doesn\'t seem to exist.')) . '

'; diff --git a/www/manage_account.php b/www/manage_account.php index 2278d7a..60a7b6a 100644 --- a/www/manage_account.php +++ b/www/manage_account.php @@ -22,7 +22,25 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { if ( $_SESSION[ 'csrf_token' ] !== $_POST[ 'csrf_token' ] ?? '' ) { die( 'Invalid CSRF token' ); } - if ( isset( $_SESSION[ '2fa_code' ] ) ) { + if ( isset( $_SESSION[ 'user_totp_pending' ] ) ) { + $db = get_db_instance(); + $stmt = $db->prepare( 'SELECT totp_secret FROM mailbox WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'user_totp_pending' ] ] ); + $pending = $stmt->fetch( PDO::FETCH_ASSOC ); + if ( ! $pending || empty( $pending[ 'totp_secret' ] ) ) { + unset( $_SESSION[ 'user_totp_pending' ] ); + $msg .= ''; + } elseif ( verify_totp_code( $pending[ 'totp_secret' ], $_POST[ 'totp_code' ] ?? '' ) ) { + $_SESSION[ 'email_user' ] = $_SESSION[ 'user_totp_pending' ]; + unset( $_SESSION[ 'user_totp_pending' ] ); + session_regenerate_id( true ); + $_SESSION[ 'csrf_token' ] = sha1( uniqid() ); + $stmt = $db->prepare( 'UPDATE mailbox SET last_login = ? WHERE username = ? AND active = 1;' ); + $stmt->execute( [ time(), $_SESSION[ 'email_user' ] ] ); + } else { + $msg .= ''; + } + } elseif ( isset( $_SESSION[ '2fa_code' ] ) ) { if ( ! empty( $_POST[ '2fa_code' ] ) && $_POST[ '2fa_code' ] === $_SESSION[ '2fa_code' ] ) { unset( $_SESSION[ '2fa_code' ] ); unset( $_SESSION[ 'pgp_key' ] ); @@ -30,7 +48,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $msg .= '

'.htmlspecialchars(_('Wrong 2FA code')).'

'; } } - if ( ! isset( $_SESSION[ '2fa_code' ] ) && isset( $_POST[ 'action' ] ) ) { + if ( ! isset( $_SESSION[ '2fa_code' ] ) && ! isset( $_SESSION[ 'user_totp_pending' ] ) && isset( $_POST[ 'action' ] ) ) { if ( $_POST[ 'action' ] === 'logout' ) { $_SESSION = []; session_regenerate_id( true ); @@ -55,26 +73,33 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { if ( $tmp = $stmt->fetch( PDO::FETCH_ASSOC ) ) { $domain = $tmp[ 'target_domain' ]; } - $stmt = $db->prepare( 'SELECT username, password, password_hash_type, tfa, pgp_key FROM mailbox WHERE username = ? AND active = 1;' ); + $stmt = $db->prepare( 'SELECT username, password, password_hash_type, tfa, pgp_key, totp_secret FROM mailbox WHERE username = ? AND active = 1;' ); $stmt->execute( [ "$user@$domain" ] ); if ( $tmp = $stmt->fetch( PDO::FETCH_ASSOC ) ) { if ( empty( $_POST[ 'pwd' ] ) || ! password_verify( $_POST[ 'pwd' ], $tmp[ 'password' ] ) ) { $ok = false; $msg .= ''; } else { - $_SESSION[ 'email_user' ] = $tmp[ 'username' ]; - $stmt = $db->prepare( 'UPDATE mailbox SET last_login = ? WHERE username = ? AND active = 1;' ); - $stmt->execute( [ time(), $_SESSION[ 'email_user' ] ] ); // update password hash if it's using an old hashing algorithm if ( $tmp[ 'password_hash_type' ] !== '{ARGON2ID}' ) { $hash = password_hash( $_POST[ 'pwd' ], PASSWORD_ARGON2ID ); $stmt = $db->prepare( 'UPDATE mailbox SET password_hash_type = "{ARGON2ID}", password = ? WHERE username = ? AND active = 1;' ); - $stmt->execute( [ $hash, $_SESSION[ 'email_user' ] ] ); + $stmt->execute( [ $hash, $tmp[ 'username' ] ] ); } - if ( $tmp[ 'tfa' ] ) { - $code = bin2hex( random_bytes( 3 ) ); - $_SESSION[ '2fa_code' ] = $code; - $_SESSION[ 'pgp_key' ] = $tmp[ 'pgp_key' ]; + if ( ! empty( $tmp[ 'totp_secret' ] ) ) { + unset( $_SESSION[ 'email_user' ] ); + session_regenerate_id( true ); + $_SESSION[ 'csrf_token' ] = sha1( uniqid() ); + $_SESSION[ 'user_totp_pending' ] = $tmp[ 'username' ]; + } else { + $_SESSION[ 'email_user' ] = $tmp[ 'username' ]; + $stmt = $db->prepare( 'UPDATE mailbox SET last_login = ? WHERE username = ? AND active = 1;' ); + $stmt->execute( [ time(), $_SESSION[ 'email_user' ] ] ); + if ( $tmp[ 'tfa' ] ) { + $code = bin2hex( random_bytes( 3 ) ); + $_SESSION[ '2fa_code' ] = $code; + $_SESSION[ 'pgp_key' ] = $tmp[ 'pgp_key' ]; + } } } } else { @@ -171,6 +196,29 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $stmt->execute( [ $_SESSION[ 'email_user' ] ] ); $msg .= '

'.htmlspecialchars(_('Successfully enabled 2FA')).'

'; } + } elseif ( $_POST[ 'action' ] === 'start_totp_setup' && ! empty( $_SESSION[ 'email_user' ] ) ) { + $_SESSION[ 'user_totp_setup' ] = generate_totp_secret(); + } elseif ( $_POST[ 'action' ] === 'enable_totp' && ! empty( $_SESSION[ 'email_user' ] ) && ! empty( $_SESSION[ 'user_totp_setup' ] ) ) { + if ( verify_totp_code( $_SESSION[ 'user_totp_setup' ], $_POST[ 'totp_code' ] ?? '' ) ) { + $stmt = $db->prepare( 'UPDATE mailbox SET totp_secret = ? WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'user_totp_setup' ], $_SESSION[ 'email_user' ] ] ); + unset( $_SESSION[ 'user_totp_setup' ] ); + $msg .= '

'.htmlspecialchars(_('Successfully enabled TOTP two-factor authentication')).'

'; + } else { + $msg .= '

'.htmlspecialchars(_('Invalid TOTP code')).'

'; + } + } elseif ( $_POST[ 'action' ] === 'disable_totp' && ! empty( $_SESSION[ 'email_user' ] ) ) { + $stmt = $db->prepare( 'SELECT totp_secret FROM mailbox WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'email_user' ] ] ); + $totp_secret = $stmt->fetchColumn(); + if ( is_string( $totp_secret ) && verify_totp_code( $totp_secret, $_POST[ 'totp_code' ] ?? '' ) ) { + $stmt = $db->prepare( 'UPDATE mailbox SET totp_secret = NULL WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $_SESSION[ 'email_user' ] ] ); + unset( $_SESSION[ 'user_totp_setup' ] ); + $msg .= '

'.htmlspecialchars(_('Successfully disabled TOTP two-factor authentication')).'

'; + } else { + $msg .= '

'.htmlspecialchars(_('Invalid TOTP code')).'

'; + } } } } @@ -197,7 +245,23 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) {
+

+
+ +
+
+
+
+ +
+
+ + prepare( 'SELECT pgp_key, tfa FROM mailbox WHERE username = ?;' ); + $stmt = $db->prepare( 'SELECT pgp_key, tfa, totp_secret FROM mailbox WHERE username = ?;' ); $stmt->execute( [ $_SESSION[ 'email_user' ] ] ); $pgp_status = $stmt->fetch( PDO::FETCH_ASSOC ); + ?> +

+ +

+
+ +
+
+
+
+ +
+ +

+

<?php echo htmlspecialchars(_('TOTP setup QR code')); ?>

+

+

+
+ +
+
+
+
+ +
+ +
+ + +
+ '.htmlspecialchars(_('Yay, PGP based 2FA is enabled!')).'

';