Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix: harden oidc state validation and session rotation (#1071)
Miguel Ribeirob75f13d0ffa3
diff --git a/admin.php b/admin.phpindex 4fd5540..55bde19 100644--- a/admin.php+++ b/admin.php@@ -31,8 +31,12 @@ if ($oidcSettings === false) {'scopes' => 'openid email profile','auth_style' => 'auto','auto_create_user' => 0,- 'password_login_disabled' => 0+ 'password_login_disabled' => 0,+ 'require_email_verified' => 1];+} else {+ // Column added via ALTER TABLE may return NULL for existing rows in SQLite+ $oidcSettings['require_email_verified'] = $oidcSettings['require_email_verified'] ?? 1;}// get user accounts@@ -272,6 +276,11 @@ $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;<?= $oidcSettings['password_login_disabled'] ? 'checked' : '' ?> /><label for="oidcPasswordLoginDisabled"><?= translate('disable_password_login', $i18n) ?></label></div>+ <div class="form-group-inline">+ <input type="checkbox" id="oidcRequireEmailVerified"+ <?= $oidcSettings['require_email_verified'] ? 'checked' : '' ?> />+ <label for="oidcRequireEmailVerified"><?= translate('require_email_verified_linking', $i18n) ?></label>+ </div><div class="buttons"><input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"id="saveOidcSettingsButton" onClick="saveOidcSettingsButton()" />diff --git a/endpoints/admin/saveoidcsettings.php b/endpoints/admin/saveoidcsettings.phpindex c9c2ef1..55afff0 100644--- a/endpoints/admin/saveoidcsettings.php+++ b/endpoints/admin/saveoidcsettings.php@@ -2,6 +2,7 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint_admin.php';+require_once '../../includes/ssrf_helper.php';$postData = file_get_contents("php://input");$data = json_decode($postData, true);@@ -19,6 +20,21 @@ $oidcScopes = isset($data['oidcScopes']) ? trim($data['oidcScopes']) : '';$oidcAuthStyle = isset($data['oidcAuthStyle']) ? trim($data['oidcAuthStyle']) : '';$oidcAutoCreateUser = isset($data['oidcAutoCreateUser']) ? (int) $data['oidcAutoCreateUser'] : 0;$oidcPasswordLoginDisabled = isset($data['oidcPasswordLoginDisabled']) ? (int) $data['oidcPasswordLoginDisabled'] : 0;+$oidcRequireEmailVerified = isset($data['oidcRequireEmailVerified']) ? (int) $data['oidcRequireEmailVerified'] : 1;++if ($oidcTokenUrl && validate_oidc_endpoint_url($oidcTokenUrl, $db) === false) {+ die(json_encode([+ "success" => false,+ "message" => "Security Error: Token URL must not target link-local or loopback addresses."+ ]));+}++if ($oidcUserInfoUrl && validate_oidc_endpoint_url($oidcUserInfoUrl, $db) === false) {+ die(json_encode([+ "success" => false,+ "message" => "Security Error: User Info URL must not target link-local or loopback addresses."+ ]));+}$checkStmt = $db->prepare('SELECT COUNT(*) as count FROM oauth_settings WHERE id = 1');$result = $checkStmt->execute();@@ -39,14 +55,15 @@ if ($row['count'] > 0) {scopes = :oidcScopes,auth_style = :oidcAuthStyle,auto_create_user = :oidcAutoCreateUser,- password_login_disabled = :oidcPasswordLoginDisabled+ password_login_disabled = :oidcPasswordLoginDisabled,+ require_email_verified = :oidcRequireEmailVerifiedWHERE id = 1');} else {// Insert new row$stmt = $db->prepare('INSERT INTO oauth_settings (- id, name, client_id, client_secret, authorization_url, token_url, user_info_url, redirect_url, logout_url, user_identifier_field, scopes, auth_style, auto_create_user, password_login_disabled+ id, name, client_id, client_secret, authorization_url, token_url, user_info_url, redirect_url, logout_url, user_identifier_field, scopes, auth_style, auto_create_user, password_login_disabled, require_email_verified) VALUES (- 1, :oidcName, :oidcClientId, :oidcClientSecret, :oidcAuthUrl, :oidcTokenUrl, :oidcUserInfoUrl, :oidcRedirectUrl, :oidcLogoutUrl, :oidcUserIdentifierField, :oidcScopes, :oidcAuthStyle, :oidcAutoCreateUser, :oidcPasswordLoginDisabled+ 1, :oidcName, :oidcClientId, :oidcClientSecret, :oidcAuthUrl, :oidcTokenUrl, :oidcUserInfoUrl, :oidcRedirectUrl, :oidcLogoutUrl, :oidcUserIdentifierField, :oidcScopes, :oidcAuthStyle, :oidcAutoCreateUser, :oidcPasswordLoginDisabled, :oidcRequireEmailVerified)');}@@ -63,6 +80,7 @@ $stmt->bindParam(':oidcScopes', $oidcScopes, SQLITE3_TEXT);$stmt->bindParam(':oidcAuthStyle', $oidcAuthStyle, SQLITE3_TEXT);$stmt->bindParam(':oidcAutoCreateUser', $oidcAutoCreateUser, SQLITE3_INTEGER);$stmt->bindParam(':oidcPasswordLoginDisabled', $oidcPasswordLoginDisabled, SQLITE3_INTEGER);+$stmt->bindParam(':oidcRequireEmailVerified', $oidcRequireEmailVerified, SQLITE3_INTEGER);$stmt->execute();if ($db->changes() > 0) {diff --git a/endpoints/admin/savesmtpsettings.php b/endpoints/admin/savesmtpsettings.phpindex ff7f59f..130f2c0 100644--- a/endpoints/admin/savesmtpsettings.php+++ b/endpoints/admin/savesmtpsettings.php@@ -2,6 +2,7 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint_admin.php';+require_once '../../includes/ssrf_helper.php';$postData = file_get_contents("php://input");$data = json_decode($postData, true);@@ -20,6 +21,21 @@ if (empty($smtpAddress) || empty($smtpPort)) {]));}+if (!validate_smtp_host($smtpAddress, $smtpPortInt, $db)) {+ die(json_encode([+ "success" => false,+ "message" => "Security Error: SMTP host must not target link-local or loopback addresses."+ ]));+}++$smtpPortInt = (int) $smtpPort;+if ($smtpPortInt < 1 || $smtpPortInt > 65535) {+ die(json_encode([+ "success" => false,+ "message" => translate('fill_all_fields', $i18n)+ ]));+}+// Save settings$stmt = $db->prepare('UPDATE admin SET smtp_address = :smtp_address, smtp_port = :smtp_port, encryption = :encryption, smtp_username = :smtp_username, smtp_password = :smtp_password, from_email = :from_email');$stmt->bindValue(':smtp_address', $smtpAddress, SQLITE3_TEXT);diff --git a/endpoints/db/restore.php b/endpoints/db/restore.phpindex 174c561..f423927 100644--- a/endpoints/db/restore.php+++ b/endpoints/db/restore.php@@ -26,6 +26,19 @@ if (isset($_FILES['file'])) {$zip = new ZipArchive();if ($zip->open($fileDestination) === true) {+ // Validate all entries before extracting — ZipArchive::extractTo() does not+ // guarantee protection against path traversal (Zip Slip).+ for ($i = 0; $i < $zip->numFiles; $i++) {+ $entry = str_replace('\\', '/', $zip->getNameIndex($i));+ if ($entry[0] === '/' || in_array('..', explode('/', $entry), true)) {+ $zip->close();+ emptyRestoreFolder();+ die(json_encode([+ "success" => false,+ "message" => "Invalid backup file: unsafe file path detected."+ ]));+ }+ }$zip->extractTo('../../.tmp/restore/');$zip->close();} else {diff --git a/endpoints/notifications/testemailnotifications.php b/endpoints/notifications/testemailnotifications.phpindex f921bec..eb4ba3a 100644--- a/endpoints/notifications/testemailnotifications.php+++ b/endpoints/notifications/testemailnotifications.php@@ -5,7 +5,8 @@ use PHPMailer\PHPMailer\SMTP;use PHPMailer\PHPMailer\Exception;require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint.php';+require_once '../../includes/validate_endpoint_admin.php';+require_once '../../includes/ssrf_helper.php';$postData = file_get_contents("php://input");$data = json_decode($postData, true);@@ -32,7 +33,21 @@ if (require '../../libs/PHPMailer/Exception.php';$smtpAddress = $data["smtpaddress"];- $smtpPort = $data["smtpport"];+ $smtpPort = (int) $data["smtpport"];++ if (!validate_smtp_host($smtpAddress, $smtpPort, $db)) {+ die(json_encode([+ "success" => false,+ "message" => "Security Error: SMTP host must not target link-local or loopback addresses."+ ]));+ }++ if ($smtpPort < 1 || $smtpPort > 65535) {+ die(json_encode([+ "success" => false,+ "message" => translate('fill_all_fields', $i18n)+ ]));+ }$smtpUsername = $data["smtpusername"];$smtpPassword = $data["smtppassword"];$fromEmail = $data["fromemail"] ? $data['fromemail'] : "[email protected]";diff --git a/endpoints/subscription/clone.php b/endpoints/subscription/clone.phpindex 5c2b2ef..3599e0d 100644--- a/endpoints/subscription/clone.php+++ b/endpoints/subscription/clone.php@@ -19,7 +19,7 @@ if ($subscriptionToClone === false) {]));}-$query = "INSERT INTO subscriptions (name, logo, price, currency_id, next_payment, cycle, frequency, notes, payment_method_id, payer_user_id, category_id, notify, url, inactive, notify_days_before, user_id, cancellation_date, replacement_subscription_id) VALUES (:name, :logo, :price, :currency_id, :next_payment, :cycle, :frequency, :notes, :payment_method_id, :payer_user_id, :category_id, :notify, :url, :inactive, :notify_days_before, :user_id, :cancellation_date, :replacement_subscription_id)";+$query = "INSERT INTO subscriptions (name, logo, price, currency_id, next_payment, auto_renew, start_date, cycle, frequency, notes, payment_method_id, payer_user_id, category_id, notify, url, inactive, notify_days_before, user_id, cancellation_date, replacement_subscription_id) VALUES (:name, :logo, :price, :currency_id, :next_payment, :auto_renew, :start_date, :cycle, :frequency, :notes, :payment_method_id, :payer_user_id, :category_id, :notify, :url, :inactive, :notify_days_before, :user_id, :cancellation_date, :replacement_subscription_id)";$cloneStmt = $db->prepare($query);$cloneStmt->bindValue(':name', $subscriptionToClone['name'], SQLITE3_TEXT);$cloneStmt->bindValue(':logo', $subscriptionToClone['logo'], SQLITE3_TEXT);diff --git a/includes/checksession.php b/includes/checksession.phpindex bd18ec8..c07df87 100644--- a/includes/checksession.php+++ b/includes/checksession.php@@ -30,12 +30,6 @@ if (isset($_GET['code']) && isset($_GET['state'])) {unset($_SESSION['oidc_state']);- if (!isset($_SESSION['oidc_state']) || !hash_equals($_SESSION['oidc_state'], $state)) {- header("Location: login.php");- exit();- }- unset($_SESSION['oidc_state']);-require_once 'includes/oidc/handle_oidc_callback.php';} else {diff --git a/includes/i18n/ca.php b/includes/i18n/ca.phpindex 1f447b9..b8b9117 100644--- a/includes/i18n/ca.php+++ b/includes/i18n/ca.php@@ -395,6 +395,8 @@ $i18n = ["oidc_oauth_enabled" => "Activar OIDC/OAuth","create_user_automatically" => "Crear usuari automàticament","disable_password_login" => "Desactivar l'inici de sessió amb contrasenya",+ "require_email_verified_linking" => "Requerir correu electrònic verificat per vincular el compte",+ "oidc_email_not_verified" => "Error d'inici de sessió: la vostra adreça de correu electrònic no ha estat verificada pel proveïdor d'identitat.","smtp_settings" => "Configuració SMTP","smtp_usage_info" => "S'utilitza per recuperar contrasenyes i enviar altres correus electrònics del sistema.","security_settings" => "Configuració de seguretat",diff --git a/includes/i18n/cs.php b/includes/i18n/cs.phpindex 784e682..4fca584 100644--- a/includes/i18n/cs.php+++ b/includes/i18n/cs.php@@ -395,6 +395,8 @@ $i18n = ["oidc_oauth_enabled" => "Povolit OIDC/OAuth","create_user_automatically" => "Automaticky vytvořit uživatele","disable_password_login" => "Zakázat přihlašování pomocí hesla",+ "require_email_verified_linking" => "Vyžadovat ověřený e-mail pro propojení účtu",+ "oidc_email_not_verified" => "Přihlášení selhalo: e-mailová adresa nebyla ověřena poskytovatelem identity.","smtp_settings" => "Nastavení SMTP","smtp_usage_info" => "Bude použito pro obnovení hesla a další systémové e-maily.","security_settings" => "Nastavení zabezpečení",diff --git a/includes/i18n/da.php b/includes/i18n/da.phpindex abd1646..cb59310 100644--- a/includes/i18n/da.php+++ b/includes/i18n/da.php@@ -395,6 +395,8 @@ $i18n = ["oidc_oauth_enabled" => "Aktivér OIDC/OAuth","create_user_automatically" => "Opret bruger automatisk","disable_password_login" => "Deaktivér adgangskode-login",+ "require_email_verified_linking" => "Kræv verificeret e-mail til kontotilknytning",+ "oidc_email_not_verified" => "Login mislykkedes: din e-mailadresse er ikke verificeret af identitetsudbyderen.","smtp_settings" => "SMTP-indstillinger","security_settings" => "Sikkerhedsindstillinger","ssrf_protection_info" => "For at forhindre Server-Side Request Forgery (SSRF) angreb blokerer Wallos som standard webhook-notifikationer til private eller interne netværksadresser.",diff --git a/includes/i18n/de.php b/includes/i18n/de.phpindex 65d2440..93b9086 100644--- a/includes/i18n/de.php+++ b/includes/i18n/de.php@@ -394,6 +394,8 @@ $i18n = ["oidc_oauth_enabled" => "OIDC/OAuth aktivieren","create_user_automatically" => "Benutzer automatisch erstellen","disable_password_login" => "Passwort-Login deaktivieren",+ "require_email_verified_linking" => "Verifizierte E-Mail für Kontoverknüpfung erforderlich",+ "oidc_email_not_verified" => "Anmeldung fehlgeschlagen: Ihre E-Mail-Adresse wurde vom Identitätsanbieter nicht verifiziert.","smtp_settings" => "SMTP Einstellungen","smtp_usage_info" => "Wird für die Passwortwiederherstellung und andere System-E-Mails verwendet","security_settings" => "Sicherheitseinstellungen",diff --git a/includes/i18n/el.php b/includes/i18n/el.phpindex 81c9650..82b7291 100644--- a/includes/i18n/el.php+++ b/includes/i18n/el.php@@ -392,6 +392,8 @@ $i18n = ["oidc_oauth_enabled" => "Ενεργοποίηση OIDC/OAuth","create_user_automatically" => "Δημιουργία χρήστη αυτόματα","disable_password_login" => "Απενεργοποίηση σύνδεσης με κωδικό πρόσβασης",+ "require_email_verified_linking" => "Απαιτείται επαληθευμένο email για τη σύνδεση λογαριασμού",+ "oidc_email_not_verified" => "Αποτυχία σύνδεσης: η διεύθυνση email σας δεν έχει επαληθευτεί από τον πάροχο ταυτότητας.","smtp_settings" => "SMTP ρυθμίσεις","security_settings" => "Ρυθμίσεις ασφάλειας","ssrf_protection_info" => "Για να αποτρέψετε επιθέσεις Server-Side Request Forgery (SSRF), το Wallos αποκλείει από προεπιλογή τις ειδοποιήσεις webhook σε ιδιωτικές ή εσωτερικές διευθύνσεις δικτύου.",diff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex c84cfbf..55fc27f 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -395,6 +395,8 @@ $i18n = ["oidc_oauth_enabled" => "Enable OIDC/OAuth","create_user_automatically" => "Create user automatically","disable_password_login" => "Disable password login",+ "require_email_verified_linking" => "Require verified email for account linking",+ "oidc_email_not_verified" => "Login failed: your email address has not been verified by the identity provider.","smtp_settings" => "SMTP Settings","smtp_usage_info" => "Will be used for password recovery and other system emails.","security_settings" => "Security Settings",diff --git a/includes/i18n/es.php b/includes/i18n/es.phpindex 60b7241..d03d6b2 100644--- a/includes/i18n/es.php+++ b/includes/i18n/es.php@@ -394,6 +394,8 @@ $i18n = ["oidc_oauth_enabled" => "Habilitar OIDC/OAuth","create_user_automatically" => "Crear usuario automáticamente","disable_password_login" => "Deshabilitar inicio de sesión con contraseña",+ "require_email_verified_linking" => "Requerir correo electrónico verificado para vincular cuenta",+ "oidc_email_not_verified" => "Error de inicio de sesión: su dirección de correo electrónico no ha sido verificada por el proveedor de identidad.","smtp_settings" => "Configuración SMTP","smtp_usage_info" => "Se utilizará para recuperar contraseñas y otros correos electrónicos del sistema.","security_settings" => "Configuración de seguridad",diff --git a/includes/i18n/fr.php b/includes/i18n/fr.phpindex 15ce5b8..93b55b2 100644--- a/includes/i18n/fr.php+++ b/includes/i18n/fr.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "Authentification OIDC activée","create_user_automatically" => "Créer un utilisateur automatiquement","disable_password_login" => "Désactiver la connexion par mot de passe",+ "require_email_verified_linking" => "Exiger un e-mail vérifié pour la liaison de compte",+ "oidc_email_not_verified" => "Échec de la connexion : votre adresse e-mail n'a pas été vérifiée par le fournisseur d'identité.","smtp_settings" => "Paramètres SMTP","smtp_usage_info" => "Sera utilisé pour la récupération du mot de passe et d'autres e-mails système.","security_settings" => "Paramètres de sécurité",diff --git a/includes/i18n/hu.php b/includes/i18n/hu.phpindex bbe6bb3..5d22035 100644--- a/includes/i18n/hu.php+++ b/includes/i18n/hu.php@@ -394,7 +394,9 @@ $i18n = ["oidc_settings" => "OIDC Beállítások","oidc_oauth_enabled" => "OIDC/OAuth engedélyezése","create_user_automatically" => "Felhasználó automatikus létrehozása",- "disable_password_login" => "Jelszavas bejelentkezés letiltása",+ "disable_password_login" => "Jelszavas bejelentkezés letiltása",+ "require_email_verified_linking" => "Ellenőrzött e-mail cím szükséges a fiókkapcsoláshoz",+ "oidc_email_not_verified" => "Bejelentkezés sikertelen: az e-mail-cím nincs hitelesítve az identitásszolgáltató által.","smtp_settings" => "SMTP Beállítások","smtp_usage_info" => "Jelszó-helyreállításhoz és más rendszer e-mailekhez lesz használva.","security_settings" => "Biztonsági beállítások",diff --git a/includes/i18n/id.php b/includes/i18n/id.phpindex 0364b41..52b5d2e 100644--- a/includes/i18n/id.php+++ b/includes/i18n/id.php@@ -395,6 +395,8 @@ $i18n = ["oidc_oauth_enabled" => "Aktifkan OIDC/OAuth","create_user_automatically" => "Buat pengguna secara otomatis","disable_password_login" => "Nonaktifkan masuk dengan kata sandi",+ "require_email_verified_linking" => "Wajibkan email terverifikasi untuk menautkan akun",+ "oidc_email_not_verified" => "Login gagal: alamat email Anda belum diverifikasi oleh penyedia identitas.","smtp_settings" => "Pengaturan SMTP","smtp_usage_info" => "Akan digunakan untuk pemulihan kata sandi dan email sistem lainnya.","security_settings" => "Pengaturan Keamanan",diff --git a/includes/i18n/it.php b/includes/i18n/it.phpindex d1964ac..6bfbcdd 100644--- a/includes/i18n/it.php+++ b/includes/i18n/it.php@@ -411,6 +411,8 @@ $i18n = ["oidc_auth_enabled" => "Autenticazione OIDC abilitata","create_user_automatically" => "Crea utente automaticamente","disable_password_login" => "Disabilita la connessione con password",+ "require_email_verified_linking" => "Richiedi email verificata per il collegamento dell'account",+ "oidc_email_not_verified" => "Accesso fallito: il tuo indirizzo email non è stato verificato dal provider di identità.","smtp_settings" => "Impostazioni SMTP","smtp_usage_info" => "Verrà utilizzato per il recupero della password e altre e-mail di sistema.","security_settings" => "Impostazioni di sicurezza",diff --git a/includes/i18n/ja.php b/includes/i18n/ja.phpindex eeb3edf..0a65a63 100644--- a/includes/i18n/ja.php+++ b/includes/i18n/ja.php@@ -395,6 +395,8 @@ $i18n = ["oidc_auth_enabled" => "OIDC認証を有効にする","create_user_automatically" => "OIDCユーザーを自動的に作成する","disable_password_login" => "パスワードログインを無効にする",+ "require_email_verified_linking" => "アカウント連携には確認済みメールアドレスが必要",+ "oidc_email_not_verified" => "ログインに失敗しました:メールアドレスがIDプロバイダーによって確認されていません。","smtp_settings" => "SMTP設定","smtp_usage_info" => "パスワードの回復やその他のシステム電子メールに使用されます。","security_settings" => "セキュリティ設定",diff --git a/includes/i18n/ko.php b/includes/i18n/ko.phpindex 88e7ea9..a94ac3c 100644--- a/includes/i18n/ko.php+++ b/includes/i18n/ko.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "OIDC 인증 활성화","create_user_automatically" => "사용자 자동 생성","disable_password_login" => "비밀번호 로그인 비활성화",+ "require_email_verified_linking" => "계정 연결에 인증된 이메일 필요",+ "oidc_email_not_verified" => "로그인 실패: 이메일 주소가 신원 제공자에 의해 확인되지 않았습니다.","smtp_settings" => "SMTP 설정","smtp_usage_info" => "비밀번호 복구 및 기타 시스템 이메일에 사용됩니다.","security_settings" => "보안 설정",diff --git a/includes/i18n/nl.php b/includes/i18n/nl.phpindex 3526d35..ed1e506 100644--- a/includes/i18n/nl.php+++ b/includes/i18n/nl.php@@ -395,6 +395,8 @@ $i18n = ["oidc_oauth_enabled" => "OIDC/OAuth inschakelen","create_user_automatically" => "Gebruiker automatisch aanmaken","disable_password_login" => "Wachtwoordlogin uitschakelen",+ "require_email_verified_linking" => "Geverifieerd e-mailadres vereisen voor accountkoppeling",+ "oidc_email_not_verified" => "Aanmelding mislukt: uw e-mailadres is niet geverifieerd door de identiteitsprovider.","smtp_settings" => "SMTP-instellingen","smtp_usage_info" => "Wordt gebruikt voor wachtwoordherstel en andere systeem e-mails.","security_settings" => "Beveiligingsinstellingen",diff --git a/includes/i18n/pl.php b/includes/i18n/pl.phpindex ff1bafe..8093bf8 100644--- a/includes/i18n/pl.php+++ b/includes/i18n/pl.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "Włącz uwierzytelnianie OIDC","create_user_automatically" => "Automatycznie twórz użytkowników","disable_password_login" => "Wyłącz logowanie za pomocą hasła",+ "require_email_verified_linking" => "Wymagaj zweryfikowanego e-maila do łączenia kont",+ "oidc_email_not_verified" => "Logowanie nie powiodło się: adres e-mail nie został zweryfikowany przez dostawcę tożsamości.","smtp_settings" => "Ustawienia SMTP","smtp_usage_info" => "Będzie używany do odzyskiwania hasła i innych e-maili systemowych.","security_settings" => "Ustawienia zabezpieczeń",diff --git a/includes/i18n/pt.php b/includes/i18n/pt.phpindex 990cb26..0862a3a 100644--- a/includes/i18n/pt.php+++ b/includes/i18n/pt.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "Activar autenticação OIDC","create_user_automatically" => "Criar utilizador automaticamente","disable_password_login" => "Desactivar login por password",+ "require_email_verified_linking" => "Exigir e-mail verificado para vinculação de conta",+ "oidc_email_not_verified" => "Falha no início de sessão: o seu endereço de e-mail não foi verificado pelo fornecedor de identidade.","smtp_settings" => "Definições SMTP","smtp_usage_info" => "Será usado para recuperações de password e outros emails do sistema.","security_settings" => "Configurações de Segurança",diff --git a/includes/i18n/pt_br.php b/includes/i18n/pt_br.phpindex bf1b65e..75d8641 100644--- a/includes/i18n/pt_br.php+++ b/includes/i18n/pt_br.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "Habilitar autenticação OIDC","create_user_automatically" => "Criar usuário automaticamente","disable_password_login" => "Desativar login por senha",+ "require_email_verified_linking" => "Exigir e-mail verificado para vinculação de conta",+ "oidc_email_not_verified" => "Falha no login: seu endereço de e-mail não foi verificado pelo provedor de identidade.","smtp_settings" => "Configurações SMTP","smtp_usage_info" => "Será usado para recuperação de senha e outros e-mails do sistema.","security_settings" => "Configurações de Segurança",diff --git a/includes/i18n/ro.php b/includes/i18n/ro.phpindex f266684..408d5c0 100644--- a/includes/i18n/ro.php+++ b/includes/i18n/ro.php@@ -395,6 +395,8 @@ $i18n = ["oidc_oauth_enabled" => "Activează OIDC/OAuth","create_user_automatically" => "Crează utilizatori automat","disable_password_login" => "Dezactivează logarea cu parolă",+ "require_email_verified_linking" => "Necesită e-mail verificat pentru conectarea contului",+ "oidc_email_not_verified" => "Autentificare eșuată: adresa de e-mail nu a fost verificată de furnizorul de identitate.","smtp_settings" => "Setări SMTP","smtp_usage_info" => "Va fi utilizată pentru recuperarea parolei și alte e-mailuri de sistem.","security_settings" => "Setări de srcuritate",diff --git a/includes/i18n/ru.php b/includes/i18n/ru.phpindex d0d5149..b0657b5 100644--- a/includes/i18n/ru.php+++ b/includes/i18n/ru.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "Включить OIDC аутентификацию","create_user_automatically" => "Автоматически создавать пользователей","disable_password_login" => "Отключить вход по паролю",+ "require_email_verified_linking" => "Требовать подтверждённый e-mail для связывания аккаунта",+ "oidc_email_not_verified" => "Ошибка входа: адрес электронной почты не подтверждён поставщиком удостоверений.","smtp_settings" => "Настройки SMTP","security_settings" => "Параметры безопасности","ssrf_protection_info" => "Чтобы предотвратить атаки Server-Side Request Forgery (SSRF), Wallos по умолчанию блокирует уведомления webhook на приватные или внутренние сетевые адреса.",diff --git a/includes/i18n/sl.php b/includes/i18n/sl.phpindex 31ab7d2..580a442 100644--- a/includes/i18n/sl.php+++ b/includes/i18n/sl.php@@ -387,6 +387,8 @@ $i18n = ["oidc_auth_enabled" => "Omogoči OIDC prijavo","create_user_automatically" => "Samodejno ustvari uporabnika","disable_password_login" => "Onemogoči prijavo z geslom",+ "require_email_verified_linking" => "Zahtevaj preverjen e-naslov za povezovanje računa",+ "oidc_email_not_verified" => "Prijava ni uspela: vaš e-poštni naslov ni bil preverjen s strani ponudnika identitete.","smtp_settings" => "Nastavitve SMTP","smtp_usage_info" => "Uporabljeno bo za obnovitev gesla in druge sistemske e-pošte.","security_settings" => "Varnostne nastavitve",diff --git a/includes/i18n/sr.php b/includes/i18n/sr.phpindex b0ad805..a3fd2da 100644--- a/includes/i18n/sr.php+++ b/includes/i18n/sr.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "OIDC аутентификација је омогућена","create_user_automatically" => "Креирај корисника аутоматски","disable_password_login" => "Онемогући пријаву лозинком",+ "require_email_verified_linking" => "Захтевај верификовану е-пошту за повезивање налога",+ "oidc_email_not_verified" => "Пријава неуспешна: е-маил адреса није верификована од стране провајдера идентитета.","smtp_settings" => "SMTP подешавања","smtp_usage_info" => "SMTP се користи за слање е-поште за обавештења.","security_settings" => "Поставке безбедности",diff --git a/includes/i18n/sr_lat.php b/includes/i18n/sr_lat.phpindex 1f168f4..2047fbf 100644--- a/includes/i18n/sr_lat.php+++ b/includes/i18n/sr_lat.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "Omogući OIDC autentifikaciju","create_user_automatically" => "Kreiraj korisnika automatski","disable_password_login" => "Onemoguči prijavu z geslom",+ "require_email_verified_linking" => "Zahtevaj verifikovanu e-poštu za povezivanje naloga",+ "oidc_email_not_verified" => "Prijava neuspešna: e-mail adresa nije verifikovana od strane provajdera identiteta.","smtp_settings" => "SMTP podešavanja","smtp_usage_info" => "Koristiće se za oporavak lozinke i druge sistemske e-poruke.","security_settings" => "Podešavanja bezbednosti",diff --git a/includes/i18n/tr.php b/includes/i18n/tr.phpindex 327a7c6..e2a7362 100644--- a/includes/i18n/tr.php+++ b/includes/i18n/tr.php@@ -394,6 +394,8 @@ $i18n = ["oidc_auth_enabled" => "OpenID Connect Kimlik Doğrulaması Etkinleştirildi","create_user_automatically" => "OpenID Connect ile giriş yapıldığında kullanıcı otomatik olarak oluşturulsun","disable_password_login" => "Parola ile giriş devre dışı bırakılsın",+ "require_email_verified_linking" => "Hesap bağlamak için doğrulanmış e-posta gerekli",+ "oidc_email_not_verified" => "Giriş başarısız: e-posta adresiniz kimlik sağlayıcı tarafından doğrulanmamış.","smtp_settings" => "SMTP Ayarları","smtp_usage_info" => "Şifre kurtarma ve diğer sistem e-postaları için kullanılacaktır.","security_settings" => "Güvenlik Ayarları",diff --git a/includes/i18n/uk.php b/includes/i18n/uk.phpindex 04e3bec..9a8d2c0 100644--- a/includes/i18n/uk.php+++ b/includes/i18n/uk.php@@ -395,6 +395,8 @@ $i18n = ["oidc_auth_enabled" => "Увімкнути OIDC автентифікацію","create_user_automatically" => "Автоматично створювати користувача при вході","disable_password_login" => "Відключити вхід за паролем",+ "require_email_verified_linking" => "Вимагати підтвердженого e-mail для прив'язки облікового запису",+ "oidc_email_not_verified" => "Помилка входу: електронну адресу не підтверджено постачальником ідентифікаційних даних.","smtp_usage_info" => "Буде використовуватися для відновлення пароля та інших системних листів.","security_settings" => "Налаштування безпеки","ssrf_protection_info" => "Щоб запобігти атакам Server-Side Request Forgery (SSRF), Wallos за замовчуванням блокує вебхуки до приватних або внутрішніх мережевих адрес.",diff --git a/includes/i18n/vi.php b/includes/i18n/vi.phpindex 661e188..77c57be 100644--- a/includes/i18n/vi.php+++ b/includes/i18n/vi.php@@ -395,6 +395,8 @@ $i18n = ["oidc_auth_enabled" => "Xác thực OIDC đã được bật","create_user_automatically" => "Tạo người dùng tự động","disable_password_login" => "Vô hiệu hóa đăng nhập bằng mật khẩu",+ "require_email_verified_linking" => "Yêu cầu email đã xác minh để liên kết tài khoản",+ "oidc_email_not_verified" => "Đăng nhập thất bại: địa chỉ email của bạn chưa được nhà cung cấp danh tính xác minh.","smtp_settings" => "Cài đặt SMTP","smtp_usage_info" => "Sẽ được sử dụng cho việc khôi phục mật khẩu và các email hệ thống khác.","security_settings" => "Cài đặt bảo mật",diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.phpindex a5d8e60..15b7156 100644--- a/includes/i18n/zh_cn.php+++ b/includes/i18n/zh_cn.php@@ -412,6 +412,8 @@ $i18n = ["oidc_auth_enabled" => "启用 OIDC 身份验证","create_user_automatically" => "当使用 OIDC 登录时自动创建用户","disable_password_login" => "禁用密码登录",+ "require_email_verified_linking" => "账号关联需要已验证的电子邮件",+ "oidc_email_not_verified" => "登录失败:您的电子邮件地址未经身份提供商验证。","smtp_settings" => "SMTP 设置","smtp_usage_info" => "将用于密码恢复和其他系统电子邮件。","security_settings" => "安全设置",diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.phpindex c04fa73..c8db05c 100644--- a/includes/i18n/zh_tw.php+++ b/includes/i18n/zh_tw.php@@ -395,6 +395,8 @@ $i18n = ["oidc_auth_enabled" => "啟用 OIDC 身份驗證","create_user_automatically" => "當使用 OIDC 登入時自動建立使用者","disable_password_login" => "停用密碼登入",+ "require_email_verified_linking" => "帳號關聯需要已驗證的電子郵件",+ "oidc_email_not_verified" => "登入失敗:您的電子郵件地址未經身份提供商驗證。","smtp_settings" => "SMTP 設定","smtp_usage_info" => "用於密碼重設和其他系統郵件。","security_settings" => "安全設定",diff --git a/includes/oidc/handle_oidc_callback.php b/includes/oidc/handle_oidc_callback.phpindex 4811148..d18d00b 100644--- a/includes/oidc/handle_oidc_callback.php+++ b/includes/oidc/handle_oidc_callback.php@@ -10,6 +10,8 @@ function generate_username_from_email($email)return $username;}+require_once __DIR__ . '/../ssrf_helper.php';+// get OIDC settings$stmt = $db->prepare('SELECT * FROM oauth_settings WHERE id = 1');$result = $stmt->execute();@@ -18,6 +20,12 @@ $oidcSettings = $result->fetchArray(SQLITE3_ASSOC);$tokenUrl = $oidcSettings['token_url'];$redirectUri = $oidcSettings['redirect_url'];+$tokenUrlInfo = validate_oidc_endpoint_url($tokenUrl, $db);+if ($tokenUrlInfo === false) {+ header("Location: login.php?error=oidc_invalid_config");+ exit();+}+$postFields = ['grant_type' => 'authorization_code','code' => $_GET['code'],@@ -31,6 +39,7 @@ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);+curl_setopt($ch, CURLOPT_RESOLVE, ["{$tokenUrlInfo['host']}:{$tokenUrlInfo['port']}:{$tokenUrlInfo['ip']}"]);$response = curl_exec($ch);unset($ch);@@ -41,11 +50,18 @@ if (!$tokenData || !isset($tokenData['access_token'])) {$userInfoUrl = $oidcSettings['user_info_url'];+$userInfoUrlInfo = validate_oidc_endpoint_url($userInfoUrl, $db);+if ($userInfoUrlInfo === false) {+ header("Location: login.php?error=oidc_invalid_config");+ exit();+}+$ch = curl_init($userInfoUrl);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $tokenData['access_token']]);+curl_setopt($ch, CURLOPT_RESOLVE, ["{$userInfoUrlInfo['host']}:{$userInfoUrlInfo['port']}:{$userInfoUrlInfo['ip']}"]);$response = curl_exec($ch);unset($ch);@@ -76,6 +92,14 @@ if ($userData) {exit();}+ // Require email_verified when the setting is enabled (default on).+ // Prevents account takeover by an attacker who presents an unverified email+ // matching an existing local account at a permissive or attacker-controlled IdP.+ if ($oidcSettings['require_email_verified'] && ($userInfo['email_verified'] ?? false) !== true) {+ header("Location: login.php?error=oidc_email_not_verified");+ exit();+ }+$stmt = $db->prepare('SELECT * FROM user WHERE email = :email');$stmt->bindValue(':email', $email, SQLITE3_TEXT);$result = $stmt->execute();diff --git a/includes/ssrf_helper.php b/includes/ssrf_helper.phpindex 69b5145..2457cef 100644--- a/includes/ssrf_helper.php+++ b/includes/ssrf_helper.php@@ -91,6 +91,105 @@ function validate_webhook_url_for_ssrf($url, $db, $i18n, $userId = null) {];}+/**+ * Validates an SMTP hostname against SSRF.+ * Private/reserved IPs (RFC-1918, link-local, loopback, CGNAT) are only+ * allowed if the host or IP appears in the admin Security Settings allowlist+ *+ * @param string $host Hostname or IP+ * @param int $port SMTP port (used for allowlist host:port matching)+ * @param SQLite3 $db+ * @return bool+ */+function validate_smtp_host($host, $port, $db) {+ $ip = gethostbyname($host);++ // DNS failure — gethostbyname returns the input unchanged on failure+ if ($ip === $host && filter_var($host, FILTER_VALIDATE_IP) === false) return false;++ $is_private = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false+ || is_cgnat_ip($ip);++ if ($is_private) {+ $stmt = $db->prepare("SELECT local_webhook_notifications_allowlist FROM admin LIMIT 1");+ $result = $stmt->execute();+ $row = $result->fetchArray(SQLITE3_ASSOC);++ $allowlist_str = $row ? $row['local_webhook_notifications_allowlist'] : '';+ $allowlist = array_filter(array_map('trim', explode(',', $allowlist_str)));++ $hostWithPort = $host . ':' . $port;+ $ipWithPort = $ip . ':' . $port;++ if (+ !in_array($host, $allowlist) &&+ !in_array($ip, $allowlist) &&+ !in_array($hostWithPort, $allowlist) &&+ !in_array($ipWithPort, $allowlist)+ ) {+ return false;+ }+ }++ return true;+}++/**+ * Validates an OIDC endpoint URL (token_url, user_info_url) against SSRF.+ * Private/reserved IPs (RFC-1918, link-local, loopback, CGNAT) are only+ * allowed if the host or IP appears in the admin Security Settings allowlist,+ *+ * @param string $url+ * @param SQLite3 $db+ * @return array|false ['host', 'ip', 'port'] on success, false on failure+ */+function validate_oidc_endpoint_url($url, $db) {+ $parsed = parse_url($url);+ if (!$parsed || !isset($parsed['host'])) return false;++ $scheme = strtolower($parsed['scheme'] ?? '');+ if (!in_array($scheme, ['http', 'https'], true)) return false;++ $host = $parsed['host'];+ $port = $parsed['port'] ?? '';+ $ip = gethostbyname($host);++ // DNS failure — gethostbyname returns the input unchanged on failure+ if ($ip === $host && filter_var($host, FILTER_VALIDATE_IP) === false) return false;++ $targetPort = $port ?: ($scheme === 'https' ? 443 : 80);++ $is_private = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false+ || is_cgnat_ip($ip);++ if ($is_private) {+ $stmt = $db->prepare("SELECT local_webhook_notifications_allowlist FROM admin LIMIT 1");+ $result = $stmt->execute();+ $row = $result->fetchArray(SQLITE3_ASSOC);++ $allowlist_str = $row ? $row['local_webhook_notifications_allowlist'] : '';+ $allowlist = array_filter(array_map('trim', explode(',', $allowlist_str)));++ $hostWithPort = $host . ':' . $targetPort;+ $ipWithPort = $ip . ':' . $targetPort;++ if (+ !in_array($host, $allowlist) &&+ !in_array($ip, $allowlist) &&+ !in_array($hostWithPort, $allowlist) &&+ !in_array($ipWithPort, $allowlist)+ ) {+ return false;+ }+ }++ return [+ 'host' => $host,+ 'ip' => $ip,+ 'port' => $targetPort,+ ];+}+/*** Non-fatal variant for use in cron jobs (sendnotifications.php).* Returns the same ['host', 'ip', 'port'] array on success, or false on failure.diff --git a/includes/version.php b/includes/version.phpindex 760ae23..9115832 100644--- a/includes/version.php+++ b/includes/version.php@@ -1,3 +1,3 @@<?php-$version = "v4.9.5";+$version = "v4.9.6";?>diff --git a/login.php b/login.phpindex 7e7888a..54d0859 100644--- a/login.php+++ b/login.php@@ -167,6 +167,7 @@ if ($oidcRow) {$loginFailed = false;$hasSuccessMessage = (isset($_GET['validated']) && $_GET['validated'] == "true") || (isset($_GET['registered']) && $_GET['registered'] == true) ? true : false;$userEmailWaitingVerification = false;+$oidcEmailNotVerified = false;if (isset($_POST['username']) && isset($_POST['password'])) {$username = $_POST['username'];$password = $_POST['password'];@@ -298,8 +299,12 @@ if (!$password_login_disabled) {}-if (isset($_GET['error']) && in_array($_GET['error'], ["oidc_user_not_found", "oidc_invalid_state"], true)) {- $loginFailed = true;+if (isset($_GET['error'])) {+ $oidcError = $_GET['error'];+ if (in_array($oidcError, ["oidc_user_not_found", "oidc_invalid_state", "oidc_email_not_verified", "oidc_invalid_config"], true)) {+ $loginFailed = true;+ $oidcEmailNotVerified = $oidcError === "oidc_email_not_verified";+ }}?>@@ -395,6 +400,10 @@ if (isset($_GET['error']) && in_array($_GET['error'], ["oidc_user_not_found", "oclass="fa-solid fa-triangle-exclamation"></i><?= translate('user_email_waiting_verification', $i18n) ?></li><?php+ } elseif ($oidcEmailNotVerified) {+ ?>+ <li><i class="fa-solid fa-triangle-exclamation"></i><?= translate('oidc_email_not_verified', $i18n) ?></li>+ <?php} else {?><li><i class="fa-solid fa-triangle-exclamation"></i><?= translate('login_failed', $i18n) ?></li>diff --git a/migrations/000047.php b/migrations/000047.phpnew file mode 100644index 0000000..8017001--- /dev/null+++ b/migrations/000047.php@@ -0,0 +1,15 @@+<?php+// Adds require_email_verified to oauth_settings.+// When enabled (default), account linking by email is only allowed when the+// IdP marks email_verified = true, preventing account takeover via unverified emails.++$columnQuery = $db->query("SELECT * FROM pragma_table_info('oauth_settings') WHERE name='require_email_verified'");+$columnRequired = $columnQuery->fetchArray(SQLITE3_ASSOC) === false;++if ($columnRequired) {+ $db->exec("ALTER TABLE oauth_settings ADD COLUMN require_email_verified INTEGER DEFAULT 1");+}++// SQLite does not physically store ALTER TABLE defaults in existing rows, so+// PHP's SQLite3 extension may return NULL for them. Backfill explicitly.+$db->exec("UPDATE oauth_settings SET require_email_verified = 1 WHERE require_email_verified IS NULL");diff --git a/scripts/admin.js b/scripts/admin.jsindex 46e49ec..60803aa 100644--- a/scripts/admin.js+++ b/scripts/admin.js@@ -459,6 +459,7 @@ function saveOidcSettingsButton() {const oidcAuthStyle = document.getElementById("oidcAuthStyle").value;const oidcAutoCreateUser = document.getElementById("oidcAutoCreateUser").checked ? 1 : 0;const oidcPasswordLoginDisabled = document.getElementById("oidcPasswordLoginDisabled").checked ? 1 : 0;+ const oidcRequireEmailVerified = document.getElementById("oidcRequireEmailVerified").checked ? 1 : 0;const data = {oidcName: oidcName,@@ -473,7 +474,8 @@ function saveOidcSettingsButton() {oidcScopes: oidcScopes,oidcAuthStyle: oidcAuthStyle,oidcAutoCreateUser: oidcAutoCreateUser,- oidcPasswordLoginDisabled: oidcPasswordLoginDisabled+ oidcPasswordLoginDisabled: oidcPasswordLoginDisabled,+ oidcRequireEmailVerified: oidcRequireEmailVerified};