1 parent
48f4b24781
commit
a045a0cd17
27 files changed
+1209
-24
No files matched your search
@@ -9,8 +9,12 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/utils/runtimepath"
|
||||
)
|
||||
|
||||
// InitializeDeployment 仅对全新安装启用新布局,不触碰已有部署或生成替代密钥。
|
||||
// InitializeDeployment 为全新部署创建状态库,并自动归档已采用 ssl 布局的原有业务密钥。
|
||||
// 更旧的 config/data 布局仍需完整迁移,不能只搬密钥而切断证书或数据库引用。
|
||||
func InitializeDeployment(root string) error {
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
return initializeDeploymentKeys(root)
|
||||
}
|
||||
for _, name := range []string{"config/config.json", "data/credential.key", "config/credential.key"} {
|
||||
if _, err := os.Lstat(filepath.Join(root, filepath.FromSlash(name))); err == nil {
|
||||
return nil
|
||||
@@ -22,7 +26,19 @@ func InitializeDeployment(root string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Close()
|
||||
if err := db.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return initializeDeploymentKeys(root)
|
||||
}
|
||||
|
||||
func initializeDeploymentKeys(root string) error {
|
||||
unlock, err := NewTransactionStore(root, RuntimeValidationOptions{}).lockState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unlock()
|
||||
return runtimepath.PrepareDeploymentKeys(root)
|
||||
}
|
||||
|
||||
// ImportDeploymentHistory 在停服迁移期间导入旧历史原始字节,原目录保持不动。
|
||||
|
||||
@@ -224,10 +224,15 @@ func (m *ConfigManager) Load(ctx context.Context) error {
|
||||
}
|
||||
now := runtime.LoadedAt
|
||||
m.mu.Lock()
|
||||
previousPending := m.pending
|
||||
m.current = runtime
|
||||
m.pending = nil
|
||||
m.status = ConfigStatus{SetupState: runtime.SetupState, ActiveGeneration: runtime.Generation, LastValidAt: &now}
|
||||
m.mu.Unlock()
|
||||
if previousPending != nil {
|
||||
releaseManagedSSL(m.loader.root, previousPending.Candidate.SSL.TLS)
|
||||
}
|
||||
maintainManagedSSL(m.loader.root, runtime.SSL.TLS)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -458,6 +463,7 @@ func (m *ConfigManager) apply(ctx context.Context, generation uint64, actor Audi
|
||||
pendingRestart := append([]ServiceName(nil), m.status.PendingRestart...)
|
||||
m.status = ConfigStatus{SetupState: candidate.SetupState, ActiveGeneration: candidate.Generation, LastValidAt: &now, PendingRestart: pendingRestart}
|
||||
m.mu.Unlock()
|
||||
maintainManagedSSL(m.loader.root, candidate.SSL.TLS, current.SSL.TLS)
|
||||
if err := m.writeAudit(ctx, ConfigAuditEvent{
|
||||
Operation: ConfigOperationUpdate,
|
||||
Section: pending.Section,
|
||||
@@ -514,6 +520,9 @@ func (m *ConfigManager) PreviewRollback(ctx context.Context, generation uint64,
|
||||
if err := ValidateRuntimeSecrets(m.vault, backup); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateRollbackSSL(m.loader.root, backup); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RollbackPreview{
|
||||
CurrentGeneration: currentGeneration,
|
||||
TargetGeneration: generation,
|
||||
@@ -552,6 +561,9 @@ func (m *ConfigManager) IssueRollbackTicket(ctx context.Context, generation uint
|
||||
if err := ValidateRuntimeSecrets(m.vault, backup); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := validateRollbackSSL(m.loader.root, backup); err != nil {
|
||||
return "", err
|
||||
}
|
||||
token, err := newRollbackTicketID()
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -671,6 +683,9 @@ func (m *ConfigManager) rollbackWithState(ctx context.Context, generation uint64
|
||||
if err := ValidateRuntimeSecrets(m.vault, candidate); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if err := validateRollbackSSL(m.loader.root, candidate); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
setCandidateGeneration(&candidate, current.Generation+1)
|
||||
candidate.Root.UpdatedAt = time.Now().UTC()
|
||||
if err := ValidateRuntimeConfig(candidate, m.options); err != nil {
|
||||
@@ -705,6 +720,7 @@ func (m *ConfigManager) rollbackWithState(ctx context.Context, generation uint64
|
||||
PendingRestart: []ServiceName{ServiceDatabase, ServiceHTTP, ServiceSMTP, ServiceEmail, ServiceSSL, ServicePlugins},
|
||||
}
|
||||
m.mu.Unlock()
|
||||
maintainManagedSSL(m.loader.root, candidate.SSL.TLS, current.SSL.TLS)
|
||||
if err := m.writeAudit(ctx, ConfigAuditEvent{
|
||||
Operation: ConfigOperationRollback,
|
||||
Section: SectionRoot,
|
||||
|
||||
@@ -78,7 +78,7 @@ func (m *ConfigManager) ManagePending(ctx context.Context, generation uint64, id
|
||||
return err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
activeSSL := m.current.SSL.TLS
|
||||
if cancel {
|
||||
m.pending = nil
|
||||
m.status.PendingRestart = append([]ServiceName(nil), pending.PreviousRestart...)
|
||||
@@ -86,5 +86,10 @@ func (m *ConfigManager) ManagePending(ctx context.Context, generation uint64, id
|
||||
m.pending.Actor = actor
|
||||
m.pending.Confirmation = confirmation
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if cancel {
|
||||
releaseManagedSSL(m.loader.root, pending.Candidate.SSL.TLS)
|
||||
maintainManagedSSL(m.loader.root, activeSSL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -10,8 +10,12 @@ var runtimeManager struct {
|
||||
// SetRuntimeManager 注入当前进程使用的配置管理器。
|
||||
func SetRuntimeManager(manager *ConfigManager) {
|
||||
runtimeManager.Lock()
|
||||
previous := runtimeManager.value
|
||||
runtimeManager.value = manager
|
||||
runtimeManager.Unlock()
|
||||
if previous != nil && previous != manager {
|
||||
previous.releasePendingSSL()
|
||||
}
|
||||
}
|
||||
|
||||
// CurrentManager 返回当前配置管理器;未完成分区配置初始化时返回 nil。
|
||||
|
||||
@@ -54,6 +54,7 @@ func WriteSSLConfig(expected, next *Config) error {
|
||||
return err
|
||||
}
|
||||
*next = merged
|
||||
maintainManagedSSL(ROOT_PATH, next.SSL, expected.SSL)
|
||||
return nil
|
||||
}
|
||||
manager := CurrentManager()
|
||||
@@ -134,6 +135,7 @@ func WriteSSLConfig(expected, next *Config) error {
|
||||
// 兼容快照与本次已提交候选一致,不再静默忽略提交后的磁盘读取失败。
|
||||
*next = *committed
|
||||
PublishConfigSnapshot(committed)
|
||||
maintainManagedSSL(ROOT_PATH, candidate.SSL.TLS, current.SSL.TLS)
|
||||
return manager.writeAudit(context.Background(), ConfigAuditEvent{
|
||||
Operation: ConfigOperationUpdate, Section: SectionSSL, ActorID: "system", ActorRole: "system",
|
||||
FromGeneration: current.Generation, ToGeneration: candidate.Generation,
|
||||
|
||||
@@ -189,6 +189,8 @@ func SSLCertificateDomains(primary, web string, accepted []string) []string {
|
||||
func SSLValidationIssue(err error) (PublicIssue, bool) {
|
||||
issue := PublicIssue{Code: "SSL_INVALID"}
|
||||
switch {
|
||||
case errors.Is(err, ErrSSLHistoryUnavailable):
|
||||
issue.Message = "历史证书已清理或不可用,请重新导入有效证书,不能回滚此配置"
|
||||
case errors.Is(err, ErrSSLFileUnavailable):
|
||||
issue.Message = "证书或私钥文件不存在或无法读取,请检查服务器路径和运行用户权限"
|
||||
case errors.Is(err, ErrSSLCertificateMismatch):
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !windows
|
||||
|
||||
package config
|
||||
|
||||
import "os"
|
||||
|
||||
func openSSLLease(path string) (*os.File, error) {
|
||||
return os.OpenFile(path, os.O_RDWR, 0600)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build windows
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// 共享删除权限仅避免旧版停服迁移被文件句柄阻挡;是否清理由独占租约决定。
|
||||
func openSSLLease(path string) (*os.File, error) {
|
||||
name, err := windows.UTF16PtrFromString(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handle, err := windows.CreateFile(name, windows.GENERIC_READ|windows.GENERIC_WRITE,
|
||||
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
|
||||
nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return os.NewFile(uintptr(handle), path), nil
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/runtimepath"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// 清理与写入共用互斥锁;暂存材料从创建到提交或取消期间始终受到保护。
|
||||
var managedSSLStorage = struct {
|
||||
sync.Mutex
|
||||
staged map[string]func()
|
||||
}{staged: make(map[string]func())}
|
||||
|
||||
type retainedSSLVersion struct {
|
||||
directory string
|
||||
modified time.Time
|
||||
}
|
||||
|
||||
func releaseManagedSSL(root string, ssl SSLConfig) {
|
||||
managedSSLStorage.Lock()
|
||||
defer managedSSLStorage.Unlock()
|
||||
releaseManagedSSLLocked(root, ssl)
|
||||
}
|
||||
|
||||
func releaseManagedSSLLocked(root string, ssl SSLConfig) {
|
||||
if ssl.CertificateRef == "" {
|
||||
return
|
||||
}
|
||||
path, err := filepath.Abs(filepath.Join(root, filepath.FromSlash(runtimepath.SSLReference(root, ssl.CertificateRef))))
|
||||
if err == nil {
|
||||
directory := filepath.Dir(path)
|
||||
if release := managedSSLStorage.staged[directory]; release != nil {
|
||||
release()
|
||||
delete(managedSSLStorage.staged, directory)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ReleaseStagedSSL 仅解除暂存保护,不立即删除;失败操作的残留由下一轮维护处理。
|
||||
func ReleaseStagedSSL(reference ManagedSSLReference) {
|
||||
releaseManagedSSL(ROOT_PATH, SSLConfig{CertificateRef: reference.CertificateRef})
|
||||
}
|
||||
|
||||
// 管理器停止或被替换时解除遗留租约;不删除材料,已提交引用仍由磁盘配置保护。
|
||||
func (m *ConfigManager) releasePendingSSL() {
|
||||
m.writeMu.Lock()
|
||||
defer m.writeMu.Unlock()
|
||||
m.mu.Lock()
|
||||
pending := m.pending
|
||||
m.pending = nil
|
||||
m.mu.Unlock()
|
||||
if pending != nil && m.loader != nil {
|
||||
releaseManagedSSL(m.loader.root, pending.Candidate.SSL.TLS)
|
||||
}
|
||||
}
|
||||
|
||||
// maintainManagedSSL 必须在配置写锁内调用;失败只告警,不能把已保存配置误报为未保存。
|
||||
func maintainManagedSSL(root string, active SSLConfig, previous ...SSLConfig) {
|
||||
managedSSLStorage.Lock()
|
||||
defer managedSSLStorage.Unlock()
|
||||
// 与其他进程的配置事务互斥;锁定后再读取生效引用及恢复状态。
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
unlock, err := NewTransactionStore(root, RuntimeValidationOptions{}).lockState()
|
||||
if err != nil {
|
||||
log.Warn("配置事务正在运行,证书历史清理将在下次维护时重试")
|
||||
return
|
||||
}
|
||||
defer unlock()
|
||||
}
|
||||
releaseManagedSSLLocked(root, active)
|
||||
if err := pruneManagedSSLLocked(root, append([]SSLConfig{active}, previous...)); err != nil {
|
||||
log.Warn("证书历史自动清理未完成,已保留现场,将在下次维护时重试")
|
||||
}
|
||||
}
|
||||
|
||||
// MaintainManagedSSLHistory 用于启动完成后及定时维护;全新安装无证书时不做删除。
|
||||
func MaintainManagedSSLHistory() {
|
||||
if manager := CurrentManager(); manager != nil {
|
||||
manager.writeMu.Lock()
|
||||
defer manager.writeMu.Unlock()
|
||||
manager.mu.RLock()
|
||||
active := manager.current.SSL.TLS
|
||||
var pending []SSLConfig
|
||||
if manager.pending != nil {
|
||||
pending = append(pending, manager.pending.Candidate.SSL.TLS)
|
||||
}
|
||||
manager.mu.RUnlock()
|
||||
maintainManagedSSL(manager.loader.root, active, pending...)
|
||||
return
|
||||
}
|
||||
sslCommitMu.Lock()
|
||||
defer sslCommitMu.Unlock()
|
||||
if cfg := CurrentConfig(); cfg != nil {
|
||||
maintainManagedSSL(ROOT_PATH, cfg.SSL)
|
||||
}
|
||||
}
|
||||
|
||||
func pruneManagedSSLLocked(root string, protected []SSLConfig) error {
|
||||
if len(protected) == 0 || protected[0].CertificateRef == "" {
|
||||
return nil
|
||||
}
|
||||
// 恢复事务可能仍需要旧材料;恢复未完成时不能清理任何版本。
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
records, err := NewTransactionStore(root, RuntimeValidationOptions{HasSuperAdmin: true}).stateRecords("transaction")
|
||||
if err != nil || len(records) != 0 {
|
||||
return errors.Join(ErrConfigRecoveryRequired, err)
|
||||
}
|
||||
} else if entries, err := os.ReadDir(filepath.Join(root, "data", "transaction")); err != nil && !os.IsNotExist(err) || len(entries) > 0 {
|
||||
return ErrConfigRecoveryRequired
|
||||
}
|
||||
keep := make(map[string]bool)
|
||||
for _, ssl := range protected {
|
||||
if ssl.CertificateRef == "" {
|
||||
continue
|
||||
}
|
||||
reference, err := resolveManagedSSLPathsAtRoot(root, ssl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keep[filepath.Dir(reference.CertificatePath)] = true
|
||||
}
|
||||
// 磁盘引用也必须保留,避免其他管理器实例或已提交未发布的候选被删除。
|
||||
data, err := os.ReadFile(filepath.Join(root, "config", "ssl.json"))
|
||||
if err == nil {
|
||||
var section SSLSectionConfig
|
||||
if err := ParseStrict(data, §ion); err != nil {
|
||||
return err
|
||||
}
|
||||
if section.TLS.CertificateRef != "" {
|
||||
reference, err := resolveManagedSSLPathsAtRoot(root, section.TLS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keep[filepath.Dir(reference.CertificatePath)] = true
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
var versions []retainedSSLVersion
|
||||
// 持有租约直到整轮清理结束,避免检查解锁后与另一个进程的导入操作竞态。
|
||||
var leases []func()
|
||||
defer func() {
|
||||
for _, release := range leases {
|
||||
release()
|
||||
}
|
||||
}()
|
||||
for _, mode := range []string{ManagedSSLModeDefault, ManagedSSLModeUpload} {
|
||||
directory, err := managedSSLRootPathAtRoot(root, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := os.ReadDir(directory)
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(directory)
|
||||
if err != nil || filepath.Clean(resolved) != filepath.Clean(directory) {
|
||||
return ErrUnsafeSSLFile
|
||||
}
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
// 只处理程序生成的完整版本;未知目录、候选和其他用户文件一律不删。
|
||||
known := name == "current" || validSSLVersion(name) || strings.HasPrefix(name, ".previous-") && validSSLVersion("version-"+strings.TrimPrefix(name, ".previous-"))
|
||||
if !known {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(directory, name)
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return ErrUnsafeSSLFile
|
||||
}
|
||||
if managedSSLStorage.staged[path] != nil {
|
||||
keep[path] = true
|
||||
}
|
||||
if keep[path] {
|
||||
versions = append(versions, retainedSSLVersion{directory: path, modified: info.ModTime()})
|
||||
continue
|
||||
}
|
||||
// 其他进程正在导入的版本持有私钥文件的独占租约,不依赖本进程内存判断。
|
||||
lease, err := openSSLLease(filepath.Join(path, "private.key"))
|
||||
if err != nil {
|
||||
keep[path] = true
|
||||
} else {
|
||||
unlock, err := lockStateFile(lease)
|
||||
if err != nil {
|
||||
keep[path] = true
|
||||
lease.Close()
|
||||
} else {
|
||||
leases = append(leases, func() { unlock(); lease.Close() })
|
||||
}
|
||||
}
|
||||
versions = append(versions, retainedSSLVersion{directory: path, modified: info.ModTime()})
|
||||
}
|
||||
}
|
||||
sort.Slice(versions, func(i, j int) bool {
|
||||
if versions[i].modified.Equal(versions[j].modified) {
|
||||
return versions[i].directory > versions[j].directory
|
||||
}
|
||||
return versions[i].modified.After(versions[j].modified)
|
||||
})
|
||||
// 两个模式合计保留两份;正在生效和暂存的版本优先,操作结束后收敛到两份。
|
||||
for _, version := range versions {
|
||||
if len(keep) >= 2 {
|
||||
break
|
||||
}
|
||||
keep[version.directory] = true
|
||||
}
|
||||
var result error
|
||||
for _, version := range versions {
|
||||
if !keep[version.directory] {
|
||||
result = errors.Join(result, removeManagedSSLDirectory(version.directory))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// 回滚前必须检查实际证书,不能提交已经被保留策略淘汰的历史引用。
|
||||
func validateRollbackSSL(root string, candidate RuntimeConfig) error {
|
||||
ssl := candidate.SSL.TLS
|
||||
if ssl.CertificateRef == "" && ssl.PrivateKeyRef == "" {
|
||||
return nil
|
||||
}
|
||||
if _, err := resolveManagedSSLReferencesAtRoot(root, ssl); err != nil {
|
||||
return ErrSSLHistoryUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var ErrSSLHistoryUnavailable = errors.New("历史证书已清理或不可用,无法回滚此配置,请重新导入有效证书")
|
||||
@@ -104,6 +104,15 @@ func ImportManagedSSL(mode string, privateKeyPEM, certificatePEM, issuerPEM []by
|
||||
}
|
||||
|
||||
func importManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) {
|
||||
managedSSLStorage.Lock()
|
||||
defer managedSSLStorage.Unlock()
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
unlock, err := NewTransactionStore(root, RuntimeValidationOptions{}).lockState()
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
defer unlock()
|
||||
}
|
||||
if !validManagedSSLMode(mode) {
|
||||
return ManagedSSLReference{}, ErrInvalidSSLMode
|
||||
}
|
||||
@@ -208,6 +217,18 @@ func ResolveManagedSSLReferences(ssl SSLConfig) (ManagedSSLReference, error) {
|
||||
}
|
||||
|
||||
func resolveManagedSSLReferencesAtRoot(root string, ssl SSLConfig) (ManagedSSLReference, error) {
|
||||
reference, err := resolveManagedSSLPathsAtRoot(root, ssl)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
if err := validateManagedSSLFiles(reference.CertificatePath, reference.PrivateKeyPath); err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
return reference, nil
|
||||
}
|
||||
|
||||
// 路径解析与材料校验分离:历史清理保护过期证书的引用,但运行和回滚仍须完整校验。
|
||||
func resolveManagedSSLPathsAtRoot(root string, ssl SSLConfig) (ManagedSSLReference, error) {
|
||||
ssl = normalizeSSLDataReferences(ssl)
|
||||
if !validManagedSSLMode(ssl.Mode) {
|
||||
return ManagedSSLReference{}, ErrInvalidSSLMode
|
||||
@@ -230,9 +251,6 @@ func resolveManagedSSLReferencesAtRoot(root string, ssl SSLConfig) (ManagedSSLRe
|
||||
if filepath.Dir(certificatePath) != filepath.Dir(privateKeyPath) {
|
||||
return ManagedSSLReference{}, ErrInvalidSSLReference
|
||||
}
|
||||
if err := validateManagedSSLFiles(certificatePath, privateKeyPath); err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
return ManagedSSLReference{
|
||||
Mode: ssl.Mode,
|
||||
CertificateRef: ssl.CertificateRef,
|
||||
@@ -450,6 +468,15 @@ func StageManagedSSL(mode string, privateKeyPEM, certificatePEM, issuerPEM []byt
|
||||
}
|
||||
|
||||
func stageManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) {
|
||||
managedSSLStorage.Lock()
|
||||
defer managedSSLStorage.Unlock()
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
unlock, err := NewTransactionStore(root, RuntimeValidationOptions{}).lockState()
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
defer unlock()
|
||||
}
|
||||
if err := validateSSLMaterial(privateKeyPEM, certificatePEM, issuerPEM, domains); err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
@@ -499,6 +526,16 @@ func stageManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificateP
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
lease, err := openSSLLease(privatePath)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
unlock, err := lockStateFile(lease)
|
||||
if err != nil {
|
||||
lease.Close()
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
managedSSLStorage.staged[directory] = func() { unlock(); lease.Close() }
|
||||
return ManagedSSLReference{Mode: mode, CertificateRef: filepath.ToSlash(publicRef), PrivateKeyRef: filepath.ToSlash(privateRef), CertificatePath: publicPath, PrivateKeyPath: privatePath}, nil
|
||||
}
|
||||
|
||||
@@ -589,6 +626,7 @@ func removeManagedSSLDirectory(directory string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 删除前完整预检,遇到未知文件不能先删掉半套证书。
|
||||
for _, entry := range entries {
|
||||
if entry.Name() != "private.key" && entry.Name() != "public.crt" && entry.Name() != "issuer.crt" {
|
||||
return ErrUnsafeSSLFile
|
||||
@@ -598,10 +636,20 @@ func removeManagedSSLDirectory(directory string) error {
|
||||
if statErr != nil || entryInfo.Mode()&os.ModeSymlink != 0 || !entryInfo.Mode().IsRegular() {
|
||||
return ErrUnsafeSSLFile
|
||||
}
|
||||
if err := os.Remove(entryPath); err != nil {
|
||||
}
|
||||
storage, err := os.OpenRoot(directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if err := storage.Remove(entry.Name()); err != nil {
|
||||
storage.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := storage.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Remove(directory)
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ func Run() error {
|
||||
if err := config.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
config.MaintainManagedSSLHistory()
|
||||
|
||||
build := buildinfo.Current()
|
||||
if build.Version == "dev" {
|
||||
|
||||
@@ -52,6 +52,7 @@ func sslCheck() {
|
||||
|
||||
// 每轮读取最新策略,切换反代模式后不再等待 HTTP 挑战或执行自动续期。
|
||||
func maintainSSL() {
|
||||
config.MaintainManagedSSLHistory()
|
||||
cfg := config.CurrentConfig()
|
||||
if cfg == nil || !cfg.IsSetupReady() {
|
||||
return
|
||||
|
||||
@@ -48,15 +48,19 @@ func NewVault(root string) (*Vault, error) {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
}
|
||||
configDir, err := runtimepath.SecureDirectory(root, filepath.Base(runtimepath.KeyDirectory(root)))
|
||||
encryptionDirectory, err := runtimepath.SecureKeyDirectory(root, "external-email-encryption.key")
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
encryptionKey, err := loadKey(filepath.Join(configDir, "external-email-encryption.key"))
|
||||
fingerprintDirectory, err := runtimepath.SecureKeyDirectory(root, "external-email-fingerprint.key")
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
fingerprintKey, err := loadKey(filepath.Join(configDir, "external-email-fingerprint.key"))
|
||||
encryptionKey, err := loadKey(filepath.Join(encryptionDirectory, "external-email-encryption.key"))
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
fingerprintKey, err := loadKey(filepath.Join(fingerprintDirectory, "external-email-fingerprint.key"))
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
|
||||
@@ -151,6 +151,7 @@ func SetSSL(sslType, priKey, crtKey string) error {
|
||||
return normalizeUserCertificateImportError(err)
|
||||
}
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
defer config.ReleaseStagedSSL(reference)
|
||||
// 导入邮件服务证书不能重新启用反代模式下的内置 HTTPS。
|
||||
if cfg.UsesProxyHTTPS() {
|
||||
cfg.HttpsEnabled = 2
|
||||
@@ -303,6 +304,7 @@ func writeCertificateFiles(cfg *config.Config, privateKey, certificate, issuer [
|
||||
return err
|
||||
}
|
||||
applyManagedSSLReference(&next, reference)
|
||||
defer config.ReleaseStagedSSL(reference)
|
||||
if err := config.WriteSSLConfig(cfg, &next); err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
@@ -86,8 +86,8 @@ func loadOrCreateKey(root string) ([]byte, error) {
|
||||
if !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
directory := runtimepath.KeyDirectory(root)
|
||||
if err := os.MkdirAll(directory, 0700); err != nil {
|
||||
directory, err := runtimepath.SecureKeyDirectory(root, "credential.key")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateKeyDirectory(directory); err != nil {
|
||||
@@ -169,6 +169,11 @@ func readKey(root string) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
directory := runtimepath.KeyDirectory(root)
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
if err := validateKeyDirectory(filepath.Join(root, "ssl")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := validateKeyDirectory(directory); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package runtimepath
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/atomicfile"
|
||||
)
|
||||
|
||||
// BusinessKeyNames 返回固定业务密钥清单,不能由外部输入扩展迁移范围。
|
||||
func BusinessKeyNames() []string {
|
||||
return []string{"credential.key", "external-email-encryption.key", "external-email-fingerprint.key"}
|
||||
}
|
||||
|
||||
func businessKeyFolder(name string) string {
|
||||
switch name {
|
||||
case "credential.key":
|
||||
return "credentials"
|
||||
case "external-email-encryption.key":
|
||||
return "external-email-encryption"
|
||||
case "external-email-fingerprint.key":
|
||||
return "external-email-fingerprint"
|
||||
default:
|
||||
panic("unknown business key")
|
||||
}
|
||||
}
|
||||
|
||||
func groupedKeyPath(root, name string) string {
|
||||
return filepath.Join(root, "ssl", businessKeyFolder(name), name)
|
||||
}
|
||||
|
||||
// KeyPath 兼容尚未升级的部署;正式启动完成归档后只使用业务子目录。
|
||||
func KeyPath(root, name string) string {
|
||||
folder := businessKeyFolder(name)
|
||||
if !DeploymentLayout(root) {
|
||||
return filepath.Join(root, "data", name)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(root, "ssl", name)); err == nil {
|
||||
return filepath.Join(root, "ssl", name)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(root, "ssl", folder)); !os.IsNotExist(err) {
|
||||
return groupedKeyPath(root, name)
|
||||
}
|
||||
return filepath.Join(root, "ssl", name)
|
||||
}
|
||||
|
||||
// SecureKeyDirectory 逐层验证目录,不能通过父目录链接写入外部位置。
|
||||
func SecureKeyDirectory(root, name string) (string, error) {
|
||||
if err := CheckKeyLayout(root); err != nil {
|
||||
return "", err
|
||||
}
|
||||
directory := filepath.Dir(KeyPath(root, name))
|
||||
base := "data"
|
||||
if DeploymentLayout(root) {
|
||||
base = "ssl"
|
||||
}
|
||||
parent, err := SecureDirectory(root, base)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if filepath.Clean(directory) == filepath.Clean(parent) {
|
||||
return parent, nil
|
||||
}
|
||||
return SecureDirectory(parent, businessKeyFolder(name))
|
||||
}
|
||||
|
||||
// PrepareDeploymentKeys 由主程序启动入口在独占状态锁内调用,不依赖安装脚本。
|
||||
// 每次重命名保留原字节;中断后的混合位置可在下次启动继续迁移。
|
||||
func PrepareDeploymentKeys(root string) error {
|
||||
if !DeploymentLayout(root) {
|
||||
return nil
|
||||
}
|
||||
if err := CheckReady(root); err != nil {
|
||||
return err
|
||||
}
|
||||
var moves []Move
|
||||
for _, name := range BusinessKeyNames() {
|
||||
source := KeyPath(root, name)
|
||||
info, err := os.Lstat(source)
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() != 32 {
|
||||
return fmt.Errorf("业务密钥无效,拒绝迁移:%s", name)
|
||||
}
|
||||
if err := safeDirectory(filepath.Join(root, "ssl")); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := safeDirectory(filepath.Dir(source)); err != nil {
|
||||
return err
|
||||
}
|
||||
if runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0 {
|
||||
return errors.New("业务密钥权限过于宽松,拒绝迁移")
|
||||
}
|
||||
if source != groupedKeyPath(root, name) {
|
||||
moves = append(moves, Move{Source: source, Target: groupedKeyPath(root, name)})
|
||||
}
|
||||
}
|
||||
ssl, err := SecureDirectory(root, "ssl")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 先检查所有目标,不能移动第一把密钥后才发现另一业务目录不安全。
|
||||
for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} {
|
||||
if err := safeDirectory(filepath.Join(ssl, folder)); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, folder := range []string{"config", "log"} {
|
||||
if _, err := SecureDirectory(root, folder); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} {
|
||||
if _, err := SecureDirectory(ssl, folder); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, move := range moves {
|
||||
if _, err := os.Lstat(move.Target); !os.IsNotExist(err) {
|
||||
return errors.New("密钥迁移目标已存在,拒绝覆盖")
|
||||
}
|
||||
if err := os.Rename(move.Source, move.Target); err != nil {
|
||||
return fmt.Errorf("业务密钥归档未完成,下次启动将继续:%w", err)
|
||||
}
|
||||
if err := atomicfile.SyncDirectory(filepath.Dir(move.Target)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := atomicfile.SyncDirectory(ssl); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return CheckKeyLayout(root)
|
||||
}
|
||||
@@ -4,17 +4,26 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CheckKeyLayout 拒绝同时存在新旧密钥,避免误用另一套加密材料。
|
||||
func CheckKeyLayout(root string) error {
|
||||
legacy, modern := false, false
|
||||
for _, name := range []string{"credential.key", "external-email-encryption.key", "external-email-fingerprint.key"} {
|
||||
for _, name := range BusinessKeyNames() {
|
||||
if _, err := os.Lstat(filepath.Join(root, "data", name)); err == nil {
|
||||
legacy = true
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
if _, err := os.Lstat(groupedKeyPath(root, name)); err == nil {
|
||||
modern = true
|
||||
if _, err := os.Lstat(filepath.Join(root, "ssl", name)); !os.IsNotExist(err) {
|
||||
return errors.New("密钥同时存在于归档目录和旧目录,拒绝自动选择或覆盖")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(root, "ssl", name)); err == nil {
|
||||
modern = true
|
||||
} else if !os.IsNotExist(err) {
|
||||
@@ -32,7 +41,7 @@ func DeploymentLayout(root string) bool {
|
||||
if _, err := os.Lstat(filepath.Join(root, "data", "credential.key")); err == nil {
|
||||
return false
|
||||
}
|
||||
for _, name := range []string{"data/smail-state.db", "ssl/credential.key"} {
|
||||
for _, name := range []string{"data/smail-state.db", "ssl/credential.key", "ssl/credentials/credential.key"} {
|
||||
info, err := os.Lstat(filepath.Join(root, filepath.FromSlash(name)))
|
||||
if err == nil && info.Mode().IsRegular() {
|
||||
return true
|
||||
@@ -42,6 +51,12 @@ func DeploymentLayout(root string) bool {
|
||||
}
|
||||
|
||||
func SecureDirectory(root, name string) (string, error) {
|
||||
if !filepath.IsLocal(name) || strings.ContainsAny(name, `/\`) || name == "." {
|
||||
return "", errors.New("受保护目录名称无效")
|
||||
}
|
||||
if err := safeDirectory(root); err != nil {
|
||||
return "", err
|
||||
}
|
||||
directory := filepath.Join(root, name)
|
||||
if err := os.Mkdir(directory, 0700); err != nil && !os.IsExist(err) {
|
||||
return "", err
|
||||
@@ -53,10 +68,7 @@ func SecureDirectory(root, name string) (string, error) {
|
||||
}
|
||||
|
||||
func KeyDirectory(root string) string {
|
||||
if DeploymentLayout(root) {
|
||||
return filepath.Join(root, "ssl")
|
||||
}
|
||||
return filepath.Join(root, "data")
|
||||
return filepath.Dir(KeyPath(root, "credential.key"))
|
||||
}
|
||||
|
||||
func SSLReference(root, value string) string {
|
||||
|
||||
@@ -184,7 +184,7 @@ func CheckReady(root string) error {
|
||||
if config.SetupState != "ready" {
|
||||
return nil
|
||||
}
|
||||
required := []string{"credential.key", "external-email-encryption.key", "external-email-fingerprint.key"}
|
||||
required := BusinessKeyNames()
|
||||
if config.Database.Type == "sqlite" {
|
||||
if !filepath.IsLocal(config.Database.LocalRef) {
|
||||
return errors.New("SQLite 本地引用无效")
|
||||
@@ -194,7 +194,12 @@ func CheckReady(root string) error {
|
||||
for _, name := range required {
|
||||
base := filepath.Join(root, "data")
|
||||
if strings.HasSuffix(name, ".key") {
|
||||
base = KeyDirectory(root)
|
||||
base = filepath.Dir(KeyPath(root, name))
|
||||
if DeploymentLayout(root) {
|
||||
if err := safeDirectory(filepath.Join(root, "ssl")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := safeDirectory(base); err != nil {
|
||||
return err
|
||||
|
||||
Reference in new issue
Block a user