This commit is contained in:
1 parent
dd9d659cb7
commit
9dc861d560
41 files changed
+1408
-198
No files matched your search
@@ -8,5 +8,7 @@ func normalizeSSLDataReferences(ssl SSLConfig) SSLConfig {
|
||||
ssl.CustomDirectory = runtimepath.LegacyReference(ssl.CustomDirectory)
|
||||
ssl.CertificateRef = runtimepath.LegacyReference(ssl.CertificateRef)
|
||||
ssl.PrivateKeyRef = runtimepath.LegacyReference(ssl.PrivateKeyRef)
|
||||
ssl.PreviousCertificateRef = runtimepath.LegacyReference(ssl.PreviousCertificateRef)
|
||||
ssl.PreviousPrivateKeyRef = runtimepath.LegacyReference(ssl.PreviousPrivateKeyRef)
|
||||
return ssl
|
||||
}
|
||||
@@ -281,6 +281,7 @@ func (m *ConfigManager) Validate(ctx context.Context, req ValidateRequest) (*Val
|
||||
}
|
||||
return &ValidationResult{Valid: false, Generation: current.Generation, Issues: []PublicIssue{issue}}, nil
|
||||
}
|
||||
retainPreviousSSL(m.loader.root, &candidate.SSL.TLS, current.SSL.TLS)
|
||||
}
|
||||
setCandidateGeneration(&candidate, current.Generation+1)
|
||||
if err := ValidateRuntimeConfig(candidate, m.options); err != nil {
|
||||
@@ -321,6 +322,7 @@ func (m *ConfigManager) Update(ctx context.Context, req UpdateRequest) (*UpdateR
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
retainPreviousSSL(m.loader.root, &candidate.SSL.TLS, current.SSL.TLS)
|
||||
}
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -348,7 +350,7 @@ func (m *ConfigManager) Update(ctx context.Context, req UpdateRequest) (*UpdateR
|
||||
setCandidateGeneration(&candidate, current.Generation+1)
|
||||
m.mu.Lock()
|
||||
m.pending = &pendingConfig{ID: id, Candidate: candidate, Section: req.Section, Actor: req.Actor, Confirmation: req.Confirmation, PreviousRestart: append([]ServiceName(nil), m.status.PendingRestart...)}
|
||||
m.status.PendingRestart = mergeServices(m.status.PendingRestart, servicesForSection(req.Section))
|
||||
m.status.PendingRestart = mergeServices(m.status.PendingRestart, servicesForChange(req.Section, current, candidate))
|
||||
m.mu.Unlock()
|
||||
return &UpdateResult{CandidateID: id, Generation: candidate.Generation, Candidate: cloneRuntimeConfig(candidate), Pending: true}, nil
|
||||
}
|
||||
@@ -677,6 +679,7 @@ func (m *ConfigManager) rollbackWithState(ctx context.Context, generation uint64
|
||||
if err := validateRollbackSSL(m.loader.root, candidate); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
retainPreviousSSL(m.loader.root, &candidate.SSL.TLS, current.SSL.TLS)
|
||||
setCandidateGeneration(&candidate, current.Generation+1)
|
||||
candidate.Root.UpdatedAt = time.Now().UTC()
|
||||
if err := ValidateRuntimeConfig(candidate, m.options); err != nil {
|
||||
|
||||
@@ -104,13 +104,15 @@ type EmailConfig struct {
|
||||
}
|
||||
|
||||
type SSLConfig struct {
|
||||
Management string `json:"management,omitempty"`
|
||||
Mode string `json:"mode"`
|
||||
DefaultDirectory string `json:"defaultDirectory"`
|
||||
CustomDirectory string `json:"customDirectory,omitempty"`
|
||||
Challenge string `json:"challenge,omitempty"`
|
||||
CertificateRef string `json:"certificateRef,omitempty"`
|
||||
PrivateKeyRef string `json:"privateKeyRef,omitempty"`
|
||||
Management string `json:"management,omitempty"`
|
||||
Mode string `json:"mode"`
|
||||
DefaultDirectory string `json:"defaultDirectory"`
|
||||
CustomDirectory string `json:"customDirectory,omitempty"`
|
||||
Challenge string `json:"challenge,omitempty"`
|
||||
CertificateRef string `json:"certificateRef,omitempty"`
|
||||
PrivateKeyRef string `json:"privateKeyRef,omitempty"`
|
||||
PreviousCertificateRef string `json:"previousCertificateRef,omitempty"`
|
||||
PreviousPrivateKeyRef string `json:"previousPrivateKeyRef,omitempty"`
|
||||
}
|
||||
|
||||
type PluginConfig struct {
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
"git.pcux.cn/xuans/Smail/utils/runtimepath"
|
||||
@@ -87,7 +86,7 @@ func runtimeCompatibility(runtime RuntimeConfig) (*Config, error) {
|
||||
}
|
||||
}
|
||||
// 迁移器保留的旧证书引用仍走严格的只读文件校验;新托管引用沿用托管解析器。
|
||||
if strings.HasPrefix(tls.CertificateRef, managedSSLRelativeRoot+"/") || strings.HasPrefix(tls.CertificateRef, "ssl/managed/") {
|
||||
if validManagedSSLMode(tls.Mode) {
|
||||
cfg.SSL = tls
|
||||
} else {
|
||||
cfg.SSLPublicKeyPath = resolvePath(tls.CertificateRef)
|
||||
|
||||
@@ -76,7 +76,7 @@ func TestPartitionedCompatibilityStartupAndWriteProtection(t *testing.T) {
|
||||
if !cfg.IsSetupReady() || cfg.DbType != DBTypeSQLite || cfg.DbDSN != filepath.Join(root, "data", "existing.db") {
|
||||
t.Fatal("partitioned startup lost initialization or database identity")
|
||||
}
|
||||
if cfg.WebDomain != "mail.example.com" || cfg.SSLPublicKeyPath != filepath.Join(root, "data", "ssl", "site.crt") {
|
||||
if cfg.WebDomain != "mail.example.com" || cfg.SSL.CertificateRef != "data/ssl/site.crt" {
|
||||
t.Fatal("partitioned startup lost domain or certificate path")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ func WriteSSLConfig(expected, next *Config) error {
|
||||
}
|
||||
sslCommitMu.Lock()
|
||||
defer sslCommitMu.Unlock()
|
||||
retainPreviousSSL(ROOT_PATH, &next.SSL, expected.SSL)
|
||||
legacyConfigMu.Lock()
|
||||
defer legacyConfigMu.Unlock()
|
||||
data, err := readConfigFile("config.json")
|
||||
@@ -87,6 +88,9 @@ func WriteSSLConfig(expected, next *Config) error {
|
||||
candidate := cloneRuntimeConfig(current)
|
||||
candidate.SSL.TLS = next.SSL
|
||||
candidate.Root.HTTP.HTTPSEnabled = next.HttpsEnabled == 1
|
||||
if err := validateCustomSSLReferences(ROOT_PATH, candidate); err != nil {
|
||||
return err
|
||||
}
|
||||
setCandidateGeneration(&candidate, current.Generation+1)
|
||||
if err := ValidateRuntimeConfig(candidate, manager.options); err != nil {
|
||||
return err
|
||||
@@ -118,7 +122,7 @@ func WriteSSLConfig(expected, next *Config) error {
|
||||
Actor: AuditActor{UserID: "system", Role: "system"},
|
||||
PreviousRestart: append([]ServiceName(nil), manager.status.PendingRestart...),
|
||||
}
|
||||
manager.status.PendingRestart = mergeServices(manager.status.PendingRestart, servicesForSection(SectionSSL))
|
||||
manager.status.PendingRestart = mergeServices(manager.status.PendingRestart, servicesForChange(SectionSSL, current, candidate))
|
||||
manager.mu.Unlock()
|
||||
if err := manager.publishSnapshot(candidate); err != nil {
|
||||
return err
|
||||
@@ -139,7 +143,7 @@ func WriteSSLConfig(expected, next *Config) error {
|
||||
return manager.writeAudit(context.Background(), ConfigAuditEvent{
|
||||
Operation: ConfigOperationUpdate, Section: SectionSSL, ActorID: "system", ActorRole: "system",
|
||||
FromGeneration: current.Generation, ToGeneration: candidate.Generation,
|
||||
Changes: AuditChanges(current, candidate),
|
||||
Changes: AuditChanges(current, candidate),
|
||||
ChangedFields: []string{"tls"}, Result: "success", CreatedAt: now,
|
||||
})
|
||||
}
|
||||
@@ -152,6 +156,17 @@ func sameSSLPolicy(left, right *Config) bool {
|
||||
left.TLSMode == right.TLSMode
|
||||
}
|
||||
|
||||
// 材料和续期策略均可热更新;只有实际监听配置发生变化才提示重启。
|
||||
func servicesForChange(section Section, previous, next RuntimeConfig) []ServiceName {
|
||||
if section == SectionSSL {
|
||||
if !reflect.DeepEqual(previous.Root.HTTP, next.Root.HTTP) {
|
||||
return []ServiceName{ServiceHTTP}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return servicesForSection(section)
|
||||
}
|
||||
|
||||
func mergeServices(previous, next []ServiceName) []ServiceName {
|
||||
result := append([]ServiceName(nil), previous...)
|
||||
for _, service := range next {
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
var ErrSSLFileUnavailable = errors.New("SSL certificate file is missing or unreadable")
|
||||
|
||||
// customSSLMaterial 在只读准备阶段保留已校验的材料,确认后再暂存,避免重新读取外部文件。
|
||||
// customSSLMaterial 保留只读准备结果;自定义文件只验证和引用,不复制。
|
||||
type customSSLMaterial struct {
|
||||
privateKey []byte
|
||||
certificate []byte
|
||||
@@ -22,7 +22,7 @@ type customSSLMaterial struct {
|
||||
func prepareCustomSSLPaths(root string, candidate *RuntimeConfig) (*customSSLMaterial, error) {
|
||||
candidate.SSL.TLS = normalizeSSLDataReferences(candidate.SSL.TLS)
|
||||
ssl := &candidate.SSL.TLS
|
||||
if EffectiveSSLManagement(*ssl) != SSLManagementCustom {
|
||||
if EffectiveSSLManagement(*ssl) == SSLManagementProject {
|
||||
return nil, nil
|
||||
}
|
||||
certificatePath := strings.TrimSpace(ssl.CertificateRef)
|
||||
@@ -62,9 +62,8 @@ func prepareCustomSSLPaths(root string, candidate *RuntimeConfig) (*customSSLMat
|
||||
ssl.Mode = ManagedSSLModeUpload
|
||||
ssl.DefaultDirectory = runtimepath.SSLReference(root, "data/ssl")
|
||||
ssl.CustomDirectory = runtimepath.SSLReference(root, "data/ssl")
|
||||
// 仅在内存中使用合法占位引用完成跨分区校验,最终候选必须换成独立版本。
|
||||
ssl.CertificateRef = managedSSLReferenceAtRoot(root, ManagedSSLModeUpload, "public.crt")
|
||||
ssl.PrivateKeyRef = managedSSLReferenceAtRoot(root, ManagedSSLModeUpload, "private.key")
|
||||
ssl.CertificateRef = directSSLReference(root, certificatePath)
|
||||
ssl.PrivateKeyRef = directSSLReference(root, privateKeyPath)
|
||||
return material, nil
|
||||
}
|
||||
|
||||
@@ -72,16 +71,48 @@ func (material *customSSLMaterial) stage(root string, candidate *RuntimeConfig)
|
||||
if material == nil {
|
||||
return nil
|
||||
}
|
||||
reference, err := stageManagedSSLAtRoot(root, ManagedSSLModeUpload, material.privateKey, material.certificate, nil, material.domains)
|
||||
if err != nil {
|
||||
return err
|
||||
return validateCustomSSLReferences(root, *candidate)
|
||||
}
|
||||
|
||||
// 部署目录内使用清晰的相对路径,目录外保留完整绝对路径。
|
||||
func directSSLReference(root, path string) string {
|
||||
absoluteRoot, err := filepath.Abs(root)
|
||||
if err == nil && pathWithin(absoluteRoot, path) {
|
||||
if relative, err := filepath.Rel(absoluteRoot, path); err == nil {
|
||||
return filepath.ToSlash(relative)
|
||||
}
|
||||
}
|
||||
candidate.SSL.TLS.CertificateRef = reference.CertificateRef
|
||||
candidate.SSL.TLS.PrivateKeyRef = reference.PrivateKeyRef
|
||||
return nil
|
||||
return filepath.ToSlash(path)
|
||||
}
|
||||
|
||||
// ValidateDirectSSLPaths 供初始化使用,与配置管理共用相同的文件安全校验。
|
||||
func ValidateDirectSSLPaths(certificatePath, privateKeyPath string, domains []string) (ManagedSSLReference, error) {
|
||||
publicPath, err := resolveCustomSSLInput(ROOT_PATH, certificatePath)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
privatePath, err := resolveCustomSSLInput(ROOT_PATH, privateKeyPath)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
publicKey, err := readExternalSSLFile(publicPath, false)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
privateKey, err := readExternalSSLFile(privatePath, true)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
if err := validateSSLMaterial(privateKey, publicKey, nil, domains); err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
return ManagedSSLReference{Mode: ManagedSSLModeUpload, CertificateRef: directSSLReference(ROOT_PATH, publicPath), PrivateKeyRef: directSSLReference(ROOT_PATH, privatePath), CertificatePath: publicPath, PrivateKeyPath: privatePath}, nil
|
||||
}
|
||||
|
||||
func resolveCustomSSLInput(root, value string) (string, error) {
|
||||
if strings.TrimSpace(value) == "" || strings.ContainsRune(value, 0) {
|
||||
return "", ErrInvalidSSLReference
|
||||
}
|
||||
for _, part := range strings.FieldsFunc(value, func(r rune) bool { return r == '/' || r == '\\' }) {
|
||||
if part == ".." {
|
||||
return "", ErrInvalidSSLReference
|
||||
@@ -137,7 +168,7 @@ func readExternalSSLFile(path string, privateKey bool) ([]byte, error) {
|
||||
|
||||
func validateCustomSSLReferences(root string, candidate RuntimeConfig) error {
|
||||
ssl := candidate.SSL.TLS
|
||||
if EffectiveSSLManagement(ssl) != SSLManagementCustom || ssl.CertificateRef == "" && ssl.PrivateKeyRef == "" {
|
||||
if ssl.CertificateRef == "" && ssl.PrivateKeyRef == "" {
|
||||
return nil
|
||||
}
|
||||
reference, err := resolveManagedSSLReferencesAtRoot(root, ssl)
|
||||
@@ -152,7 +183,21 @@ func validateCustomSSLReferences(root string, candidate RuntimeConfig) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return validateSSLMaterial(privateKey, certificate, nil, runtimeCertificateDomains(&candidate))
|
||||
return validateSSLMaterial(privateKey, certificate, nil, validationCertificateDomains(&candidate))
|
||||
}
|
||||
|
||||
func validationCertificateDomains(candidate *RuntimeConfig) []string {
|
||||
if EffectiveSSLManagement(candidate.SSL.TLS) == SSLManagementProject && candidate.SSL.TLS.Challenge == SSLChallengeDNS {
|
||||
domains := []string{"*." + strings.TrimPrefix(candidate.Root.Domains.Primary, "*.")}
|
||||
if candidate.Root.Domains.Web != "" {
|
||||
domains = append(domains, candidate.Root.Domains.Web)
|
||||
}
|
||||
for _, domain := range candidate.Root.Domains.Accepted {
|
||||
domains = append(domains, "smtp."+domain, "imap."+domain, "pop."+domain)
|
||||
}
|
||||
return domains
|
||||
}
|
||||
return runtimeCertificateDomains(candidate)
|
||||
}
|
||||
|
||||
func runtimeCertificateDomains(candidate *RuntimeConfig) []string {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// 调用方持有配置写锁;先事务清除过期引用,再由文件维护回收材料。
|
||||
func (m *ConfigManager) clearExpiredPreviousSSL() error {
|
||||
m.mu.RLock()
|
||||
current := cloneRuntimeConfig(m.current)
|
||||
pending := m.pending
|
||||
m.mu.RUnlock()
|
||||
if pending != nil {
|
||||
if pending.Committed && pending.Actor.UserID == "ssl-maintenance" {
|
||||
return m.publishExpiredSSL(pending.Candidate)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
ssl := current.SSL.TLS
|
||||
if ssl.PreviousCertificateRef == "" {
|
||||
return nil
|
||||
}
|
||||
path, err := resolveCustomSSLInput(m.loader.root, ssl.PreviousCertificateRef)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := resolveManagedSSLReferencesAtRoot(m.loader.root, ssl); err != nil {
|
||||
return err
|
||||
}
|
||||
_, statErr := os.Lstat(path)
|
||||
if !os.IsNotExist(statErr) {
|
||||
data, err := readExternalSSLFile(path, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
certificates, err := parseCertificatePEM(data)
|
||||
if err != nil || len(certificates) == 0 {
|
||||
return ErrInvalidSSLMaterial
|
||||
}
|
||||
if time.Now().Before(certificates[0].NotAfter) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
candidate := cloneRuntimeConfig(current)
|
||||
candidate.SSL.TLS.PreviousCertificateRef = ""
|
||||
candidate.SSL.TLS.PreviousPrivateKeyRef = ""
|
||||
setCandidateGeneration(&candidate, current.Generation+1)
|
||||
if err := m.snapshots.Validate(candidate); err != nil {
|
||||
return err
|
||||
}
|
||||
id, err := newRollbackTicketID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.transactions.Commit(current, candidate); err != nil {
|
||||
return err
|
||||
}
|
||||
// 事务已经落盘时保留恢复入口;下轮维护重试发布,不再次提交同一代次。
|
||||
m.mu.Lock()
|
||||
m.pending = &pendingConfig{ID: id, Candidate: candidate, Section: SectionSSL, Committed: true,
|
||||
Actor: AuditActor{UserID: "ssl-maintenance", Role: "system"}}
|
||||
m.mu.Unlock()
|
||||
return m.publishExpiredSSL(candidate)
|
||||
}
|
||||
|
||||
func (m *ConfigManager) publishExpiredSSL(candidate RuntimeConfig) error {
|
||||
if err := m.publishSnapshot(candidate); err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
m.mu.Lock()
|
||||
m.current = candidate
|
||||
m.pending = nil
|
||||
m.status.SetupState = candidate.SetupState
|
||||
m.status.DegradedReasons = nil
|
||||
m.status.ActiveGeneration = candidate.Generation
|
||||
m.status.LastValidAt = &now
|
||||
m.mu.Unlock()
|
||||
log.WithFields(log.Fields{"action": "清理过期证书引用", "result": "success"}).Info("上一套证书已到期,已解除保留")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/atomicfile"
|
||||
"git.pcux.cn/xuans/Smail/utils/runtimepath"
|
||||
)
|
||||
|
||||
const flatSSLPrefix = "smail-tls-"
|
||||
|
||||
func legacyManagedSSLReference(value string) bool {
|
||||
value = runtimepath.LegacyReference(value)
|
||||
return strings.HasPrefix(value, "data/ssl/managed/") || strings.HasPrefix(value, "ssl/managed/")
|
||||
}
|
||||
|
||||
func flatSSLPair(root, certificatePath, privateKeyPath string) bool {
|
||||
directory, err := filepath.Abs(filepath.Join(root, "ssl"))
|
||||
if err != nil || filepath.Dir(certificatePath) != directory || filepath.Dir(privateKeyPath) != directory {
|
||||
return false
|
||||
}
|
||||
name := strings.TrimSuffix(filepath.Base(certificatePath), ".crt")
|
||||
return strings.HasSuffix(certificatePath, ".crt") && strings.HasPrefix(name, flatSSLPrefix) &&
|
||||
validSSLVersion("version-"+strings.TrimPrefix(name, flatSSLPrefix)) && filepath.Base(privateKeyPath) == name+".key"
|
||||
}
|
||||
|
||||
// 新材料使用不可变的成对文件;配置事务是唯一的生效指针,不覆盖当前文件。
|
||||
func stageFlatSSLAtRoot(root, mode string, privateKey, certificate, issuer []byte, domains []string) (ManagedSSLReference, error) {
|
||||
managedSSLStorage.Lock()
|
||||
defer managedSSLStorage.Unlock()
|
||||
if !validManagedSSLMode(mode) {
|
||||
return ManagedSSLReference{}, ErrInvalidSSLMode
|
||||
}
|
||||
if err := validateSSLMaterial(privateKey, certificate, issuer, domains); err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
unlock, err := NewTransactionStore(root, RuntimeValidationOptions{}).lockState()
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
defer unlock()
|
||||
}
|
||||
directory, err := filepath.Abs(filepath.Join(root, "ssl"))
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
if err := ensureManagedDirectoryAtRoot(root, directory); err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
token, err := randomStorageToken()
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
base := flatSSLPrefix + token
|
||||
storage, err := os.OpenRoot(directory)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
defer storage.Close()
|
||||
// 证书链合并到一个证书文件,不额外生成 issuer 文件。
|
||||
certificates, _ := parseCertificatePEM(certificate)
|
||||
issuers, _ := parseCertificatePEM(issuer)
|
||||
certificate = encodeSSLCertificates(appendUniqueCertificates(certificates, issuers...))
|
||||
if len(certificate) > maxManagedSSLFileSize {
|
||||
return ManagedSSLReference{}, ErrInvalidSSLMaterial
|
||||
}
|
||||
var written []string
|
||||
complete := false
|
||||
defer func() {
|
||||
if !complete {
|
||||
for _, name := range written {
|
||||
_ = storage.Remove(name)
|
||||
}
|
||||
}
|
||||
}()
|
||||
for _, file := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
}{{base + ".key", privateKey}, {base + ".crt", certificate}} {
|
||||
if _, err := storage.Lstat(file.name); !os.IsNotExist(err) {
|
||||
return ManagedSSLReference{}, ErrUnsafeSSLFile
|
||||
}
|
||||
written = append(written, file.name)
|
||||
if err := atomicfile.WriteRoot(storage, file.name, file.data, 0600); err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
}
|
||||
publicPath, privatePath := filepath.Join(directory, base+".crt"), filepath.Join(directory, base+".key")
|
||||
if err := validateManagedSSLFiles(publicPath, privatePath); 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[publicPath] = func() { unlock(); lease.Close() }
|
||||
complete = true
|
||||
return ManagedSSLReference{Mode: mode, CertificateRef: "ssl/" + base + ".crt", PrivateKeyRef: "ssl/" + base + ".key", CertificatePath: publicPath, PrivateKeyPath: privatePath}, nil
|
||||
}
|
||||
|
||||
// 只有上一套由本程序生成的证书才纳入到期自动删除;手动文件不会被接管。
|
||||
func retainPreviousSSL(root string, next *SSLConfig, previous SSLConfig) {
|
||||
next.PreviousCertificateRef = previous.PreviousCertificateRef
|
||||
next.PreviousPrivateKeyRef = previous.PreviousPrivateKeyRef
|
||||
if next.CertificateRef == previous.CertificateRef && next.PrivateKeyRef == previous.PrivateKeyRef {
|
||||
return
|
||||
}
|
||||
ref, err := resolveManagedSSLPathsAtRoot(root, previous)
|
||||
if err == nil && flatSSLPair(root, ref.CertificatePath, ref.PrivateKeyPath) {
|
||||
if validateManagedSSLFiles(ref.CertificatePath, ref.PrivateKeyPath) == nil {
|
||||
next.PreviousCertificateRef = previous.CertificateRef
|
||||
next.PreviousPrivateKeyRef = previous.PrivateKeyRef
|
||||
}
|
||||
}
|
||||
if next.PreviousCertificateRef == next.CertificateRef {
|
||||
next.PreviousCertificateRef, next.PreviousPrivateKeyRef = "", ""
|
||||
}
|
||||
}
|
||||
|
||||
func pruneFlatSSLLocked(root string, protected []SSLConfig) error {
|
||||
// 当前材料不可用时暂停回收,避免丢失仍可恢复的历史证书。
|
||||
if len(protected) == 0 {
|
||||
return nil
|
||||
}
|
||||
if _, err := resolveManagedSSLReferencesAtRoot(root, protected[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
directory, err := filepath.Abs(filepath.Join(root, "ssl"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := os.ReadDir(directory)
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(directory)
|
||||
if err != nil || filepath.Clean(resolved) != directory {
|
||||
return ErrUnsafeSSLFile
|
||||
}
|
||||
keep := make(map[string]bool)
|
||||
for _, ssl := range protected {
|
||||
if path, err := resolveCustomSSLInput(root, ssl.CertificateRef); ssl.CertificateRef != "" && err == nil {
|
||||
keep[path] = true
|
||||
}
|
||||
// 已经降为上一套的配置不能继续保护更早一代,避免保留链无限延长。
|
||||
if ssl.CertificateRef == protected[0].PreviousCertificateRef {
|
||||
continue
|
||||
}
|
||||
publicPath, err := resolveCustomSSLInput(root, ssl.PreviousCertificateRef)
|
||||
privatePath, keyErr := resolveCustomSSLInput(root, ssl.PreviousPrivateKeyRef)
|
||||
if err == nil && keyErr == nil && flatSSLPair(root, publicPath, privatePath) {
|
||||
// 即使已经到期,也必须等配置事务解除引用后才能删除。
|
||||
keep[publicPath] = true
|
||||
}
|
||||
}
|
||||
storage, err := os.OpenRoot(directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer storage.Close()
|
||||
for _, entry := range entries {
|
||||
publicPath := filepath.Join(directory, entry.Name())
|
||||
privatePath := strings.TrimSuffix(publicPath, ".crt") + ".key"
|
||||
if !flatSSLPair(root, publicPath, privatePath) || keep[publicPath] || managedSSLStorage.staged[publicPath] != nil {
|
||||
continue
|
||||
}
|
||||
// 租约覆盖整个删除过程;未知、链接、不完整材料保留给管理员处理。
|
||||
certificate, err := readExternalSSLFile(publicPath, false)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
certificates, err := parseCertificatePEM(certificate)
|
||||
if err != nil || len(certificates) == 0 {
|
||||
continue
|
||||
}
|
||||
privateKey, err := readExternalSSLFile(privatePath, true)
|
||||
if err != nil {
|
||||
// 先删私钥、后删证书;中断留下的孤立证书可在下轮安全重试。
|
||||
if _, statErr := os.Lstat(privatePath); os.IsNotExist(statErr) {
|
||||
if err := storage.Remove(filepath.Base(publicPath)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := tls.X509KeyPair(certificate, privateKey); err != nil {
|
||||
continue
|
||||
}
|
||||
lease, err := openSSLLease(privatePath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
unlock, err := lockStateFile(lease)
|
||||
if err != nil {
|
||||
lease.Close()
|
||||
continue
|
||||
}
|
||||
err = storage.Remove(filepath.Base(privatePath))
|
||||
if err == nil {
|
||||
err = storage.Remove(filepath.Base(publicPath))
|
||||
}
|
||||
unlock()
|
||||
lease.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func encodeSSLCertificates(certificates []*x509.Certificate) []byte {
|
||||
var result []byte
|
||||
for _, certificate := range certificates {
|
||||
result = append(result, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate.Raw})...)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// 所有协议共享已完整校验的内存证书;只影响新握手,不关闭既有连接。
|
||||
var liveTLS = struct {
|
||||
sync.Mutex
|
||||
root string
|
||||
certificate *tls.Certificate
|
||||
checked time.Time
|
||||
warned time.Time
|
||||
}{}
|
||||
|
||||
func CurrentCertificateConfig() *Config {
|
||||
cfg := CurrentConfig()
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
if manager := CurrentManager(); manager != nil {
|
||||
runtime := manager.Snapshot()
|
||||
cfg.SSL = runtime.SSL.TLS
|
||||
cfg.Domain, cfg.WebDomain = runtime.Root.Domains.Primary, runtime.Root.Domains.Web
|
||||
cfg.Domains = runtime.Root.Domains.Accepted
|
||||
cfg.TLSMode = runtime.Root.HTTP.TLSMode
|
||||
cfg.HttpsEnabled = 2
|
||||
if runtime.Root.HTTP.HTTPSEnabled {
|
||||
cfg.HttpsEnabled = 1
|
||||
}
|
||||
cfg.SSLType = SSLTypeUser
|
||||
if EffectiveSSLManagement(cfg.SSL) == SSLManagementProject {
|
||||
cfg.SSLType = SSLTypeAutoHTTP
|
||||
if cfg.SSL.Challenge == SSLChallengeDNS {
|
||||
cfg.SSLType = SSLTypeAutoDNS
|
||||
}
|
||||
}
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func runtimeTLSCertificate(force bool) (*tls.Certificate, error) {
|
||||
liveTLS.Lock()
|
||||
defer liveTLS.Unlock()
|
||||
now := time.Now()
|
||||
if liveTLS.root != ROOT_PATH {
|
||||
liveTLS.certificate, liveTLS.checked, liveTLS.warned = nil, time.Time{}, time.Time{}
|
||||
liveTLS.root = ROOT_PATH
|
||||
}
|
||||
if !force && liveTLS.certificate != nil && now.Sub(liveTLS.checked) < time.Second && now.Before(liveTLS.certificate.Leaf.NotAfter) {
|
||||
return liveTLS.certificate, nil
|
||||
}
|
||||
liveTLS.checked = now
|
||||
cfg := CurrentCertificateConfig()
|
||||
certificate, err := loadValidatedRuntimeCertificate(cfg)
|
||||
if err == nil {
|
||||
liveTLS.certificate = &certificate
|
||||
return liveTLS.certificate, nil
|
||||
}
|
||||
if (liveTLS.certificate == nil || !now.Before(liveTLS.certificate.Leaf.NotAfter)) && cfg != nil && cfg.SSL.PreviousCertificateRef != "" {
|
||||
previous := *cfg
|
||||
previous.SSL.CertificateRef = cfg.SSL.PreviousCertificateRef
|
||||
previous.SSL.PrivateKeyRef = cfg.SSL.PreviousPrivateKeyRef
|
||||
if fallback, fallbackErr := loadValidatedRuntimeCertificate(&previous); fallbackErr == nil {
|
||||
liveTLS.certificate = &fallback
|
||||
}
|
||||
}
|
||||
if liveTLS.certificate != nil && now.Before(liveTLS.certificate.Leaf.NotAfter) {
|
||||
if now.Sub(liveTLS.warned) >= time.Minute {
|
||||
log.WithFields(log.Fields{"action": "热加载 TLS 证书", "result": "failure"}).Warn("新证书不可用,继续使用尚未过期的已校验证书")
|
||||
liveTLS.warned = now
|
||||
}
|
||||
return liveTLS.certificate, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func loadValidatedRuntimeCertificate(cfg *Config) (tls.Certificate, error) {
|
||||
certificate, err := LoadRuntimeTLSCertificate(cfg)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
certificate.Leaf, err = x509.ParseCertificate(certificate.Certificate[0])
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
runtime := RuntimeConfig{Root: RootConfig{Domains: DomainConfig{Primary: cfg.Domain, Web: cfg.WebDomain, Accepted: cfg.Domains}}}
|
||||
runtime.SSL.TLS = cfg.SSL
|
||||
if cfg.SSLType == SSLTypeAutoDNS {
|
||||
runtime.SSL.TLS.Management = SSLManagementProject
|
||||
runtime.SSL.TLS.Challenge = SSLChallengeDNS
|
||||
}
|
||||
for _, domain := range validationCertificateDomains(&runtime) {
|
||||
if err := certificate.Leaf.VerifyHostname(domain); err != nil {
|
||||
return tls.Certificate{}, ErrSSLCertificateDomain
|
||||
}
|
||||
}
|
||||
return certificate, nil
|
||||
}
|
||||
|
||||
// NewRuntimeTLSConfig 在启动时验证证书,后续握手自动使用最新有效证书。
|
||||
func NewRuntimeTLSConfig() (*tls.Config, error) {
|
||||
if certificate, err := runtimeTLSCertificate(true); certificate == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tls.Config{MinVersion: tls.VersionTLS12, GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
certificate, err := runtimeTLSCertificate(false)
|
||||
if certificate != nil {
|
||||
return certificate, nil
|
||||
}
|
||||
return nil, err
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func ReloadRuntimeTLSCertificate() error {
|
||||
_, err := runtimeTLSCertificate(true)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/runtimepath"
|
||||
)
|
||||
|
||||
// MigrateLegacySSLStorage 在监听器启动前迁移旧引用;提交失败时不删除旧材料。
|
||||
// 自定义模式优先复用 ssl 根目录中完全相同的原件,无法匹配时才迁出旧版本。
|
||||
func MigrateLegacySSLStorage(root string) error {
|
||||
if !runtimepath.DeploymentLayout(root) {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(root, "config", "config.json"))
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
partitioned, err := isPartitionedConfig(data)
|
||||
if err != nil || !partitioned {
|
||||
return err
|
||||
}
|
||||
options := RuntimeValidationOptions{HasSuperAdmin: true}
|
||||
store := NewTransactionStore(root, options)
|
||||
if err := store.Recover(); err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := NewConfigLoader(root, ConfigLoaderOptions{Validation: options}).Load()
|
||||
if err != nil || !legacyManagedSSLReference(current.SSL.TLS.CertificateRef) {
|
||||
return err
|
||||
}
|
||||
ref, err := resolveManagedSSLReferencesAtRoot(root, current.SSL.TLS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := readExternalSSLFile(ref.PrivateKeyPath, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
certificate, err := readExternalSSLFile(ref.CertificatePath, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
candidate := cloneRuntimeConfig(current)
|
||||
next := &candidate.SSL.TLS
|
||||
if EffectiveSSLManagement(*next) != SSLManagementProject {
|
||||
ref, err = matchingDirectSSL(root, key, certificate)
|
||||
} else {
|
||||
ref = ManagedSSLReference{}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ref.CertificateRef == "" {
|
||||
ref, err = stageFlatSSLAtRoot(root, next.Mode, key, certificate, nil, validationCertificateDomains(&candidate))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer releaseManagedSSL(root, SSLConfig{CertificateRef: ref.CertificateRef})
|
||||
}
|
||||
next.CertificateRef, next.PrivateKeyRef = ref.CertificateRef, ref.PrivateKeyRef
|
||||
next.DefaultDirectory = "ssl"
|
||||
if next.Mode == ManagedSSLModeUpload {
|
||||
next.CustomDirectory = "ssl"
|
||||
}
|
||||
previous, err := previousLegacySSL(root, current.SSL.TLS, certificate, validationCertificateDomains(&candidate))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if previous.CertificateRef != "" {
|
||||
defer releaseManagedSSL(root, SSLConfig{CertificateRef: previous.CertificateRef})
|
||||
next.PreviousCertificateRef, next.PreviousPrivateKeyRef = previous.CertificateRef, previous.PrivateKeyRef
|
||||
}
|
||||
if err := validateCustomSSLReferences(root, candidate); err != nil {
|
||||
return err
|
||||
}
|
||||
setCandidateGeneration(&candidate, current.Generation+1)
|
||||
return store.Commit(current, candidate)
|
||||
}
|
||||
|
||||
func matchingDirectSSL(root string, key, certificate []byte) (ManagedSSLReference, error) {
|
||||
directory := filepath.Join(root, "ssl")
|
||||
entries, err := os.ReadDir(directory)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".crt") || strings.HasPrefix(entry.Name(), flatSSLPrefix) {
|
||||
continue
|
||||
}
|
||||
publicPath := filepath.Join(directory, entry.Name())
|
||||
privatePath := strings.TrimSuffix(publicPath, ".crt") + ".key"
|
||||
publicBytes, publicErr := readExternalSSLFile(publicPath, false)
|
||||
privateBytes, privateErr := readExternalSSLFile(privatePath, true)
|
||||
if publicErr == nil && privateErr == nil && bytes.Equal(certificate, publicBytes) && bytes.Equal(key, privateBytes) {
|
||||
return ManagedSSLReference{Mode: ManagedSSLModeUpload, CertificateRef: directSSLReference(root, publicPath), PrivateKeyRef: directSSLReference(root, privatePath)}, nil
|
||||
}
|
||||
}
|
||||
return ManagedSSLReference{}, nil
|
||||
}
|
||||
|
||||
// 重复副本不算上一套证书;只迁移最近一套仍有效且覆盖当前服务域名的不同材料。
|
||||
func previousLegacySSL(root string, active SSLConfig, certificate []byte, domains []string) (ManagedSSLReference, error) {
|
||||
var candidates []retainedSSLVersion
|
||||
for _, mode := range []string{ManagedSSLModeDefault, ManagedSSLModeUpload} {
|
||||
directory, err := managedSSLRootPathAtRoot(root, mode)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
entries, err := os.ReadDir(directory)
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !validSSLVersion(entry.Name()) && entry.Name() != "current" {
|
||||
continue
|
||||
}
|
||||
if info, err := entry.Info(); err == nil && info.IsDir() && info.Mode()&os.ModeSymlink == 0 {
|
||||
candidates = append(candidates, retainedSSLVersion{directory: filepath.Join(directory, entry.Name()), modified: info.ModTime()})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(candidates, func(i, j int) bool { return candidates[i].modified.After(candidates[j].modified) })
|
||||
for _, candidate := range candidates {
|
||||
publicBytes, publicErr := readExternalSSLFile(filepath.Join(candidate.directory, "public.crt"), false)
|
||||
privateBytes, privateErr := readExternalSSLFile(filepath.Join(candidate.directory, "private.key"), true)
|
||||
if publicErr != nil || privateErr != nil || bytes.Equal(certificate, publicBytes) || validateSSLMaterial(privateBytes, publicBytes, nil, domains) != nil {
|
||||
continue
|
||||
}
|
||||
return stageFlatSSLAtRoot(root, active.Mode, privateBytes, publicBytes, nil, domains)
|
||||
}
|
||||
return ManagedSSLReference{}, nil
|
||||
}
|
||||
@@ -36,6 +36,10 @@ func releaseManagedSSLLocked(root string, ssl SSLConfig) {
|
||||
}
|
||||
path, err := filepath.Abs(filepath.Join(root, filepath.FromSlash(runtimepath.SSLReference(root, ssl.CertificateRef))))
|
||||
if err == nil {
|
||||
if release := managedSSLStorage.staged[path]; release != nil {
|
||||
release()
|
||||
delete(managedSSLStorage.staged, path)
|
||||
}
|
||||
directory := filepath.Dir(path)
|
||||
if release := managedSSLStorage.staged[directory]; release != nil {
|
||||
release()
|
||||
@@ -86,6 +90,10 @@ func MaintainManagedSSLHistory() {
|
||||
if manager := CurrentManager(); manager != nil {
|
||||
manager.writeMu.Lock()
|
||||
defer manager.writeMu.Unlock()
|
||||
if err := manager.clearExpiredPreviousSSL(); err != nil {
|
||||
log.WithFields(log.Fields{"action": "清理过期证书引用", "result": "failure"}).Warn("配置维护未完成,下次自动重试")
|
||||
return
|
||||
}
|
||||
manager.mu.RLock()
|
||||
active := manager.current.SSL.TLS
|
||||
var pending []SSLConfig
|
||||
@@ -107,6 +115,11 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error {
|
||||
if len(protected) == 0 || protected[0].CertificateRef == "" {
|
||||
return nil
|
||||
}
|
||||
if !legacyManagedSSLReference(protected[0].CertificateRef) {
|
||||
if _, err := resolveManagedSSLReferencesAtRoot(root, protected[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// 恢复事务可能仍需要旧材料;恢复未完成时不能清理任何版本。
|
||||
if runtimepath.DeploymentLayout(root) {
|
||||
records, err := NewTransactionStore(root, RuntimeValidationOptions{HasSuperAdmin: true}).stateRecords("transaction")
|
||||
@@ -125,7 +138,9 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keep[filepath.Dir(reference.CertificatePath)] = true
|
||||
if legacyManagedSSLReference(ssl.CertificateRef) {
|
||||
keep[filepath.Dir(reference.CertificatePath)] = true
|
||||
}
|
||||
}
|
||||
// 磁盘引用也必须保留,避免其他管理器实例或已提交未发布的候选被删除。
|
||||
data, err := os.ReadFile(filepath.Join(root, "config", "ssl.json"))
|
||||
@@ -135,11 +150,14 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error {
|
||||
return err
|
||||
}
|
||||
if section.TLS.CertificateRef != "" {
|
||||
protected = append(protected, section.TLS)
|
||||
reference, err := resolveManagedSSLPathsAtRoot(root, section.TLS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keep[filepath.Dir(reference.CertificatePath)] = true
|
||||
if legacyManagedSSLReference(section.TLS.CertificateRef) {
|
||||
keep[filepath.Dir(reference.CertificatePath)] = true
|
||||
}
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
@@ -209,12 +227,14 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error {
|
||||
}
|
||||
return versions[i].modified.After(versions[j].modified)
|
||||
})
|
||||
// 两个模式合计保留两份;正在生效和暂存的版本优先,操作结束后收敛到两份。
|
||||
for _, version := range versions {
|
||||
if len(keep) >= 2 {
|
||||
break
|
||||
// 尚未迁移的旧配置暂时沿用旧规则;迁移完成后不再为 managed 额外保留副本。
|
||||
if legacyManagedSSLReference(protected[0].CertificateRef) {
|
||||
for _, version := range versions {
|
||||
if len(keep) >= 2 {
|
||||
break
|
||||
}
|
||||
keep[version.directory] = true
|
||||
}
|
||||
keep[version.directory] = true
|
||||
}
|
||||
var result error
|
||||
for _, version := range versions {
|
||||
@@ -222,7 +242,17 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error {
|
||||
result = errors.Join(result, removeManagedSSLDirectory(version.directory))
|
||||
}
|
||||
}
|
||||
return result
|
||||
if result == nil {
|
||||
// 仅删除已空的旧目录;未知文件会使 Remove 失败并原样保留。
|
||||
for _, mode := range []string{ManagedSSLModeDefault, ManagedSSLModeUpload} {
|
||||
directory, err := managedSSLRootPathAtRoot(root, mode)
|
||||
if err == nil {
|
||||
_ = os.Remove(directory)
|
||||
_ = os.Remove(filepath.Dir(directory))
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors.Join(result, pruneFlatSSLLocked(root, protected))
|
||||
}
|
||||
|
||||
// 回滚前必须检查实际证书,不能提交已经被保留策略淘汰的历史引用。
|
||||
|
||||
@@ -91,16 +91,27 @@ func LoadRuntimeTLSCertificate(cfg *Config) (tls.Certificate, error) {
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
certificate, err := tls.LoadX509KeyPair(certificatePath, privateKeyPath)
|
||||
privateKey, err := readExternalSSLFile(privateKeyPath, true)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
publicKey, err := readExternalSSLFile(certificatePath, false)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
if err := validateSSLMaterial(privateKey, publicKey, nil, nil); err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
certificate, err := tls.X509KeyPair(publicKey, privateKey)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
return certificate, nil
|
||||
}
|
||||
|
||||
// ImportManagedSSL 校验证书材料后写入候选目录,并原子切换 current 目录。
|
||||
// ImportManagedSSL 兼容旧调用名称;新材料只写入 ssl 根目录,不再创建 managed。
|
||||
func ImportManagedSSL(mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) {
|
||||
return importManagedSSLAtRoot(ROOT_PATH, mode, privateKeyPEM, certificatePEM, issuerPEM, domains)
|
||||
return StageManagedSSL(mode, privateKeyPEM, certificatePEM, issuerPEM, domains)
|
||||
}
|
||||
|
||||
func importManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) {
|
||||
@@ -211,7 +222,7 @@ func importManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificate
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ResolveManagedSSLReferences 将内部引用解析为受控文件路径,拒绝任意路径输入。
|
||||
// ResolveManagedSSLReferences 兼容旧名称;解析旧受管引用或自定义直接路径并复验证书。
|
||||
func ResolveManagedSSLReferences(ssl SSLConfig) (ManagedSSLReference, error) {
|
||||
return resolveManagedSSLReferencesAtRoot(ROOT_PATH, ssl)
|
||||
}
|
||||
@@ -236,6 +247,20 @@ func resolveManagedSSLPathsAtRoot(root string, ssl SSLConfig) (ManagedSSLReferen
|
||||
if ssl.CertificateRef == "" || ssl.PrivateKeyRef == "" {
|
||||
return ManagedSSLReference{}, ErrInvalidSSLReference
|
||||
}
|
||||
if !legacyManagedSSLReference(ssl.CertificateRef) && !legacyManagedSSLReference(ssl.PrivateKeyRef) {
|
||||
certificatePath, err := resolveCustomSSLInput(root, ssl.CertificateRef)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
privateKeyPath, err := resolveCustomSSLInput(root, ssl.PrivateKeyRef)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
}
|
||||
if ssl.Mode == ManagedSSLModeDefault && !flatSSLPair(root, certificatePath, privateKeyPath) {
|
||||
return ManagedSSLReference{}, ErrInvalidSSLReference
|
||||
}
|
||||
return ManagedSSLReference{Mode: ssl.Mode, CertificateRef: ssl.CertificateRef, PrivateKeyRef: ssl.PrivateKeyRef, CertificatePath: certificatePath, PrivateKeyPath: privateKeyPath}, nil
|
||||
}
|
||||
rootPath, err := managedSSLRootPathAtRoot(root, ssl.Mode)
|
||||
if err != nil {
|
||||
return ManagedSSLReference{}, err
|
||||
@@ -464,7 +489,7 @@ func validSSLVersion(version string) bool {
|
||||
|
||||
// StageManagedSSL 只写入独立版本,不替换现用文件;配置事务成功后引用才生效。
|
||||
func StageManagedSSL(mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) {
|
||||
return stageManagedSSLAtRoot(ROOT_PATH, mode, privateKeyPEM, certificatePEM, issuerPEM, domains)
|
||||
return stageFlatSSLAtRoot(ROOT_PATH, mode, privateKeyPEM, certificatePEM, issuerPEM, domains)
|
||||
}
|
||||
|
||||
func stageManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) {
|
||||
@@ -540,25 +565,13 @@ func stageManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificateP
|
||||
}
|
||||
|
||||
func validateManagedSSLFiles(certificatePath, privateKeyPath string) error {
|
||||
for _, item := range []struct {
|
||||
path string
|
||||
isPrivate bool
|
||||
}{{certificatePath, false}, {privateKeyPath, true}} {
|
||||
info, err := os.Lstat(item.path)
|
||||
if err != nil || info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > maxManagedSSLFileSize || hasMultipleFileLinks(item.path) {
|
||||
return ErrUnsafeSSLFile
|
||||
}
|
||||
if item.isPrivate && info.Mode().Perm()&0077 != 0 && runtimeSupportsPermissionCheck() {
|
||||
return ErrSSLPrivateKeyPermission
|
||||
}
|
||||
}
|
||||
privateKeyPEM, err := os.ReadFile(privateKeyPath)
|
||||
privateKeyPEM, err := readExternalSSLFile(privateKeyPath, true)
|
||||
if err != nil {
|
||||
return ErrUnsafeSSLFile
|
||||
return err
|
||||
}
|
||||
certificatePEM, err := os.ReadFile(certificatePath)
|
||||
certificatePEM, err := readExternalSSLFile(certificatePath, false)
|
||||
if err != nil {
|
||||
return ErrUnsafeSSLFile
|
||||
return err
|
||||
}
|
||||
return validateSSLMaterial(privateKeyPEM, certificatePEM, nil, nil)
|
||||
}
|
||||
|
||||
@@ -11,12 +11,11 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) {
|
||||
func TestImportManagedSSLUsesImmutableRootFiles(t *testing.T) {
|
||||
oldRoot := ROOT_PATH
|
||||
ROOT_PATH = t.TempDir()
|
||||
t.Cleanup(func() { ROOT_PATH = oldRoot })
|
||||
@@ -26,10 +25,11 @@ func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ReleaseStagedSSL(first)
|
||||
if filepath.IsAbs(first.CertificateRef) || filepath.IsAbs(first.PrivateKeyRef) {
|
||||
t.Fatal("SSL 内部引用不应为绝对路径")
|
||||
}
|
||||
if first.CertificateRef != "data/ssl/managed/default/current/public.crt" || first.PrivateKeyRef != "data/ssl/managed/default/current/private.key" {
|
||||
if !flatSSLPair(ROOT_PATH, first.CertificatePath, first.PrivateKeyPath) {
|
||||
t.Fatalf("内部引用不符合预期: %+v", first)
|
||||
}
|
||||
resolved, err := ResolveManagedSSLReferences(SSLConfig{Mode: ManagedSSLModeDefault, DefaultDirectory: "config/ssl", CertificateRef: first.CertificateRef, PrivateKeyRef: first.PrivateKeyRef})
|
||||
@@ -45,8 +45,9 @@ func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second.CertificatePath != first.CertificatePath {
|
||||
t.Fatal("current 引用路径应保持稳定")
|
||||
defer ReleaseStagedSSL(second)
|
||||
if second.CertificatePath == first.CertificatePath {
|
||||
t.Fatal("新证书必须使用独立文件,不能覆盖正在使用的材料")
|
||||
}
|
||||
currentData, err := os.ReadFile(second.CertificatePath)
|
||||
if err != nil {
|
||||
@@ -55,22 +56,9 @@ func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) {
|
||||
if string(currentData) == string(certificatePEM) {
|
||||
t.Fatal("current 目录没有切换到新证书")
|
||||
}
|
||||
previousMatches := false
|
||||
entries, err := os.ReadDir(filepath.Dir(filepath.Dir(second.CertificatePath)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !strings.HasPrefix(entry.Name(), ".previous-") {
|
||||
continue
|
||||
}
|
||||
previousData, readErr := os.ReadFile(filepath.Join(filepath.Dir(filepath.Dir(second.CertificatePath)), entry.Name(), "public.crt"))
|
||||
if readErr == nil && string(previousData) == string(certificatePEM) {
|
||||
previousMatches = true
|
||||
}
|
||||
}
|
||||
if !previousMatches {
|
||||
t.Fatal("更新后未保留旧证书目录")
|
||||
previousData, err := os.ReadFile(first.CertificatePath)
|
||||
if err != nil || string(previousData) != string(certificatePEM) {
|
||||
t.Fatal("暂存新证书改变了原证书")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,8 +134,8 @@ func TestResolveManagedSSLReferencesRejectsUnsafeReferences(t *testing.T) {
|
||||
{Mode: ManagedSSLModeUpload, CertificateRef: `\\server\share\public.crt`, PrivateKeyRef: reference.PrivateKeyRef},
|
||||
}
|
||||
for index, candidate := range unsafe {
|
||||
if _, err := ResolveManagedSSLReferences(candidate); !errors.Is(err, ErrInvalidSSLReference) {
|
||||
t.Fatalf("用例 %d error = %v, want %v", index, err, ErrInvalidSSLReference)
|
||||
if _, err := ResolveManagedSSLReferences(candidate); err == nil {
|
||||
t.Fatalf("用例 %d 不应接受缺失、不配对或不安全的文件", index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,7 +191,7 @@ func TestValidateSSLMaterialRejectsDomainExpiryAndWeakKeys(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareCustomSSLPathsImportsExternalFilesOnlyWhenSaving(t *testing.T) {
|
||||
func TestPrepareCustomSSLPathsKeepsDirectFilesWithoutCopying(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
previousRoot := ROOT_PATH
|
||||
ROOT_PATH = root
|
||||
@@ -233,8 +221,8 @@ func TestPrepareCustomSSLPathsImportsExternalFilesOnlyWhenSaving(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("校验外部证书失败: %v", err)
|
||||
}
|
||||
if runtime.SSL.TLS.CertificateRef == certificatePath || runtime.SSL.TLS.PrivateKeyRef == privateKeyPath {
|
||||
t.Fatal("仅校验阶段不应保留外部证书路径")
|
||||
if runtime.SSL.TLS.CertificateRef != filepath.ToSlash(certificatePath) || runtime.SSL.TLS.PrivateKeyRef != filepath.ToSlash(privateKeyPath) {
|
||||
t.Fatal("仅校验阶段应保留规范化的直接路径")
|
||||
}
|
||||
managedRoot := filepath.Join(root, "data", "ssl", "managed", "upload")
|
||||
if _, err := os.Stat(managedRoot); !os.IsNotExist(err) {
|
||||
@@ -244,11 +232,11 @@ func TestPrepareCustomSSLPathsImportsExternalFilesOnlyWhenSaving(t *testing.T) {
|
||||
if err := material.stage(root, &runtime); err != nil {
|
||||
t.Fatalf("保存外部证书失败: %v", err)
|
||||
}
|
||||
if runtime.SSL.TLS.CertificateRef == certificatePath || runtime.SSL.TLS.PrivateKeyRef == privateKeyPath {
|
||||
t.Fatal("保存后不应继续使用外部证书路径")
|
||||
if runtime.SSL.TLS.CertificateRef != filepath.ToSlash(certificatePath) || runtime.SSL.TLS.PrivateKeyRef != filepath.ToSlash(privateKeyPath) {
|
||||
t.Fatal("保存后应继续引用原始文件")
|
||||
}
|
||||
if !strings.HasPrefix(runtime.SSL.TLS.CertificateRef, "data/ssl/managed/upload/version-") {
|
||||
t.Fatalf("证书引用未切换到受管版本: %q", runtime.SSL.TLS.CertificateRef)
|
||||
if _, err := os.Stat(managedRoot); !os.IsNotExist(err) {
|
||||
t.Fatal("保存自定义证书不应创建副本")
|
||||
}
|
||||
if _, err := ResolveManagedSSLReferences(runtime.SSL.TLS); err != nil {
|
||||
t.Fatalf("受管证书引用无法解析: %v", err)
|
||||
@@ -263,7 +251,7 @@ func TestValidateSSLMaterialAcceptsBundledIssuerWithoutDuplicateChainEntry(t *te
|
||||
}
|
||||
}
|
||||
|
||||
func testManagedCertificate(t *testing.T, domain string, notBefore, notAfter time.Time, bits int) ([]byte, []byte) {
|
||||
func testManagedCertificate(t *testing.T, domain string, notBefore, notAfter time.Time, bits int, additionalDomains ...string) ([]byte, []byte) {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, bits)
|
||||
if err != nil {
|
||||
@@ -272,7 +260,7 @@ func testManagedCertificate(t *testing.T, domain string, notBefore, notAfter tim
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(time.Now().UnixNano()),
|
||||
Subject: pkix.Name{CommonName: domain},
|
||||
DNSNames: []string{domain},
|
||||
DNSNames: append([]string{domain}, additionalDomains...),
|
||||
NotBefore: notBefore,
|
||||
NotAfter: notAfter,
|
||||
BasicConstraintsValid: true,
|
||||
|
||||
@@ -173,6 +173,16 @@ func smtpRelayConfigured(smtp SMTPConfig) bool {
|
||||
}
|
||||
|
||||
func validateSSL(ssl SSLConfig) error {
|
||||
if (ssl.PreviousCertificateRef == "") != (ssl.PreviousPrivateKeyRef == "") {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
if ssl.PreviousCertificateRef != "" {
|
||||
publicPath, err := resolveCustomSSLInput(".", ssl.PreviousCertificateRef)
|
||||
privatePath, keyErr := resolveCustomSSLInput(".", ssl.PreviousPrivateKeyRef)
|
||||
if err != nil || keyErr != nil || !isControlledRelativePath(ssl.PreviousCertificateRef) || !isControlledRelativePath(ssl.PreviousPrivateKeyRef) || !flatSSLPair(".", publicPath, privatePath) {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
}
|
||||
if !isControlledRelativePath(ssl.DefaultDirectory) {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
@@ -196,6 +206,19 @@ func validateSSL(ssl SSLConfig) error {
|
||||
default:
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
if EffectiveSSLManagement(ssl) == SSLManagementCustom || EffectiveSSLManagement(ssl) == SSLManagementWebServer {
|
||||
if (ssl.CertificateRef == "") != (ssl.PrivateKeyRef == "") {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
for _, value := range []string{ssl.CertificateRef, ssl.PrivateKeyRef} {
|
||||
if value != "" {
|
||||
if _, err := resolveCustomSSLInput(".", value); err != nil {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if (ssl.CertificateRef != "" && !isControlledRelativePath(ssl.CertificateRef)) ||
|
||||
(ssl.PrivateKeyRef != "" && !isControlledRelativePath(ssl.PrivateKeyRef)) {
|
||||
return ErrInvalidSSL
|
||||
|
||||
@@ -21,6 +21,9 @@ func Run() (err error) {
|
||||
if err := runtimepath.CheckReady(config.ROOT_PATH); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.MigrateLegacySSLStorage(config.ROOT_PATH); err != nil {
|
||||
return fmt.Errorf("迁移证书存储失败,原文件已保留: %w", err)
|
||||
}
|
||||
if err := config.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package cron_server
|
||||
import (
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/services/setup/ssl"
|
||||
"git.pcux.cn/xuans/Smail/signal"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"time"
|
||||
// 新增:HTTP 就绪探测
|
||||
@@ -14,8 +13,6 @@ import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var expiredTime time.Time
|
||||
|
||||
func Start() {
|
||||
|
||||
// 第一次启动,等待到初始化完成
|
||||
@@ -34,26 +31,14 @@ func Start() {
|
||||
|
||||
// 只检查外部维护的本地邮件证书是否更新,不触发 ACME。
|
||||
func sslCheck() {
|
||||
_, newExpTime, _, err := ssl.CheckSSLCrtInfo()
|
||||
if err != nil {
|
||||
log.Errorf("SSL Check Error! %+v", err)
|
||||
return
|
||||
}
|
||||
if expiredTime.IsZero() {
|
||||
expiredTime = newExpTime
|
||||
return
|
||||
}
|
||||
if newExpTime != expiredTime {
|
||||
expiredTime = newExpTime
|
||||
log.Infoln("SSL certificate had update! restarting")
|
||||
signal.RestartChan <- true
|
||||
}
|
||||
// 校验失败时保留尚未过期的内存证书;不发送服务重启信号。
|
||||
_ = config.ReloadRuntimeTLSCertificate()
|
||||
}
|
||||
|
||||
// 每轮读取最新策略,切换反代模式后不再等待 HTTP 挑战或执行自动续期。
|
||||
func maintainSSL() {
|
||||
config.MaintainManagedSSLHistory()
|
||||
cfg := config.CurrentConfig()
|
||||
cfg := config.CurrentCertificateConfig()
|
||||
if cfg == nil || !cfg.IsSetupReady() {
|
||||
return
|
||||
}
|
||||
@@ -61,7 +46,6 @@ func maintainSSL() {
|
||||
sslCheck()
|
||||
return
|
||||
}
|
||||
expiredTime = time.Time{}
|
||||
if cfg.SSLType == config.SSLTypeAutoHTTP && !waitHTTPReady() {
|
||||
return
|
||||
}
|
||||
@@ -70,10 +54,17 @@ func maintainSSL() {
|
||||
|
||||
// 每天检查证书,外部管理模式仅保留本地证书变更检查。
|
||||
func sslUpdateLoop() {
|
||||
lastRenewal := time.Time{}
|
||||
for {
|
||||
maintainSSL()
|
||||
// 每24小时检测一次证书有效期
|
||||
time.Sleep(24 * time.Hour)
|
||||
if time.Since(lastRenewal) >= 24*time.Hour {
|
||||
maintainSSL()
|
||||
lastRenewal = time.Now()
|
||||
} else {
|
||||
config.MaintainManagedSSLHistory()
|
||||
sslCheck()
|
||||
}
|
||||
// 每分钟清理已到期的上一套证书;自动签发仍最多每天检查一次。
|
||||
time.Sleep(time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +84,7 @@ func waitHTTPReady() bool {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
|
||||
for i := 0; i < 90; i++ {
|
||||
if !config.CurrentConfig().AutomaticSSLEnabled() {
|
||||
if !config.CurrentCertificateConfig().AutomaticSSLEnabled() {
|
||||
return false
|
||||
}
|
||||
requestContext, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
|
||||
@@ -67,12 +67,13 @@ func HttpsStart() error {
|
||||
if legacyCfg == nil {
|
||||
return fmt.Errorf("legacy SSL configuration is unavailable")
|
||||
}
|
||||
certificatePath, privateKeyPath, err := config.ResolveRuntimeSSLPaths(legacyCfg)
|
||||
tlsConfig, err := config.NewRuntimeTLSConfig()
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve HTTPS certificate: %w", err)
|
||||
}
|
||||
|
||||
httpsServer = &http.Server{
|
||||
TLSConfig: tlsConfig,
|
||||
Addr: fmt.Sprintf(":%d", httpsPort),
|
||||
Handler: securityHeaders(dbmigration.GuardHTTP(session.Instance.LoadAndSave(mux))),
|
||||
ReadTimeout: time.Second * 90,
|
||||
@@ -83,7 +84,7 @@ func HttpsStart() error {
|
||||
ErrorLog: nullLog,
|
||||
}
|
||||
log.WithFields(log.Fields{"action": "启动 HTTPS 监听", "object": httpsServer.Addr, "result": "started"}).Info("开始绑定监听端口")
|
||||
if err := httpsServer.ListenAndServeTLS(certificatePath, privateKeyPath); err != nil {
|
||||
if err := httpsServer.ListenAndServeTLS("", ""); err != nil {
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
log.WithFields(log.Fields{"action": "停止 HTTPS 监听", "object": httpsServer.Addr, "result": "success"}).Info("监听已正常关闭")
|
||||
return nil
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package imap_server
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"github.com/emersion/go-imap/v2"
|
||||
@@ -62,14 +61,10 @@ func newIMAPServer() (*imapserver.Server, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("runtime configuration is unavailable")
|
||||
}
|
||||
crt, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
tlsConfig, err := config.NewRuntimeTLSConfig()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load IMAP TLS certificate: %w", err)
|
||||
}
|
||||
tlsConfig := &tls.Config{
|
||||
Certificates: []tls.Certificate{crt},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
|
||||
memServer := NewServer()
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ func writeIMAPTestCertificate(root string) (string, string, error) {
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "localhost"},
|
||||
DNSNames: []string{"localhost"},
|
||||
DNSNames: []string{"localhost", "test.domain", "*.test.domain"},
|
||||
NotBefore: time.Now().Add(-time.Minute),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
|
||||
@@ -2,7 +2,6 @@ package pop3_server
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/internal/gopop"
|
||||
@@ -22,12 +21,10 @@ func StartWithTls() error {
|
||||
if domains.Primary == "" {
|
||||
return fmt.Errorf("mail domain is not configured")
|
||||
}
|
||||
crt, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
tlsConfig, err := config.NewRuntimeTLSConfig()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load POP3 TLS certificate: %w", err)
|
||||
}
|
||||
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12}
|
||||
tlsConfig.Certificates = []tls.Certificate{crt}
|
||||
tlsConfig.Time = time.Now
|
||||
tlsConfig.Rand = rand.Reader
|
||||
port := config.CurrentMailPorts().POP3TLS
|
||||
@@ -52,12 +49,10 @@ func Start() error {
|
||||
if domains.Primary == "" {
|
||||
return fmt.Errorf("mail domain is not configured")
|
||||
}
|
||||
crt, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
tlsConfig, err := config.NewRuntimeTLSConfig()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load POP3 certificate: %w", err)
|
||||
}
|
||||
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12}
|
||||
tlsConfig.Certificates = []tls.Certificate{crt}
|
||||
tlsConfig.Time = time.Now
|
||||
tlsConfig.Rand = rand.Reader
|
||||
port := config.CurrentMailPorts().POP3
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package smtp_server
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
@@ -43,12 +42,12 @@ func StartWithTLSNew() error {
|
||||
// force TLS for auth
|
||||
instanceTlsNew.AllowInsecureAuth = false
|
||||
// Load the certificate and key
|
||||
cer, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
tlsConfig, err := config.NewRuntimeTLSConfig()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load SMTP STARTTLS certificate: %w", err)
|
||||
}
|
||||
// Configure the TLS support for STARTTLS
|
||||
instanceTlsNew.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cer}, MinVersion: tls.VersionTLS12}
|
||||
instanceTlsNew.TLSConfig = tlsConfig
|
||||
|
||||
log.WithFields(log.Fields{"action": "启动 SMTP STARTTLS 监听", "object": instanceTlsNew.Addr, "result": "started"}).Info("开始绑定监听端口")
|
||||
// 提交端口使用 STARTTLS(先连接,再升级 TLS),而非隐式 TLS。
|
||||
@@ -80,12 +79,12 @@ func StartWithTLS() error {
|
||||
// force TLS for auth
|
||||
instanceTls.AllowInsecureAuth = true
|
||||
// Load the certificate and key
|
||||
cer, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
tlsConfig, err := config.NewRuntimeTLSConfig()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load SMTP TLS certificate: %w", err)
|
||||
}
|
||||
// Configure the TLS support
|
||||
instanceTls.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cer}, MinVersion: tls.VersionTLS12}
|
||||
instanceTls.TLSConfig = tlsConfig
|
||||
|
||||
log.WithFields(log.Fields{"action": "启动 SMTP TLS 监听", "object": instanceTls.Addr, "result": "started"}).Info("开始绑定监听端口")
|
||||
if err := instanceTls.ListenAndServeTLS(); err != nil && !errors.Is(err, smtp.ErrServerClosed) {
|
||||
@@ -116,12 +115,12 @@ func Start() error {
|
||||
// force TLS for auth
|
||||
instance.AllowInsecureAuth = false
|
||||
// Load the certificate and key
|
||||
cer, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
tlsConfig, err := config.NewRuntimeTLSConfig()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load SMTP certificate: %w", err)
|
||||
}
|
||||
// Configure the TLS support
|
||||
instance.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cer}, MinVersion: tls.VersionTLS12}
|
||||
instance.TLSConfig = tlsConfig
|
||||
|
||||
log.WithFields(log.Fields{"action": "启动 SMTP 收信监听", "object": instance.Addr, "result": "started"}).Info("开始绑定监听端口")
|
||||
if err := instance.ListenAndServe(); err != nil && !errors.Is(err, smtp.ErrServerClosed) {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
stderrors "errors"
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/services/setup"
|
||||
"git.pcux.cn/xuans/Smail/signal"
|
||||
"git.pcux.cn/xuans/Smail/utils/async"
|
||||
"git.pcux.cn/xuans/Smail/utils/errors"
|
||||
"git.pcux.cn/xuans/Smail/utils/runtimepath"
|
||||
@@ -138,20 +137,11 @@ func SetSSL(sslType, priKey, crtKey string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
privatePEM, err := os.ReadFile(privatePath)
|
||||
if err != nil {
|
||||
return newUserCertificateError("SSL 私钥无法读取,请确认文件路径和 smail 用户权限")
|
||||
}
|
||||
publicPEM, err := os.ReadFile(publicPath)
|
||||
if err != nil {
|
||||
return newUserCertificateError("SSL 证书无法读取,请确认文件路径和 smail 用户权限")
|
||||
}
|
||||
reference, err := config.StageManagedSSL(config.ManagedSSLModeUpload, privatePEM, publicPEM, nil, sslDomains(cfg))
|
||||
reference, err := config.ValidateDirectSSLPaths(publicPath, privatePath, sslDomains(cfg))
|
||||
if err != nil {
|
||||
return normalizeUserCertificateImportError(err)
|
||||
}
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
defer config.ReleaseStagedSSL(reference)
|
||||
// 导入邮件服务证书不能重新启用反代模式下的内置 HTTPS。
|
||||
if cfg.UsesProxyHTTPS() {
|
||||
cfg.HttpsEnabled = 2
|
||||
@@ -177,7 +167,7 @@ func clearLegacySSLPaths(cfg *config.Config) {
|
||||
cfg.SSLPublicKeyPath = ""
|
||||
}
|
||||
|
||||
// applyManagedSSLReference 将证书切换结果写入内部引用,不持久化服务器路径。
|
||||
// applyManagedSSLReference 保存已校验的证书路径,新签发文件直接位于 ssl 下。
|
||||
func applyManagedSSLReference(cfg *config.Config, reference config.ManagedSSLReference) {
|
||||
if cfg == nil {
|
||||
return
|
||||
@@ -192,12 +182,12 @@ func applyManagedSSLReference(cfg *config.Config, reference config.ManagedSSLRef
|
||||
cfg.SSL = config.SSLConfig{
|
||||
Management: management,
|
||||
Mode: reference.Mode,
|
||||
DefaultDirectory: runtimepath.SSLReference(config.ROOT_PATH, "data/ssl"),
|
||||
DefaultDirectory: "ssl",
|
||||
CertificateRef: reference.CertificateRef,
|
||||
PrivateKeyRef: reference.PrivateKeyRef,
|
||||
}
|
||||
if reference.Mode == config.ManagedSSLModeUpload {
|
||||
cfg.SSL.CustomDirectory = runtimepath.SSLReference(config.ROOT_PATH, "data/ssl/managed/upload")
|
||||
cfg.SSL.CustomDirectory = "ssl"
|
||||
} else if cfg.SSLType == config.SSLTypeAutoDNS {
|
||||
cfg.SSL.Challenge = config.SSLChallengeDNS
|
||||
} else {
|
||||
@@ -596,8 +586,8 @@ func CheckSSLCrtInfo() (int, time.Time, bool, error) {
|
||||
return cast.ToInt(hours / 24), cert.NotAfter, nameMatchFail, nil
|
||||
}
|
||||
|
||||
func Update(needRestart bool) {
|
||||
cfg := config.CurrentConfig()
|
||||
func Update(_ bool) {
|
||||
cfg := config.CurrentCertificateConfig()
|
||||
if cfg.AutomaticSSLEnabled() && cfg.IsSetupReady() {
|
||||
days, _, nameMatchFail, err := CheckSSLCrtInfo()
|
||||
|
||||
@@ -613,9 +603,8 @@ func Update(needRestart bool) {
|
||||
return
|
||||
}
|
||||
log.WithFields(log.Fields{"action": "更新 TLS 证书", "result": "success"}).Info("证书已更新并保存")
|
||||
if needRestart {
|
||||
// 更新完证书,重启服务
|
||||
signal.RestartChan <- true
|
||||
if err := config.ReloadRuntimeTLSCertificate(); err != nil {
|
||||
log.WithFields(log.Fields{"action": "热加载 TLS 证书", "result": "failure"}).Warn("续期配置已保存,运行证书切换失败,请检查证书文件")
|
||||
}
|
||||
} else {
|
||||
log.Debugf("SSL Check.")
|
||||
|
||||
@@ -94,7 +94,7 @@ func TestApplyManagedSSLReferenceDoesNotPersistLegacyPaths(t *testing.T) {
|
||||
if cfg.SSL.Mode != config.ManagedSSLModeUpload || cfg.SSL.CertificateRef != reference.CertificateRef || cfg.SSL.PrivateKeyRef != reference.PrivateKeyRef {
|
||||
t.Fatalf("受控 SSL 内部引用写入错误: %+v", cfg.SSL)
|
||||
}
|
||||
if cfg.SSL.CustomDirectory != "data/ssl/managed/upload" {
|
||||
if cfg.SSL.CustomDirectory != "ssl" {
|
||||
t.Fatalf("自定义受控目录写入错误: %s", cfg.SSL.CustomDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ func PrepareDeploymentKeys(root string) error {
|
||||
return err
|
||||
}
|
||||
// 先检查所有目标,不能移动第一把密钥后才发现另一业务目录不安全。
|
||||
for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} {
|
||||
for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim"} {
|
||||
if err := safeDirectory(filepath.Join(ssl, folder)); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
@@ -114,7 +114,7 @@ func PrepareDeploymentKeys(root string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} {
|
||||
for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim"} {
|
||||
if _, err := SecureDirectory(ssl, folder); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user