Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:lock: Throttle Basic Auth brute-force and use constant-time comparison for the access auth code https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v

Daniel9e21021b434e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 3bd78277cf..819d3d28b4 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -2387,6 +2387,8 @@
"350": "تعذر إكمال كتابة دفتر الملاحظات الجديد أو فهرسته؛ تم وضع علامة عليه بأنه غير مكتمل",
"351": "حدث خطأ غير متوقع؛ تحقق من سجل النظام للمهمة [%s]",
"352": "لا يتسع النموذج المحدد لسياق الوكيل حتى بعد الضغط. انتقل إلى نموذج ذي نافذة سياق أكبر",
- "353": "تجاهل حقل قالب العنصر الجديد [%s] قيم الخيارات غير المتاحة [%s]"
+ "353": "تجاهل حقل قالب العنصر الجديد [%s] قيم الخيارات غير المتاحة [%s]",
+ "354": "عدد محاولات المصادقة الفاشلة كبير جدًا، يرجى المحاولة مرة أخرى لاحقًا",
+ "355": "يجب أن تتكون كلمة مرور شاشة القفل من 8 أحرف على الأقل"
}
}
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index c240033dbf..a562d47784 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -2387,6 +2387,8 @@
"350": "Das Schreiben oder Indizieren des neuen Notizbuchs konnte nicht abgeschlossen werden; es wurde als unvollständig markiert",
"351": "Ein unerwarteter Fehler ist aufgetreten; prüfen Sie das Systemprotokoll für die Aufgabe [%s]",
"352": "Der Agentenkontext passt auch nach der Komprimierung nicht in das ausgewählte Modell. Wechseln Sie zu einem Modell mit größerem Kontextfenster",
- "353": "Das Feld [%s] der Vorlage für neue Einträge hat nicht verfügbare Optionswerte ignoriert [%s]"
+ "353": "Das Feld [%s] der Vorlage für neue Einträge hat nicht verfügbare Optionswerte ignoriert [%s]",
+ "354": "Zu viele fehlgeschlagene Authentifizierungsversuche, bitte versuchen Sie es später erneut",
+ "355": "Das Bildschirmsperr-Passwort muss mindestens 8 Zeichen lang sein"
}
}
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 5a468aea49..aee38e9777 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -2387,6 +2387,8 @@
"350": "Unable to finish writing or indexing the new notebook; it has been marked as incomplete",
"351": "An unexpected error occurred; check the system log for task [%s]",
"352": "The agent context cannot fit the selected model after compaction. Switch to a model with a larger context window",
- "353": "New item template field [%s] ignored unavailable option values [%s]"
+ "353": "New item template field [%s] ignored unavailable option values [%s]",
+ "354": "Too many failed authentication attempts, please try again later",
+ "355": "The lock screen password must be at least 8 characters"
}
}
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index fc31b10b8a..08dfcd71d8 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -2387,6 +2387,8 @@
"350": "No se pudo terminar de escribir o indexar el nuevo cuaderno; se ha marcado como incompleto",
"351": "Se produjo un error inesperado; consulte el registro del sistema para la tarea [%s]",
"352": "El contexto del agente no cabe en el modelo seleccionado después de la compresión. Cambia a un modelo con una ventana de contexto mayor",
- "353": "El campo [%s] de la plantilla de nuevo elemento ignoró los valores de opción no disponibles [%s]"
+ "353": "El campo [%s] de la plantilla de nuevo elemento ignoró los valores de opción no disponibles [%s]",
+ "354": "Demasiados intentos de autenticación fallidos, inténtelo de nuevo más tarde",
+ "355": "La contraseña de la pantalla de bloqueo debe tener al menos 8 caracteres"
}
}
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 8d22494a60..1255d5797c 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -2387,6 +2387,8 @@
"350": "Impossible de terminer l’écriture ou l’indexation du nouveau carnet ; il a été marqué comme incomplet",
"351": "Une erreur inattendue s’est produite ; consultez le journal système pour la tâche [%s]",
"352": "Le contexte de l’agent ne tient pas dans le modèle sélectionné après compression. Choisissez un modèle avec une fenêtre de contexte plus grande",
- "353": "Le champ [%s] du modèle de nouvel élément a ignoré les valeurs d’option indisponibles [%s]"
+ "353": "Le champ [%s] du modèle de nouvel élément a ignoré les valeurs d’option indisponibles [%s]",
+ "354": "Trop de tentatives d'authentification échouées, veuillez réessayer plus tard",
+ "355": "Le mot de passe de l'écran de verrouillage doit comporter au moins 8 caractères"
}
}
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index ac816c8706..c81e74bfd2 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -2387,6 +2387,8 @@
"350": "לא ניתן להשלים את הכתיבה או יצירת האינדקס של המחברת החדשה; היא סומנה כלא שלמה",
"351": "אירעה שגיאה בלתי צפויה; יש לבדוק את יומן המערכת עבור המשימה [%s]",
"352": "ההקשר של הסוכן אינו נכנס למודל שנבחר גם לאחר דחיסה. עבור למודל עם חלון הקשר גדול יותר",
- "353": "השדה [%s] בתבנית הפריט החדש התעלם מערכי אפשרויות שאינם זמינים [%s]"
+ "353": "השדה [%s] בתבנית הפריט החדש התעלם מערכי אפשרויות שאינם זמינים [%s]",
+ "354": "יותר מדי ניסיונות אימות נכשלו, נסה שוב מאוחר יותר",
+ "355": "סיסמת מסך הנעילה חייבת להכיל לפחות 8 תווים"
}
}
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 1d86a0085e..cea6c87c73 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -2387,6 +2387,8 @@
"350": "नई नोटबुक को लिखना या इंडेक्स करना पूरा नहीं हो सका; इसे अपूर्ण चिह्नित किया गया है",
"351": "एक अप्रत्याशित त्रुटि हुई; कार्य [%s] के लिए सिस्टम लॉग देखें",
"352": "संपीड़न के बाद भी एजेंट का संदर्भ चयनित मॉडल में समा नहीं सकता। बड़ी संदर्भ विंडो वाले मॉडल पर जाएँ",
- "353": "नए आइटम टेम्पलेट फ़ील्ड [%s] ने अनुपलब्ध विकल्प मानों [%s] को अनदेखा किया"
+ "353": "नए आइटम टेम्पलेट फ़ील्ड [%s] ने अनुपलब्ध विकल्प मानों [%s] को अनदेखा किया",
+ "354": "बहुत अधिक असफल प्रमाणीकरण प्रयास, कृपया बाद में पुनः प्रयास करें",
+ "355": "लॉक स्क्रीन पासवर्ड कम से कम 8 अक्षरों का होना चाहिए"
}
}
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 18a7090410..d3264327b1 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -2387,6 +2387,8 @@
"350": "Tidak dapat menyelesaikan penulisan atau pengindeksan buku catatan baru; buku catatan telah ditandai belum lengkap",
"351": "Terjadi kesalahan tak terduga; periksa log sistem untuk tugas [%s]",
"352": "Konteks agen tidak muat dalam model yang dipilih setelah pemadatan. Beralihlah ke model dengan jendela konteks yang lebih besar",
- "353": "Bidang templat item baru [%s] mengabaikan nilai opsi yang tidak tersedia [%s]"
+ "353": "Bidang templat item baru [%s] mengabaikan nilai opsi yang tidak tersedia [%s]",
+ "354": "Terlalu banyak percobaan autentikasi yang gagal, silakan coba lagi nanti",
+ "355": "Kata sandi layar kunci harus terdiri dari minimal 8 karakter"
}
}
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 7fe36cbf22..51ba2bc7e8 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -2387,6 +2387,8 @@
"350": "Impossibile completare la scrittura o l’indicizzazione del nuovo taccuino; è stato contrassegnato come incompleto",
"351": "Si è verificato un errore imprevisto; controlla il registro di sistema per l’attività [%s]",
"352": "Il contesto dell’agente non rientra nel modello selezionato dopo la compressione. Passa a un modello con una finestra di contesto più ampia",
- "353": "Il campo [%s] del modello per nuovi elementi ha ignorato i valori di opzione non disponibili [%s]"
+ "353": "Il campo [%s] del modello per nuovi elementi ha ignorato i valori di opzione non disponibili [%s]",
+ "354": "Troppi tentativi di autenticazione falliti, riprova più tardi",
+ "355": "La password della schermata di blocco deve contenere almeno 8 caratteri"
}
}
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index fa4c46cdb2..6ec05b73a0 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -2387,6 +2387,8 @@
"350": "新しいノートブックの書き込みまたはインデックス作成を完了できませんでした。不完全としてマークしました",
"351": "予期しないエラーが発生しました。タスク [%s] のシステムログを確認してください",
"352": "圧縮後もエージェントのコンテキストが選択したモデルに収まりません。より大きなコンテキストウィンドウを持つモデルに切り替えてください",
- "353": "新規アイテムテンプレートのフィールド [%s] で利用できない選択肢の値 [%s] が無視されました"
+ "353": "新規アイテムテンプレートのフィールド [%s] で利用できない選択肢の値 [%s] が無視されました",
+ "354": "認証失敗が多すぎます。しばらくしてから再試行してください",
+ "355": "ロック画面パスワードは 8 文字以上にしてください"
}
}
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index c0493d2153..084c1abd99 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -2387,6 +2387,8 @@
"350": "새 노트북 쓰기 또는 색인 생성을 완료할 수 없어 미완료로 표시했습니다",
"351": "예기치 않은 오류가 발생했습니다. 작업 [%s]의 시스템 로그를 확인하세요",
"352": "압축 후에도 에이전트 컨텍스트가 선택한 모델에 맞지 않습니다. 컨텍스트 창이 더 큰 모델로 전환하세요",
- "353": "새 항목 템플릿 필드 [%s]에서 사용할 수 없는 옵션 값 [%s]을 무시했습니다"
+ "353": "새 항목 템플릿 필드 [%s]에서 사용할 수 없는 옵션 값 [%s]을 무시했습니다",
+ "354": "인증 실패 횟수가 너무 많습니다. 잠시 후 다시 시도하세요",
+ "355": "잠금 화면 비밀번호는 8자 이상이어야 합니다"
}
}
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index f1c82d18d3..78de4f0045 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -2387,6 +2387,8 @@
"350": "Het schrijven of indexeren van het nieuwe notitieboek kon niet worden voltooid; het is als onvolledig gemarkeerd",
"351": "Er is een onverwachte fout opgetreden; controleer het systeemlogboek voor taak [%s]",
"352": "De agentcontext past na compressie niet in het geselecteerde model. Kies een model met een groter contextvenster",
- "353": "Veld [%s] van de sjabloon voor nieuwe items heeft niet-beschikbare optiewaarden genegeerd [%s]"
+ "353": "Veld [%s] van de sjabloon voor nieuwe items heeft niet-beschikbare optiewaarden genegeerd [%s]",
+ "354": "Te veel mislukte verificatiepogingen, probeer het later opnieuw",
+ "355": "Het wachtwoord van het vergrendelscherm moet minimaal 8 tekens bevatten"
}
}
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index e290f2671a..5c73181111 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -2387,6 +2387,8 @@
"350": "Nie można ukończyć zapisywania lub indeksowania nowego notatnika; został oznaczony jako niekompletny",
"351": "Wystąpił nieoczekiwany błąd; sprawdź dziennik systemowy zadania [%s]",
"352": "Kontekst agenta nie mieści się w wybranym modelu po kompresji. Wybierz model z większym oknem kontekstowym",
- "353": "Pole [%s] szablonu nowego elementu zignorowało niedostępne wartości opcji [%s]"
+ "353": "Pole [%s] szablonu nowego elementu zignorowało niedostępne wartości opcji [%s]",
+ "354": "Zbyt wiele nieudanych prób uwierzytelnienia, spróbuj ponownie później",
+ "355": "Hasło ekranu blokady musi mieć co najmniej 8 znaków"
}
}
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 0ce5acef7d..75f32cc6ff 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -2387,6 +2387,8 @@
"350": "Não foi possível concluir a gravação ou indexação do novo caderno; ele foi marcado como incompleto",
"351": "Ocorreu um erro inesperado; verifique o registro do sistema para a tarefa [%s]",
"352": "O contexto do agente não cabe no modelo selecionado após a compactação. Mude para um modelo com uma janela de contexto maior",
- "353": "O campo [%s] do modelo de novo item ignorou valores de opção indisponíveis [%s]"
+ "353": "O campo [%s] do modelo de novo item ignorou valores de opção indisponíveis [%s]",
+ "354": "Muitas tentativas de autenticação falharam, tente novamente mais tarde",
+ "355": "A senha da tela de bloqueio deve ter pelo menos 8 caracteres"
}
}
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 30abac7b2b..79f3cda9f3 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -2387,6 +2387,8 @@
"350": "Не удалось завершить запись или индексацию нового блокнота; он помечен как незавершённый",
"351": "Произошла непредвиденная ошибка; проверьте системный журнал для задачи [%s]",
"352": "Контекст агента не помещается в выбранную модель даже после сжатия. Выберите модель с большим контекстным окном",
- "353": "Поле [%s] шаблона нового элемента проигнорировало недоступные значения параметров [%s]"
+ "353": "Поле [%s] шаблона нового элемента проигнорировало недоступные значения параметров [%s]",
+ "354": "Слишком много неудачных попыток аутентификации, повторите попытку позже",
+ "355": "Пароль экрана блокировки должен содержать не менее 8 символов"
}
}
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 8d1ac1f95a..2be166bea9 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -2387,6 +2387,8 @@
"350": "Zápis alebo indexovanie nového zápisníka sa nepodarilo dokončiť; bol označený ako neúplný",
"351": "Vyskytla sa neočakávaná chyba; skontrolujte systémový denník úlohy [%s]",
"352": "Kontext agenta sa ani po kompresii nezmestí do vybraného modelu. Vyberte model s väčším kontextovým oknom",
- "353": "Pole [%s] šablóny novej položky ignorovalo nedostupné hodnoty možností [%s]"
+ "353": "Pole [%s] šablóny novej položky ignorovalo nedostupné hodnoty možností [%s]",
+ "354": "Príliš veľa neúspešných pokusov o overenie, skúste to znova neskôr",
+ "355": "Heslo uzamknutej obrazovky musí mať aspoň 8 znakov"
}
}
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index b800f71ef1..d69f63ffae 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -2387,6 +2387,8 @@
"350": "ไม่สามารถเขียนหรือจัดทำดัชนีสมุดบันทึกใหม่ให้เสร็จสมบูรณ์ได้ จึงทำเครื่องหมายว่าไม่สมบูรณ์",
"351": "เกิดข้อผิดพลาดที่ไม่คาดคิด โปรดตรวจสอบบันทึกระบบของงาน [%s]",
"352": "บริบทของเอเจนต์ยังไม่พอดีกับโมเดลที่เลือกหลังการบีบอัด โปรดเปลี่ยนไปใช้โมเดลที่มีหน้าต่างบริบทใหญ่กว่า",
- "353": "ฟิลด์เทมเพลตรายการใหม่ [%s] ละเว้นค่าตัวเลือกที่ไม่พร้อมใช้งาน [%s]"
+ "353": "ฟิลด์เทมเพลตรายการใหม่ [%s] ละเว้นค่าตัวเลือกที่ไม่พร้อมใช้งาน [%s]",
+ "354": "การยืนยันตัวตนล้มเหลวหลายครั้งเกินไป กรุณาลองใหม่ในภายหลัง",
+ "355": "รหัสผ่านหน้าจอล็อกต้องมีอย่างน้อย 8 ตัวอักษร"
}
}
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 97979dfde8..626214ebf7 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -2387,6 +2387,8 @@
"350": "Yeni not defterinin yazılması veya dizine eklenmesi tamamlanamadı; eksik olarak işaretlendi",
"351": "Beklenmeyen bir hata oluştu; görev [%s] için sistem günlüğünü kontrol edin",
"352": "Ajan bağlamı sıkıştırmadan sonra seçilen modele sığmıyor. Daha büyük bağlam penceresine sahip bir modele geçin",
- "353": "Yeni öğe şablonu alanı [%s] kullanılamayan seçenek değerlerini yok saydı [%s]"
+ "353": "Yeni öğe şablonu alanı [%s] kullanılamayan seçenek değerlerini yok saydı [%s]",
+ "354": "Çok fazla başarısız kimlik doğrulama denemesi, lütfen daha sonra tekrar deneyin",
+ "355": "Kilit ekranı parolası en az 8 karakter olmalıdır"
}
}
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 249057a6ad..42e682e2b5 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -2387,6 +2387,8 @@
"350": "Не вдалося завершити запис або індексування нового нотатника; його позначено як незавершений",
"351": "Сталася неочікувана помилка; перевірте системний журнал для завдання [%s]",
"352": "Контекст агента не вміщується у вибрану модель навіть після стиснення. Виберіть модель із більшим контекстним вікном",
- "353": "Поле [%s] шаблону нового елемента проігнорувало недоступні значення параметрів [%s]"
+ "353": "Поле [%s] шаблону нового елемента проігнорувало недоступні значення параметрів [%s]",
+ "354": "Забагато невдалих спроб автентифікації, спробуйте пізніше",
+ "355": "Пароль екрана блокування має містити щонайменше 8 символів"
}
}
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 3020c36dbb..7f5d10d48a 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -2387,6 +2387,8 @@
"350": "无法完成新笔记本的写入或索引,已将其标记为导入未完成",
"351": "发生未知错误,请在系统日志中查找任务 [%s]",
"352": "智能体上下文压缩后仍无法适配所选模型,请切换到上下文窗口更大的模型",
- "353": "新增条目模板字段 [%s] 已忽略不可用的选项值 [%s]"
+ "353": "新增条目模板字段 [%s] 已忽略不可用的选项值 [%s]",
+ "354": "认证失败次数过多,请稍后重试",
+ "355": "锁屏密码长度不能少于 8 个字符"
}
}
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 7cea50330c..7aef45f8e9 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -2387,6 +2387,8 @@
"350": "無法完成新筆記本的寫入或索引,已將其標記為匯入未完成",
"351": "發生未知錯誤,請在系統日誌中尋找任務 [%s]",
"352": "智能體上下文壓縮後仍無法適配所選模型,請切換到上下文視窗更大的模型",
- "353": "新增條目範本欄位 [%s] 已忽略不可用的選項值 [%s]"
+ "353": "新增條目範本欄位 [%s] 已忽略不可用的選項值 [%s]",
+ "354": "認證失敗次數過多,請稍後重試",
+ "355": "鎖屏密碼長度不能少於 8 個字元"
}
}
diff --git a/kernel/api/system.go b/kernel/api/system.go
index a6fcb94385..7d5eaf0478 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -844,7 +844,8 @@ func setAccessAuthCode(c *gin.Context) {
}
aac := arg["accessAuthCode"].(string)
- if model.MaskedAccessAuthCode == aac {
+ masked := model.MaskedAccessAuthCode == aac
+ if masked {
aac = model.Conf.AccessAuthCode
}
@@ -859,6 +860,13 @@ func setAccessAuthCode(c *gin.Context) {
return
}
+ // 仅校验新设置的密码,掩码回填的已有密码和清空(禁用锁屏)不做长度限制,避免用户被锁定 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v
+ if !masked && 0 < len(aac) && 8 > len(aac) {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(333)
+ return
+ }
+
model.Conf.AccessAuthCode = aac
model.Conf.Save()
diff --git a/kernel/model/session.go b/kernel/model/session.go
index feee0a94f9..dfee9d6a77 100644
--- a/kernel/model/session.go
+++ b/kernel/model/session.go
@@ -113,7 +113,7 @@ func LoginAuth(c *gin.Context) {
authCode = util.RemoveInvalid(authCode)
authCode = strings.TrimSpace(authCode)
- if Conf.AccessAuthCode != authCode {
+ if !util.AuthCodeEquals(Conf.AccessAuthCode, authCode) {
ret.Code = -1
ret.Msg = Conf.Language(83)
logging.LogWarnf("invalid auth code [ip=%s]", util.GetRemoteAddr(c.Request))
@@ -136,6 +136,7 @@ func LoginAuth(c *gin.Context) {
workspaceSession.AccessAuthCode = authCode
util.WrongAuthCount = 0
+ util.AuthThrottleReset(c.ClientIP())
workspaceSession.Captcha = gulu.Rand.String(7)
maxAge := 0 // Default session expiration (browser session)
@@ -332,11 +333,23 @@ func CheckAuth(c *gin.Context) {
// 通过 BasicAuth (header: Authorization)
if username, password, ok := c.Request.BasicAuth(); ok {
// 使用锁屏密码作为密码
- if util.WorkspaceName == username && Conf.AccessAuthCode == password {
+ ip := c.ClientIP()
+ if retryAfter := util.AuthThrottleCheck(ip); 0 < retryAfter {
+ // 锁定期间持续记录失败,防止暴力破解 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v
+ util.AuthThrottleFail(ip)
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ c.JSON(http.StatusTooManyRequests, map[string]any{"code": -1, "msg": Conf.Language(332)})
+ c.Abort()
+ return
+ }
+ if util.WorkspaceName == username && util.AuthCodeEquals(Conf.AccessAuthCode, password) {
+ util.AuthThrottleReset(ip)
c.Set(RoleContextKey, RoleAdministrator)
c.Next()
return
}
+ logging.LogWarnf("invalid auth code [ip=%s]", ip)
+ util.AuthThrottleFail(ip)
}
// WebDAV BasicAuth Authenticate
diff --git a/kernel/util/session.go b/kernel/util/session.go
index f330c76c56..8bd8e53271 100644
--- a/kernel/util/session.go
+++ b/kernel/util/session.go
@@ -17,7 +17,10 @@
package util
import (
+ "crypto/subtle"
"strings"
+ "sync"
+ "time"
"github.com/88250/gulu"
ginSessions "github.com/gin-contrib/sessions"
@@ -31,6 +34,88 @@ func NeedCaptcha() bool {
return 3 < WrongAuthCount
}
+// AuthCodeEquals 恒定时间比较认证码,避免通过响应时间差异猜测秘密。
+func AuthCodeEquals(a, b string) bool {
+ return 1 == subtle.ConstantTimeCompare([]byte(a), []byte(b))
+}
+
+var (
+ authThrottleLock = sync.Mutex{}
+ authThrottles = map[string]*authThrottle{} // key: 来源 IP
+)
+
+// authThrottle 记录认证失败次数与锁定状态,用于防止无验证码的认证路径(如 Basic Auth)被暴力破解。
+type authThrottle struct {
+ FailCount int
+ LockUntil time.Time
+ LastFail time.Time
+}
+
+const (
+ authThrottleMaxFail = 5 // 连续失败次数达到该值时开始锁定
+ authThrottleLockBaseSec = 30 // 首次锁定秒数
+ authThrottleLockMaxSec = 15 * 60 // 锁定秒数上限
+ authThrottleWindowSec = 15 * 60 // 失败计数滑动窗口,窗口内失败才累计
+)
+
+// AuthThrottleCheck 返回 key 剩余锁定秒数,0 表示未锁定。
+func AuthThrottleCheck(key string) (retryAfter int) {
+ authThrottleLock.Lock()
+ defer authThrottleLock.Unlock()
+
+ throttle := authThrottles[key]
+ if nil == throttle {
+ return 0
+ }
+ if time.Now().Before(throttle.LockUntil) {
+ return int(time.Until(throttle.LockUntil)/time.Second) + 1
+ }
+ if !throttle.LockUntil.IsZero() {
+ // 锁定已过期,清除失败计数
+ delete(authThrottles, key)
+ return 0
+ }
+ if authThrottleWindowSec*time.Second <= time.Now().Sub(throttle.LastFail) {
+ // 超过窗口期未再失败,清除计数避免误锁
+ delete(authThrottles, key)
+ }
+ return 0
+}
+
+// AuthThrottleFail 记录一次认证失败,达到阈值后按指数退避锁定。
+func AuthThrottleFail(key string) {
+ authThrottleLock.Lock()
+ defer authThrottleLock.Unlock()
+
+ now := time.Now()
+ throttle := authThrottles[key]
+ if nil == throttle {
+ throttle = &authThrottle{}
+ authThrottles[key] = throttle
+ } else if authThrottleWindowSec*time.Second <= now.Sub(throttle.LastFail) {
+ // 超过窗口期,重置失败计数
+ throttle.FailCount = 0
+ }
+ throttle.LastFail = now
+ throttle.FailCount++
+ if throttle.FailCount <= authThrottleMaxFail {
+ return
+ }
+
+ lockSec := authThrottleLockBaseSec << (throttle.FailCount - authThrottleMaxFail)
+ if authThrottleLockMaxSec < lockSec {
+ lockSec = authThrottleLockMaxSec
+ }
+ throttle.LockUntil = now.Add(time.Duration(lockSec) * time.Second)
+}
+
+// AuthThrottleReset 认证成功后清除失败计数。
+func AuthThrottleReset(key string) {
+ authThrottleLock.Lock()
+ defer authThrottleLock.Unlock()
+ delete(authThrottles, key)
+}
+
// SessionData represents the session.
type SessionData struct {
Workspaces map[string]*WorkspaceSession // <WorkspacePath, WorkspaceSession>
diff --git a/kernel/util/session_test.go b/kernel/util/session_test.go
new file mode 100644
index 0000000000..1d6ff18432
--- /dev/null
+++ b/kernel/util/session_test.go
@@ -0,0 +1,137 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package util
+
+import (
+ "testing"
+ "time"
+)
+
+// TestAuthCodeEquals 验证恒定时间比较的相等与不等判定。
+func TestAuthCodeEquals(t *testing.T) {
+ if !AuthCodeEquals("secret123", "secret123") {
+ t.Fatal("equal codes should match")
+ }
+ if AuthCodeEquals("secret123", "secret124") {
+ t.Fatal("different codes should not match")
+ }
+ if AuthCodeEquals("secret123", "secret") {
+ t.Fatal("codes of different length should not match")
+ }
+ if AuthCodeEquals("", "secret123") || AuthCodeEquals("secret123", "") {
+ t.Fatal("empty code should not match a non-empty one")
+ }
+ if !AuthCodeEquals("", "") {
+ t.Fatal("both empty codes should match")
+ }
+}
+
+// TestAuthThrottleThreshold 验证未达阈值不锁定、超过阈值后锁定。
+func TestAuthThrottleThreshold(t *testing.T) {
+ key := "TestAuthThrottleThreshold"
+ resetAuthThrottleForTest(key)
+ for i := 0; i < authThrottleMaxFail; i++ {
+ if retryAfter := AuthThrottleCheck(key); 0 < retryAfter {
+ t.Fatalf("locked before reaching threshold at attempt %d", i+1)
+ }
+ AuthThrottleFail(key)
+ }
+ AuthThrottleFail(key)
+ if retryAfter := AuthThrottleCheck(key); 0 >= retryAfter {
+ t.Fatal("expected lock after exceeding threshold")
+ }
+}
+
+// TestAuthThrottleBackoff 验证锁定期随持续失败指数增长且不超过上限。
+func TestAuthThrottleBackoff(t *testing.T) {
+ key := "TestAuthThrottleBackoff"
+ resetAuthThrottleForTest(key)
+ for i := 0; i < authThrottleMaxFail+1; i++ {
+ AuthThrottleFail(key)
+ }
+ firstLock := time.Until(authThrottles[key].LockUntil)
+ for i := 0; i < authThrottleMaxFail; i++ {
+ AuthThrottleFail(key)
+ }
+ extendedLock := time.Until(authThrottles[key].LockUntil)
+ if !(extendedLock > firstLock) {
+ t.Fatal("expected lock to extend while failures keep coming")
+ }
+ if authThrottleLockMaxSec*time.Second < extendedLock {
+ t.Fatalf("lock exceeded the cap: %v", extendedLock)
+ }
+}
+
+// TestAuthThrottleWindowReset 验证窗口期外的陈旧失败计数被清零,避免误锁。
+func TestAuthThrottleWindowReset(t *testing.T) {
+ key := "TestAuthThrottleWindowReset"
+ resetAuthThrottleForTest(key)
+ AuthThrottleFail(key)
+ authThrottleLock.Lock()
+ authThrottles[key].LastFail = time.Now().Add(-authThrottleWindowSec * time.Second)
+ authThrottleLock.Unlock()
+ AuthThrottleFail(key)
+ authThrottleLock.Lock()
+ count := authThrottles[key].FailCount
+ authThrottleLock.Unlock()
+ if count != 1 {
+ t.Fatalf("expected stale failure count to reset, got %d", count)
+ }
+}
+
+// TestAuthThrottleReset 验证认证成功后清除失败计数。
+func TestAuthThrottleReset(t *testing.T) {
+ key := "TestAuthThrottleReset"
+ resetAuthThrottleForTest(key)
+ for i := 0; i < authThrottleMaxFail+1; i++ {
+ AuthThrottleFail(key)
+ }
+ if retryAfter := AuthThrottleCheck(key); 0 >= retryAfter {
+ t.Fatal("expected lock before reset")
+ }
+ AuthThrottleReset(key)
+ if retryAfter := AuthThrottleCheck(key); 0 < retryAfter {
+ t.Fatal("expected no lock after reset")
+ }
+}
+
+// TestAuthThrottleExpiry 验证锁定期过期后解除锁定并清理记录。
+func TestAuthThrottleExpiry(t *testing.T) {
+ key := "TestAuthThrottleExpiry"
+ resetAuthThrottleForTest(key)
+ for i := 0; i < authThrottleMaxFail+1; i++ {
+ AuthThrottleFail(key)
+ }
+ authThrottleLock.Lock()
+ authThrottles[key].LockUntil = time.Now().Add(-time.Second)
+ authThrottleLock.Unlock()
+ if retryAfter := AuthThrottleCheck(key); 0 < retryAfter {
+ t.Fatal("expected lock to be expired")
+ }
+ authThrottleLock.Lock()
+ _, exists := authThrottles[key]
+ authThrottleLock.Unlock()
+ if exists {
+ t.Fatal("expected expired throttle entry to be cleaned up")
+ }
+}
+
+func resetAuthThrottleForTest(key string) {
+ authThrottleLock.Lock()
+ delete(authThrottles, key)
+ authThrottleLock.Unlock()
+}