Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
dcbf6dc
build(deps): update Go security dependencies
SoraKasvgano Oct 7, 2026
3942b19
build(deps): update frontend security dependencies
SoraKasvgano Oct 7, 2026
fa69c99
fix(location): verify TLS and bound IP lookup resources
SoraKasvgano Oct 7, 2026
91dc89e
fix(dev): default the frontend proxy and listener to localhost
SoraKasvgano Oct 7, 2026
cabd812
fix(api): enforce authorization on registered private routes
SoraKasvgano Oct 7, 2026
e2f418e
fix(auth): expire, hash and revoke web sessions
SoraKasvgano Oct 7, 2026
9311e0e
fix(auth): migrate password hashes and use secure random secrets
SoraKasvgano Oct 7, 2026
62ebc13
fix(http): recover panics without disclosing request secrets
SoraKasvgano Oct 7, 2026
a2a2e6b
fix(http): trust forwarded client addresses only from configured proxies
SoraKasvgano Oct 7, 2026
9f3a08f
fix(auth): require an operator secret for initial administrator setup
SoraKasvgano Oct 7, 2026
b08cf2d
fix(auth): bound failed attempts and concurrent password work
SoraKasvgano Oct 7, 2026
e3fbe2b
fix(api): enforce resource ownership and deleted tenant boundaries
SoraKasvgano Oct 7, 2026
201d2fa
fix(storage): restrict permissions for newly created database files
SoraKasvgano Oct 7, 2026
e36c621
fix(http): validate API origins, request bodies and response headers
SoraKasvgano Oct 7, 2026
6e863c4
fix(http): bound server timeouts and require modern TLS
SoraKasvgano Oct 7, 2026
a8febd6
fix(tunnel): validate signed authentication timestamps
SoraKasvgano Oct 7, 2026
f646ceb
fix(tunnel): validate upgrade routes and websocket frame boundaries
SoraKasvgano Oct 7, 2026
e7fb6fa
fix(tunnel): enforce authenticated connection lifecycle and revocation
SoraKasvgano Oct 7, 2026
6e1d2d1
fix(tunnel): validate DHCP inputs and bound address allocation
SoraKasvgano Oct 7, 2026
a549b7c
fix(tunnel): bound failed authentication attempts per client IP
SoraKasvgano Oct 7, 2026
b0d1b8c
fix(ui): guard navigation with current session and role
SoraKasvgano Oct 7, 2026
6716410
fix(ui): handle failed login requests and prevent duplicate submissions
SoraKasvgano Oct 7, 2026
36b214c
fix(ui): mask network passwords in forms and tables
SoraKasvgano Oct 7, 2026
141d5e0
docs(security): document deployment and compatibility guidance
SoraKasvgano Oct 7, 2026
4f4b11c
feat(storage): serialize SQLite writes with durable group commits
SoraKasvgano Oct 7, 2026
c935ce2
fix(storage): commit business mutations atomically before responding
SoraKasvgano Oct 7, 2026
70a1a1a
feat(storage): enforce active identities and parent integrity
SoraKasvgano Oct 7, 2026
f8a62d1
feat(model): coalesce device state with generation-safe persistence
SoraKasvgano Oct 7, 2026
593247f
perf(candy): persist device telemetry in shared batches
SoraKasvgano Oct 7, 2026
4b82b66
perf(api): aggregate user statistics with fixed query counts
SoraKasvgano Oct 7, 2026
592efc3
feat(background): add observable non-overlapping task scheduler
SoraKasvgano Oct 7, 2026
54af651
feat(model): add bounded cleanup and integrity audits
SoraKasvgano Oct 7, 2026
393e654
refactor(background): run maintenance through the shared scheduler
SoraKasvgano Oct 7, 2026
3b27fce
feat(admin): inspect and trigger background maintenance tasks
SoraKasvgano Oct 7, 2026
96ef3f1
fix(server): drain websocket state and storage during shutdown
SoraKasvgano Oct 7, 2026
6d4f202
style(i18n): normalize translation indentation
SoraKasvgano Oct 7, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
cacao
cacao-*
sqlite.db
sqlite.db-wal
sqlite.db-shm
cookie
*.mmdb
*.crt
Expand Down
61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Candy Server with WebUI

## Build

Requires Go 1.25 or newer and Node.js/npm for the frontend build.

```bash
# build a binary that runs natively
make
Expand All @@ -21,3 +23,62 @@ cacao
# loglevel=[debug] listen=[127.0.0.1:8080] storage=[/var/lib/cacao]
cacao --loglevel=debug --listen=127.0.0.1:8080 --storage=/var/lib/cacao
```

## 公网访问加固

默认监听地址仍为 `:80`(存储目录存在证书与私钥时为 `:443`)。已有账号、网络密码、客户端报文格式及子网转发保持兼容;不需要重新注册或修改网络密钥。

- 登录、首次初始化和修改密码按来源 IP 与账号累计认证失败,达到每分钟 30 次后暂时返回 HTTP 429,带 `Retry-After`。登录/改密最多并行执行 8 次密码校验,超出时提示稍后重试,避免并发爆破耗尽 CPU。成功认证不累计失败;普通业务 API 和已建立的隧道不受该限速影响。
- Candy WebSocket 每 IP 每分钟最多容许 60 次失败认证;新连接需在 15 秒内完成认证,报文最大 64 KiB。正常转发与成功重连不累计失败次数。客户端与服务器应保持时间同步,签名时间允许前后 5 分钟偏差。
- 所有私有 API 在服务端校验登录与角色,并校验网络、设备、路由的归属。登录页和注册页可以公开访问,不会因此授予业务权限。
- Web 会话在服务端 24 小时后失效。升级时已有会话获得一次 24 小时宽限期,无需立即退出;旧密码在下一次成功登录时自动迁移为加盐的 bcrypt 哈希。退出、修改密码、管理员重置密码都会撤销对应旧会话。
- Cookie 使用 HttpOnly、SameSite=Lax;直接 HTTPS 访问自动加 Secure。API 响应不缓存,并拒绝跨站请求、非 JSON 的非空请求体及超过 1 MiB 的请求。

### 反向代理部署

**使用反向代理时必须显式设置 `--trusted-proxies` 为实际代理的 IP/CIDR**,并让代理覆盖客户端传来的转发头。默认不信任 `X-Forwarded-For` / `X-Real-IP`,防止攻击者伪造地址绕过限速。未配置时,同一代理后的用户共享来源 IP 的失败额度;不要将全部公网地址设为可信代理。

例如,同机 Nginx 终止 HTTPS 时:

```bash
cacao --listen=127.0.0.1:8080 --storage=/var/lib/cacao --trusted-proxies=127.0.0.1,::1 --secure-cookies=true
```

在已有 HTTPS `server` 中保留原域名和客户端路径,并配置:

```nginx
# Place this map in the http context.
map $http_upgrade $cacao_connection {
default upgrade;
'' close;
}

# Place this location in the existing HTTPS server context.
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $cacao_connection;
proxy_read_timeout 75s;
}
```

`--secure-cookies=true` 仅适用于浏览器确实通过 HTTPS 访问的部署,否则浏览器不会通过 HTTP 发送登录 Cookie。公网应使用 HTTPS/WSS,并在代理或防火墙限制后端端口直连。程序不自动改变已有 HTTP/WS 客户端地址;切换 TLS 前先确认现有客户端配置。时间窗口内的签名重放仍依赖 WSS 防止报文被截获,彻底防重放需要升级客户端协议。

### 首次安装

只有空数据库首次创建管理员时需要初始化密钥;已有安装不需要设置。启动前设置至少 32 字符的随机密钥,例如:

```bash
export CACAO_SETUP_TOKEN="$(openssl rand -hex 32)"
cacao --listen=127.0.0.1:8080 --storage=/var/lib/cacao
```

通过本机访问或配置好 HTTPS 后,在注册页填写此密钥以创建首个管理员。初始化后可从环境中移除该密钥。普通注册默认关闭,已有管理员设置的开放注册状态会保留。

升级前备份存储目录,并在使用相同代理与客户端的测试环境验证。身份认证限速在单进程内生效,重启后计数清空;多实例或大规模流量攻击需同时在入口代理实施防护。开发服务器默认只监听本机,不应作为公网生产入口。

安全回归检查:`go test ./...`、`go vet ./...`;前端在 `frontend` 下运行 `npm test`、`npm run build` 和 `npm audit --omit=dev`。
38 changes: 38 additions & 0 deletions SECURITY_REVIEW.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# 公网访问安全加固记录

检查日期:2026-10-06。范围为本仓库代码与本地回归验证,没有修改线上服务。

本次以保留已有账号、网络密码、监听默认值、Candy 报文格式和子网转发行为为约束。登录/注册页可以公开访问,数据权限由服务端判断。成功认证、普通业务 API、已建立隧道不累计认证失败次数;认证失败过多或密码计算并发超过上限时返回可重试的 429。

## 已修复的问题

| 问题 | 原有风险 | 修复 |
| --- | --- | --- |
| 首次注册自动成为管理员 | 新部署公开后可能被抢先接管 | 空数据库初始化必须提供部署者设置的随机密钥;初始化串行化;已初始化数据库不能重复引导管理员 |
| Candy 认证状态不完整 | 完成 VMAC 后、完成 AUTH 前可以发出 PEER 报文;重复身份报文可能破坏连接状态 | 显式认证状态控制,业务报文必须完成 AUTH,禁止重复身份切换 |
| 无爆破防护、默认信任代理头 | 可以持续猜测凭据,并伪造来源地址绕过按 IP 限制 | HTTP 按 IP/账号累计失败,WebSocket 按 IP 累计失败;限速表有界且不能在满表时绕过;只信任显式配置的代理 |
| 会话无服务端期限、重置密码不撤销令牌 | 被窃取令牌可长期使用,管理员改密后仍有效 | 24 小时会话期限、令牌哈希存储、密码重置撤销会话;旧会话迁移不刷新业务活跃时间 |
| 密码快速确定性哈希、弱随机网络密钥 | 数据库泄漏后的离线猜测成本较低 | 旧密码登录后迁移为 bcrypt;保留长密码兼容;新随机密钥使用密码学随机源 |
| 对象与删除状态检查不足 | 零 ID 查询可能误选记录;越权设备查询暴露在线状态;已删除用户的网络仍可能接入 | 显式 ID 条件、先校验对象归属、过滤软删除用户/网络,并撤销关联连接 |
| 空帧、DHCP 边界、无资源上限 | 异常请求可能触发 panic、耗尽地址池循环、占用内存或连接 | 修复解析边界和有界 DHCP 分配;限制帧/HTTP 请求体/请求头,设置鉴权期限和读写超时 |
| 页面和请求缺少纵深防护 | 点击劫持、跨站请求、缓存敏感响应、前端直接显示管理页 | 安全响应头、同源校验、JSON 请求约束、Cookie 属性、响应禁止缓存、前端会话与角色守卫 |
| 开发代理默认指向第三方服务 | 本地开发登录凭据可能被发送至第三方 | 默认代理到本机,可显式覆盖目标 |

## 验证结果

- `go test ./... -count=1`、`go vet ./...` 通过。
- Linux amd64、关闭 CGO 的生产程序构建通过。
- HTTP 回归覆盖全部私有 API 的匿名访问、普通用户访问管理员接口、跨用户对象操作、旧密码/会话迁移、首次初始化、密码重置撤销、失败限速、代理头伪造和 CSRF。
- Candy 回归覆盖正常认证、子网转发、重连、改密撤销、未认证业务报文、空/超大帧、DHCP 边界、同源限制、限速表饱和,以及用户名 `api` 的原有网络路径。
- 前端 6 项权限导航测试、构建、修改文件的 ESLint 检查通过;真实 Edge 在严格 CSP 下验证注册页及匿名管理页跳转,未出现 CSP 违规。
- 更新 Go 依赖后,`govulncheck` 未发现当前程序可达或导入包中的已知漏洞;依赖模块中仍有 18 项未被当前代码调用的告警。
- `npm audit --omit=dev` 为 0;全量审计仍有 9 项开发工具链告警,需要另行进行大版本迁移。开发服务器不应公开部署。
- 当前 Windows 环境未启用 CGO 且没有 C 编译器,未执行 Go race 检测;常规测试包含连接替换和撤销回归。

## 部署与兼容性

构建要求提高到 Go 1.25,以使用网络/文本库的漏洞修复版本。已有密码和会话有迁移兼容,默认监听仍为 `:80` / `:443`。升级前备份数据库,在与生产相同的代理和客户端环境中验证。

反向代理必须配置实际的 `--trusted-proxies`,保留 Host 并覆盖客户端来源头,否则代理后的用户共享失败额度。仅在浏览器确实使用 HTTPS 时开启 `--secure-cookies=true`。空数据库首次部署还需 `CACAO_SETUP_TOKEN`。具体配置见 [README](README.md#公网访问加固)。

已建立的隧道不受认证限速影响;被猜测的同一账号或同一来源 IP 在失败窗口内可能暂时无法新登录。限速状态仅保存在当前进程;多实例和大规模流量攻击需入口层配合。签名时间校验允许前后 5 分钟;窗口内的截获重放仍需 WSS 防护,完全消除需要升级客户端协议。
142 changes: 70 additions & 72 deletions api/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,44 @@ import (
"time"

"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/lanthora/cacao/candy"
"github.com/lanthora/cacao/model"
"github.com/lanthora/cacao/storage"
"gorm.io/gorm"
)

func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.String()
if strings.HasPrefix(path, "/api/") {
if user, ok := c.Get("user"); ok {
user := user.(*model.User)
if strings.HasPrefix(path, "/api/admin/") {
if user.Role == "admin" {
c.Next()
} else {
setErrorCode(c, PermissionDenied)
c.Abort()
}
} else if path == "/api/user/info" || path == "/api/user/logout" {
c.Next()
} else if user.Role == "normal" {
c.Next()
} else {
setErrorCode(c, PermissionDenied)
c.Abort()
}
}
value, ok := c.Get("user")
user, valid := value.(*model.User)
if !ok || !valid || user == nil {
setErrorCode(c, NotLoggedIn)
c.Abort()
return
}
path := c.FullPath()
allowed := false
if strings.HasPrefix(path, "/api/admin/") {
allowed = user.Role == "admin"
} else if path == "/api/user/info" || path == "/api/user/logout" || path == "/api/user/changePassword" {
allowed = user.Role == "admin" || user.Role == "normal"
} else {
allowed = user.Role == "normal"
}
if !allowed {
setErrorCode(c, PermissionDenied)
c.Abort()
return
}
c.Next()
}
}

func AdminShowUsers(c *gin.Context) {
users := model.GetUsers()
users, err := model.GetUsersWithStatistics()
if !writeSucceeded(c, err) {
return
}

type userinfo struct {
UserID uint `json:"userid"`
Expand All @@ -60,11 +64,11 @@ func AdminShowUsers(c *gin.Context) {
Username: u.Name,
Role: u.Role,
RegTime: u.CreatedAt.Format(time.DateTime),
LastActiveTime: model.GetLastActiveTimeByUserID(u.ID).Format(time.DateTime),
NetNum: uint(len(model.GetNetsByUserID(u.ID))),
DevNum: uint(len(model.GetDevicesByUserID(u.ID))),
RxSum: model.GetRxSumByUserID(u.ID),
TxSum: model.GetTxSumByUserID(u.ID),
LastActiveTime: u.UpdatedAt.Format(time.DateTime),
NetNum: u.NetNum,
DevNum: u.DevNum,
RxSum: u.RxSum,
TxSum: u.TxSum,
})
}

Expand All @@ -91,42 +95,25 @@ func AdminAddUser(c *gin.Context) {
return
}

db := storage.Get()
if func() bool {
count := int64(0)
db.Model(&model.User{}).Where(&model.User{Name: request.Username}).Count(&count)
return count > 0
}() {
setErrorCode(c, UsernameAlreadyTaken)
return
}

user := model.User{
Name: request.Username,
Password: hashUserPassword(request.Username, request.Password),
Token: uuid.NewString(),
Role: "normal",
}

if result := db.Create(&user); result.Error != nil {
setUnexpectedMessage(c, result.Error.Error())
return
}

setResponseData(c, gin.H{
"name": user.Name,
"role": user.Role,
})

netModel := &model.Net{
UserID: user.ID,
Name: "@",
Password: randomString(8),
DHCP: "192.168.202.0/24",
Broadcast: true,
}
netModel.Create()
candy.InsertNet(netModel)
if !writeSucceeded(c, createAccount(c, &user, netModel, false, false)) {
return
}
if !writeSucceeded(c, candy.SyncNet(netModel.ID)) {
return
}
setResponseData(c, gin.H{"name": user.Name, "role": user.Role})
}

func AdminDeleteUser(c *gin.Context) {
Expand All @@ -145,13 +132,13 @@ func AdminDeleteUser(c *gin.Context) {
return
}

nets := model.GetNetsByUserID(request.UserID)
for _, n := range nets {
candy.DeleteNet(n.ID)
model.DeleteDevicesByNetID(n.ID)
model.DeleteNetByNetID(n.ID)
netIDs, err := model.DeleteUserTree(request.UserID)
if !writeSucceeded(c, err) {
return
}
for _, id := range netIDs {
candy.DeleteNet(id)
}
model.DeleteUserByUserID(request.UserID)
setResponseData(c, nil)
}

Expand Down Expand Up @@ -179,13 +166,25 @@ func AdminUpdateUserPassword(c *gin.Context) {
setErrorCode(c, Unexpected)
return
}
user.Password = hashUserPassword(user.Name, request.Password)
user.Save()
password := hashUserPassword(user.Name, request.Password)
err := storage.WriteContext(c.Request.Context(), func(tx *gorm.DB) error {
result := tx.Model(&model.User{}).Where("id = ?", user.ID).Updates(map[string]interface{}{"password": password, "token": "", "token_expires_at": nil})
if result.Error != nil {
return result.Error
}
if result.RowsAffected != 1 {
return businessError(UserNotExists)
}
return nil
})
if !writeSucceeded(c, err) {
return
}
setResponseData(c, nil)
}

func AdminGetOpenRegisterConfig(c *gin.Context) {
openreg := model.GetConfig("openreg", "true") == "true"
openreg := model.GetConfig("openreg", "false") == "true"
setResponseData(c, gin.H{
"openreg": openreg,
})
Expand All @@ -199,10 +198,8 @@ func AdminSetOpenRegisterConfig(c *gin.Context) {
setErrorCode(c, InvalidRequest)
return
}
if request.OpenReg {
model.SetConfig("openreg", "true")
} else {
model.SetConfig("openreg", "false")
if !writeSucceeded(c, model.SetConfig("openreg", strconv.FormatBool(request.OpenReg))) {
return
}
setResponseData(c, nil)
}
Expand All @@ -227,7 +224,9 @@ func AdminSetRegisterIntervalConfig(c *gin.Context) {
return
}

model.SetConfig("reginterval", strconv.FormatUint(uint64(request.RegInterval), 10))
if !writeSucceeded(c, model.SetConfig("reginterval", strconv.FormatUint(uint64(request.RegInterval), 10))) {
return
}
setResponseData(c, nil)
}

Expand All @@ -246,10 +245,8 @@ func AdminSetAutoCleanUserConfig(c *gin.Context) {
setErrorCode(c, InvalidRequest)
return
}
if request.AutoCleanInactiveUser {
model.SetConfig("autoCleanUser", "true")
} else {
model.SetConfig("autoCleanUser", "false")
if !writeSucceeded(c, model.SetConfig("autoCleanUser", strconv.FormatBool(request.AutoCleanInactiveUser))) {
return
}
setResponseData(c, nil)
}
Expand Down Expand Up @@ -278,11 +275,12 @@ func AdminSetInactiveUserThresholdConfig(c *gin.Context) {
return
}

model.SetConfig("inactiveUserThreshold", strconv.FormatUint(uint64(request.InactiveUserThreshold), 10))
if !writeSucceeded(c, model.SetConfig("inactiveUserThreshold", strconv.FormatUint(uint64(request.InactiveUserThreshold), 10))) {
return
}
setResponseData(c, nil)
}

func AdminCleanInactiveUser(c *gin.Context) {
candy.CleanInactiveUser()
setResponseData(c, nil)
triggerBackgroundTask(c, "clean-inactive-users")
}
Loading