补齐Nginx辅助服务安全初始化与部署模板
This commit is contained in:
1 parent
aa5d669db1
commit
d8b4850916
13 files changed
+593
-4
No files matched your search
@@ -10,6 +10,7 @@ import (
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/nginxactivation"
|
||||
)
|
||||
@@ -57,12 +58,55 @@ func run(ctx context.Context, path string) error {
|
||||
return service.Serve(ctx, listener)
|
||||
}
|
||||
|
||||
func execute(ctx context.Context, arguments []string) error {
|
||||
flags := flag.NewFlagSet("scert-nginx", flag.ContinueOnError)
|
||||
flags.SetOutput(os.Stdout)
|
||||
flags.Usage = func() {
|
||||
fmt.Fprintln(flags.Output(), "用法:scert-nginx [参数];默认由 systemd socket 启动服务。")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
path := flags.String("policy", "/etc/scert-nginx/policy.json", "root 管理的独立激活策略文件")
|
||||
initialize := flags.Bool("initialize", false, "仅初始化专用证书材料,不重载 Nginx")
|
||||
chain := flags.String("certificate", "", "root 受保护的现有完整证书链文件")
|
||||
key := flags.String("private-key", "", "root 受保护的现有私钥文件")
|
||||
if err := flags.Parse(arguments); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if flags.NArg() != 0 || *path == "" {
|
||||
return errors.New("不接受位置参数,策略路径不能为空")
|
||||
}
|
||||
if !*initialize {
|
||||
if *chain != "" || *key != "" {
|
||||
return errors.New("证书材料参数仅用于显式初始化")
|
||||
}
|
||||
return run(ctx, *path)
|
||||
}
|
||||
if *chain == "" || *key == "" {
|
||||
return errors.New("初始化必须同时提供证书和私钥路径")
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
return errors.New("Nginx 激活目录初始化必须由 root 执行")
|
||||
}
|
||||
policy, err := nginxactivation.LoadPolicy(*path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取受信激活策略失败:%w", err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
if _, err := policy.Rotation().Initialize(ctx, *chain, *key); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("专用证书材料已初始化;尚未修改或重载 Nginx,请继续核对站点接线。")
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
path := flag.String("policy", "/etc/scert-nginx/policy.json", "root 管理的独立激活策略文件")
|
||||
flag.Parse()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := run(ctx, *path); err != nil {
|
||||
if err := execute(ctx, os.Args[1:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Nginx 本地激活服务启动或运行失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -11,6 +12,18 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExecuteRejectsInvalidInitializationArguments(t *testing.T) {
|
||||
for _, args := range [][]string{
|
||||
{"--initialize"}, {"--initialize", "--certificate", "/no-certificate"},
|
||||
{"--initialize", "--private-key", "/no-key"}, {"--certificate", "/no-certificate"},
|
||||
{"--private-key", "/no-key"}, {"--policy", ""}, {"unexpected"},
|
||||
} {
|
||||
if err := execute(context.Background(), args); err == nil {
|
||||
t.Fatalf("无效初始化参数被接受:%v", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInheritedListener(t *testing.T) {
|
||||
if mode := os.Getenv("SCERT_LISTENER_TEST_CHILD"); mode != "" {
|
||||
os.Setenv("LISTEN_PID", strconv.Itoa(os.Getpid()))
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNginxActivationDeploymentPolicy(t *testing.T) {
|
||||
for name, required := range map[string][]string{
|
||||
"scert-nginx.socket": {
|
||||
"ListenStream=/run/scert-nginx/activation.sock", "Accept=no", "SocketUser=root",
|
||||
"SocketGroup=Scert", "SocketMode=0660", "DirectoryMode=0755", "RemoveOnStop=no",
|
||||
"Service=scert-nginx.service", "WantedBy=sockets.target",
|
||||
},
|
||||
"scert-nginx.service": {
|
||||
"Requires=scert-nginx.socket nginx.service", "PartOf=nginx.service", "User=root", "Group=root",
|
||||
"ExecStart=/usr/local/libexec/scert-nginx --policy /etc/scert-nginx/policy.json",
|
||||
"NoNewPrivileges=yes", "ProtectSystem=strict", "ProtectHome=yes", "PrivateTmp=yes",
|
||||
"CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_CHOWN", "AmbientCapabilities=",
|
||||
"RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6", "TimeoutStopSec=40",
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
data, err := os.ReadFile(filepath.Join("..", "..", "..", "deploy", "systemd", name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := strings.Split(activeUnitText(string(data)), "\n")
|
||||
for _, expected := range required {
|
||||
found := false
|
||||
for _, line := range lines {
|
||||
found = found || strings.TrimSpace(line) == expected
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("辅助服务模板缺少安全策略:%s", expected)
|
||||
}
|
||||
}
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "ListenStream=") && line != "ListenStream=/run/scert-nginx/activation.sock" {
|
||||
t.Errorf("辅助服务不应监听其他地址:%s", line)
|
||||
}
|
||||
if strings.HasPrefix(line, "ExecStart=/scert/") || strings.HasPrefix(line, "ExecStartPre=") || strings.Contains(line, "--initialize") {
|
||||
t.Errorf("辅助服务不应执行应用目录程序或隐式初始化:%s", line)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join("..", "..", "..", "deploy", "nginx", "policy.json.example"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var policy struct {
|
||||
AllowedUID *uint32 `json:"allowed_uid"`
|
||||
SocketPath string `json:"socket_path"`
|
||||
Directory string `json:"directory"`
|
||||
Hostname string `json:"hostname"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &policy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if policy.AllowedUID != nil || policy.Hostname != "__MANAGEMENT_HOST__" || policy.SocketPath != "/run/scert-nginx/activation.sock" || policy.Directory != "/var/lib/scert-nginx" {
|
||||
t.Fatal("策略示例必须显式要求填写调用 UID 和域名,并匹配专用目录")
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@
|
||||
|
||||
## 接入前要求
|
||||
|
||||
发布包现提供独立 socket/service、拒绝直接使用的策略模板和 `--initialize` 命令。初始化从 root 受保护副本导入当前证书,核对双层 TLS 与就绪状态,仅创建专用材料,不修改或重载站点;已有状态或失败残留拒绝覆盖。部署步骤见 `deploy/nginx/Nginx辅助服务部署说明.md`,新增初始化用例尚待 Linux 执行,模板尚未完成 systemd 实机验收。
|
||||
|
||||
1. 安装独立 socket/service,固定调用 UID,初始化专用版本目录并让目标站点引用 `active.conf`。
|
||||
2. 应用须持久化旧状态、候选摘要、激活阶段和关联事务;完整生命周期必须串行化,不能在恢复检查上游之后并发切换上游。
|
||||
3. 覆盖代理暂存、上游配置持久化与内存切换、代理提交之间的中断及应答丢失,并在启动时先恢复再允许申请下一张证书。
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package nginxactivation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Initialize 仅准备首次接线材料,不修改站点、不重载 Nginx,也不覆盖已有状态。
|
||||
func (r Rotation) Initialize(ctx context.Context, certificatePath, privateKeyPath string) (string, error) {
|
||||
root, lock, err := r.open(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer root.Close()
|
||||
defer lock.Close()
|
||||
if err := requireUninitialized(root); err != nil {
|
||||
return "", err
|
||||
}
|
||||
chain, err := readInitializationMaterial(certificatePath, 1<<20, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
key, err := readInitializationMaterial(privateKeyPath, 64<<10, true)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer clear(key)
|
||||
leaf, err := r.validateMaterial(ctx, chain, key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := r.Proxy.Wait(ctx, leaf.Raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := r.Upstream.Wait(ctx, leaf.Raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := r.Reloader.Check(ctx); err != nil {
|
||||
return "", fmt.Errorf("初始化前 Nginx 配置检查失败:%w", err)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := requireUninitialized(root); err != nil {
|
||||
return "", err
|
||||
}
|
||||
id, err := newID()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := root.Mkdir(id, 0o700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := writeExclusive(root, filepath.Join(id, "fullchain.pem"), chain); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := writeExclusive(root, filepath.Join(id, "key.pem"), key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
version, err := root.Open(id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := errors.Join(version.Sync(), version.Close()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 最后独占创建引用;断电或写入失败后的残留必须人工核对,不能自动覆盖重试。
|
||||
if err := writeExclusive(root, includeName, renderInclude(r.Directory, id)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
directory, err := root.Open(".")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := errors.Join(directory.Sync(), directory.Close()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func requireUninitialized(root *os.Root) error {
|
||||
directory, err := root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer directory.Close()
|
||||
entries, err := directory.ReadDir(-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name() != ".activation.lock" {
|
||||
return errors.New("激活目录存在旧状态或初始化残留,拒绝覆盖,请先人工核对")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readInitializationMaterial(path string, limit int64, private bool) ([]byte, error) {
|
||||
if err := validateOwnedFile(path, uint32(os.Geteuid()), false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root, err := os.OpenRoot(filepath.Dir(path))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
if private {
|
||||
info, err := root.Lstat(filepath.Base(path))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if info.Mode().Perm()&0o077 != 0 {
|
||||
return nil, errors.New("初始化私钥不能允许组或其他用户读取")
|
||||
}
|
||||
}
|
||||
return readRegular(root, filepath.Base(path), limit)
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package nginxactivation
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/processlock"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func initializationFixture(t *testing.T) (*rotationFixture, string, string) {
|
||||
t.Helper()
|
||||
f := newRotationFixture(t)
|
||||
f.rotation.Directory = t.TempDir()
|
||||
if err := os.Chmod(f.rotation.Directory, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
material := t.TempDir()
|
||||
chain, key := filepath.Join(material, "fullchain.pem"), filepath.Join(material, "key.pem")
|
||||
writeTestFile(t, chain, f.old.chain)
|
||||
writeTestFile(t, key, f.old.key)
|
||||
return f, chain, key
|
||||
}
|
||||
|
||||
func TestInitializeCreatesPrivateBaselineWithoutReload(t *testing.T) {
|
||||
f, chain, key := initializationFixture(t)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
id, err := f.rotation.Initialize(ctx, chain, key)
|
||||
if err != nil || !validID(id) {
|
||||
t.Fatal("初始化失败或版本编号无效", err)
|
||||
}
|
||||
if f.reloader.reloadCount != 0 || f.reloader.checkCount != 1 {
|
||||
t.Fatal("初始化只能检查既有配置,不能重载")
|
||||
}
|
||||
for path, mode := range map[string]os.FileMode{
|
||||
id: 0o700, filepath.Join(id, "fullchain.pem"): 0o600,
|
||||
filepath.Join(id, "key.pem"): 0o600, includeName: 0o600,
|
||||
} {
|
||||
info, err := os.Lstat(filepath.Join(f.rotation.Directory, path))
|
||||
if err != nil || info.Mode().Perm() != mode {
|
||||
t.Fatalf("初始化材料权限错误:%s,%v", path, err)
|
||||
}
|
||||
}
|
||||
root, err := os.OpenRoot(f.rotation.Directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
include, err := readRegular(root, includeName, 4096)
|
||||
if err != nil || !bytes.Equal(include, renderInclude(f.rotation.Directory, id)) {
|
||||
t.Fatal("专用引用格式错误", err)
|
||||
}
|
||||
if err := verifyIncludeMaterial(root, include, f.old.pair.Certificate[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(f.rotation.Directory, journalName)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("初始化不应创建轮换事务", err)
|
||||
}
|
||||
if _, err := f.rotation.Initialize(ctx, chain, key); err == nil {
|
||||
t.Fatal("不能重复初始化已有状态")
|
||||
}
|
||||
if err := requireInclude(root, include); err != nil {
|
||||
t.Fatal("重复初始化改变了原引用", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeRejectsUnsafeMaterial(t *testing.T) {
|
||||
for _, scenario := range []string{
|
||||
"key-readable", "key-writable", "parent-writable", "symlink", "hardlink", "fifo",
|
||||
"large", "mismatch", "different-leaf", "upstream-mismatch", "relative", "missing",
|
||||
} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
f, chain, key := initializationFixture(t)
|
||||
switch scenario {
|
||||
case "key-readable", "key-writable", "parent-writable":
|
||||
path, mode := key, os.FileMode(0o644)
|
||||
if scenario == "key-writable" {
|
||||
mode = 0o666
|
||||
}
|
||||
if scenario == "parent-writable" {
|
||||
path, mode = filepath.Dir(key), 0o777
|
||||
}
|
||||
if err := os.Chmod(path, mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "symlink":
|
||||
if err := os.Symlink(key, key+".link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key += ".link"
|
||||
case "hardlink":
|
||||
if err := os.Link(key, key+".link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "fifo":
|
||||
key += ".fifo"
|
||||
if err := unix.Mkfifo(key, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "large":
|
||||
writeTestFile(t, chain, make([]byte, (1<<20)+1))
|
||||
case "mismatch":
|
||||
writeTestFile(t, key, f.candidate.key)
|
||||
case "different-leaf":
|
||||
writeTestFile(t, chain, f.candidate.chain)
|
||||
writeTestFile(t, key, f.candidate.key)
|
||||
case "upstream-mismatch":
|
||||
f.upstream.active.Store(&f.candidate.pair)
|
||||
case "relative":
|
||||
key = "key.pem"
|
||||
case "missing":
|
||||
key += ".missing"
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
|
||||
defer cancel()
|
||||
if _, err := f.rotation.Initialize(ctx, chain, key); err == nil {
|
||||
t.Fatal("不应接受不可信或不一致的初始化材料")
|
||||
}
|
||||
if f.reloader.checkCount != 0 || f.reloader.reloadCount != 0 {
|
||||
t.Fatal("材料预检失败不应执行 Nginx 命令")
|
||||
}
|
||||
assertInitializationEmpty(t, f.rotation.Directory)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializePreservesExistingState(t *testing.T) {
|
||||
for _, scenario := range []string{"include", "transaction", "partial", "external-change", "config-failure", "cancel", "locked"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
f, chain, key := initializationFixture(t)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
name, content := "", []byte("保留原有状态\n")
|
||||
switch scenario {
|
||||
case "include", "transaction", "partial":
|
||||
name = map[string]string{"include": includeName, "transaction": journalName, "partial": ".pending-old"}[scenario]
|
||||
writeTestFile(t, filepath.Join(f.rotation.Directory, name), content)
|
||||
case "external-change":
|
||||
name = includeName
|
||||
f.reloader.check = func(int) error {
|
||||
writeTestFile(t, filepath.Join(f.rotation.Directory, name), content)
|
||||
return nil
|
||||
}
|
||||
case "config-failure":
|
||||
f.reloader.check = func(int) error { return errors.New("注入配置检查失败") }
|
||||
case "cancel":
|
||||
cancel()
|
||||
case "locked":
|
||||
lock, err := processlock.Acquire(filepath.Join(f.rotation.Directory, ".activation.lock"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lock.Close()
|
||||
}
|
||||
if _, err := f.rotation.Initialize(ctx, chain, key); err == nil {
|
||||
t.Fatal("已有状态、取消或故障不应初始化成功")
|
||||
}
|
||||
if f.reloader.reloadCount != 0 {
|
||||
t.Fatal("初始化不能重载 Nginx")
|
||||
}
|
||||
if name == "" {
|
||||
assertInitializationEmpty(t, f.rotation.Directory)
|
||||
return
|
||||
}
|
||||
actual, err := os.ReadFile(filepath.Join(f.rotation.Directory, name))
|
||||
if err != nil || !bytes.Equal(actual, content) {
|
||||
t.Fatal("初始化不能覆盖已有状态", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertInitializationEmpty(t *testing.T, directory string) {
|
||||
t.Helper()
|
||||
root, err := os.OpenRoot(directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
if err := requireUninitialized(root); err != nil {
|
||||
t.Fatal("预检失败不应留下证书或引用", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user