统一 frontend、backend、test、test-log 和 out 目录,更新构建、部署及测试入口;纳入配置管理兼容与首次安全引导修复;排除本机配置、密钥和测试产物。
This commit is contained in:
1 parent
28cd9d3406
commit
f60d3b0880
603 files changed
+2351
-660
No files matched your search
@@ -0,0 +1,119 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
"github.com/go-acme/lego/v4/challenge/dns01"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type authInfo struct {
|
||||
Domain string
|
||||
Token string
|
||||
KeyAuth string
|
||||
}
|
||||
|
||||
type HttpChallenge struct {
|
||||
mu sync.RWMutex
|
||||
authInfo map[string]*authInfo
|
||||
}
|
||||
|
||||
var instance = &HttpChallenge{authInfo: map[string]*authInfo{}}
|
||||
|
||||
func (h *HttpChallenge) Present(domain, token, keyAuth string) error {
|
||||
h.mu.Lock()
|
||||
h.authInfo[token] = &authInfo{
|
||||
Domain: domain,
|
||||
Token: token,
|
||||
KeyAuth: keyAuth,
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *HttpChallenge) CleanUp(domain, token, keyAuth string) error {
|
||||
h.mu.Lock()
|
||||
delete(h.authInfo, token)
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetHttpChallengeInstance() *HttpChallenge {
|
||||
return instance
|
||||
}
|
||||
|
||||
func (h *HttpChallenge) KeyAuthorization(token string) (string, bool) {
|
||||
h.mu.RLock()
|
||||
info, ok := h.authInfo[token]
|
||||
h.mu.RUnlock()
|
||||
if !ok || info == nil {
|
||||
return "", false
|
||||
}
|
||||
return info.KeyAuth, true
|
||||
}
|
||||
|
||||
type DNSChallenge struct {
|
||||
mu sync.RWMutex
|
||||
authInfo map[string]*authInfo
|
||||
}
|
||||
|
||||
var dnsInstance = &DNSChallenge{authInfo: map[string]*authInfo{}}
|
||||
|
||||
func GetDnsChallengeInstance() *DNSChallenge {
|
||||
return dnsInstance
|
||||
}
|
||||
|
||||
func (h *DNSChallenge) Present(domain, token, keyAuth string) error {
|
||||
challengeDomain := strings.TrimSpace(domain)
|
||||
challengeDomain = strings.TrimSuffix(challengeDomain, ".")
|
||||
challengeDomain = strings.TrimPrefix(challengeDomain, "*.")
|
||||
info := dns01.GetChallengeInfo(challengeDomain, keyAuth)
|
||||
log.Infof("SSL DNS challenge generated for domain=%s", domain)
|
||||
h.mu.Lock()
|
||||
h.authInfo[token] = &authInfo{
|
||||
Domain: info.FQDN,
|
||||
Token: token,
|
||||
KeyAuth: info.Value,
|
||||
}
|
||||
h.mu.Unlock()
|
||||
log.Info("SSL challenge value generated")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *DNSChallenge) CleanUp(domain, token, keyAuth string) error {
|
||||
h.mu.Lock()
|
||||
delete(h.authInfo, token)
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *DNSChallenge) Timeout() (timeout, interval time.Duration) {
|
||||
return 60 * time.Minute, 5 * time.Second
|
||||
}
|
||||
|
||||
type DNSItem struct {
|
||||
Type string `json:"type"`
|
||||
Host string `json:"host"`
|
||||
Value string `json:"value"`
|
||||
TTL int `json:"ttl"`
|
||||
Tips string `json:"tips"`
|
||||
}
|
||||
|
||||
func (h *DNSChallenge) GetDNSSettings(ctx *context.Context) []*DNSItem {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
ret := []*DNSItem{}
|
||||
for _, info := range h.authInfo {
|
||||
ret = append(ret, &DNSItem{
|
||||
Type: "TXT",
|
||||
Host: info.Domain,
|
||||
Value: info.KeyAuth,
|
||||
TTL: 3600,
|
||||
})
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHttpChallengeConcurrentAccess(t *testing.T) {
|
||||
h := &HttpChallenge{authInfo: map[string]*authInfo{}}
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
token := fmt.Sprintf("token-%d", i)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := h.Present("example.com", token, "key-"+token); err != nil {
|
||||
t.Errorf("Present returned an error: %v", err)
|
||||
return
|
||||
}
|
||||
if keyAuth, ok := h.KeyAuthorization(token); !ok || keyAuth != "key-"+token {
|
||||
t.Errorf("unexpected key authorization for %s", token)
|
||||
}
|
||||
if err := h.CleanUp("example.com", token, "key-"+token); err != nil {
|
||||
t.Errorf("CleanUp returned an error: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestDNSChallengeConcurrentAccess(t *testing.T) {
|
||||
h := &DNSChallenge{authInfo: map[string]*authInfo{}}
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
token := fmt.Sprintf("token-%d", i)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := h.Present("example.com", token, "key-"+token); err != nil {
|
||||
t.Errorf("Present returned an error: %v", err)
|
||||
return
|
||||
}
|
||||
_ = h.GetDNSSettings(nil)
|
||||
if err := h.CleanUp("example.com", token, "key-"+token); err != nil {
|
||||
t.Errorf("CleanUp returned an error: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package ssl
|
||||
|
||||
//import (
|
||||
// "github.com/go-acme/lego/v4/providers/dns"
|
||||
// "os"
|
||||
// "git.pcux.cn/xuans/Smail/utils/errors"
|
||||
// "regexp"
|
||||
// "strings"
|
||||
//)
|
||||
//
|
||||
//func GetServerParamsList(serverName string) ([]string, error) {
|
||||
// var serverParams []string
|
||||
//
|
||||
// infos, err := os.ReadDir("./")
|
||||
// if err != nil {
|
||||
// return nil, errors.Wrap(err)
|
||||
// }
|
||||
//
|
||||
// upperServerName := strings.ToUpper(serverName)
|
||||
//
|
||||
// for _, info := range infos {
|
||||
// if strings.HasPrefix(info.Name(), upperServerName) {
|
||||
// serverParams = append(serverParams, info.Name())
|
||||
// }
|
||||
// }
|
||||
// if len(serverParams) != 0 {
|
||||
// return serverParams, nil
|
||||
// }
|
||||
//
|
||||
// _, err = dns.NewDNSChallengeProviderByName(serverName)
|
||||
// if err == nil {
|
||||
// return nil, errors.New(serverName + " Not Support")
|
||||
// }
|
||||
// if strings.Contains(err.Error(), "unrecognized DNS provider") {
|
||||
// return nil, err
|
||||
// }
|
||||
//
|
||||
// re := regexp.MustCompile(`missing: (.+)`)
|
||||
// // namesilo: some credentials information are missing: NAMESILO_API_KEY
|
||||
// estr := err.Error()
|
||||
// name := re.FindStringSubmatch(estr)
|
||||
//
|
||||
// if len(name) == 2 {
|
||||
// names := strings.Split(name[1], ",")
|
||||
//
|
||||
// for _, s := range names {
|
||||
// serverParams = append(serverParams, s)
|
||||
// SetDomainServerParams(s, "empty")
|
||||
// }
|
||||
//
|
||||
// }
|
||||
// _, err = dns.NewDNSChallengeProviderByName(serverName)
|
||||
//
|
||||
// return serverParams, err
|
||||
//}
|
||||
//
|
||||
//func SetDomainServerParams(name, value string) {
|
||||
// key := name
|
||||
// err := os.WriteFile(key, []byte(value), 0644)
|
||||
// if err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
// err = os.Setenv(name+"_FILE", key)
|
||||
// if err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,555 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
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"
|
||||
"github.com/go-acme/lego/v4/certificate"
|
||||
"github.com/go-acme/lego/v4/challenge/dns01"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cast"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
)
|
||||
|
||||
type MyUser struct {
|
||||
Email string
|
||||
Registration *registration.Resource
|
||||
key crypto.PrivateKey
|
||||
}
|
||||
|
||||
type userCertificateError struct {
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *userCertificateError) Error() string {
|
||||
return e.message
|
||||
}
|
||||
|
||||
func newUserCertificateError(message string) error {
|
||||
return &userCertificateError{message: message}
|
||||
}
|
||||
|
||||
// UserCertificateErrorMessage 只返回可以安全展示给初始化页面的证书错误。
|
||||
func UserCertificateErrorMessage(err error) string {
|
||||
var certificateError *userCertificateError
|
||||
if stderrors.As(err, &certificateError) {
|
||||
return certificateError.message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func normalizeUserCertificateImportError(err error) error {
|
||||
switch {
|
||||
case stderrors.Is(err, config.ErrSSLCertificateMismatch):
|
||||
return newUserCertificateError("SSL 证书与私钥不匹配")
|
||||
case stderrors.Is(err, config.ErrSSLCertificateDomain):
|
||||
return newUserCertificateError("SSL 证书与已配置域名不匹配,请检查主域名、Web 域名和附加域名")
|
||||
case stderrors.Is(err, config.ErrSSLCertificateExpired):
|
||||
return newUserCertificateError("SSL 证书无效、尚未生效或已经过期")
|
||||
case stderrors.Is(err, config.ErrSSLPrivateKeyPermission):
|
||||
return newUserCertificateError("SSL 私钥权限过于宽松,请限制为仅 Smail 运行用户可读取")
|
||||
case stderrors.Is(err, config.ErrInvalidSSLMaterial), stderrors.Is(err, config.ErrUnsafeSSLFile):
|
||||
return newUserCertificateError("SSL 证书或私钥文件无效")
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (u *MyUser) GetEmail() string {
|
||||
return u.Email
|
||||
}
|
||||
func (u MyUser) GetRegistration() *registration.Resource {
|
||||
return u.Registration
|
||||
}
|
||||
func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
|
||||
return u.key
|
||||
}
|
||||
|
||||
func GetSSL() (string, error) {
|
||||
cfg, err := config.ReadConfig()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err)
|
||||
}
|
||||
if cfg.SSLType == "" {
|
||||
return config.SSLTypeAutoHTTP, nil
|
||||
}
|
||||
|
||||
return cfg.SSLType, nil
|
||||
}
|
||||
|
||||
func SetSSL(sslType, priKey, crtKey string) error {
|
||||
cfg, err := config.ReadConfig()
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
if sslType == config.SSLTypeAutoHTTP || sslType == config.SSLTypeUser || sslType == config.SSLTypeAutoDNS {
|
||||
cfg.SSLType = sslType
|
||||
} else {
|
||||
return errors.New("SSL 类型错误")
|
||||
}
|
||||
|
||||
if cfg.SSLType != config.SSLTypeUser {
|
||||
clearLegacySSLPaths(cfg)
|
||||
cfg.SSL = config.SSLConfig{
|
||||
Mode: config.ManagedSSLModeDefault,
|
||||
DefaultDirectory: "config/ssl",
|
||||
}
|
||||
}
|
||||
if cfg.SSLType == config.SSLTypeUser {
|
||||
privatePath, publicPath, err := validateUserCertificatePaths(priKey, crtKey)
|
||||
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.ImportManagedSSL(config.ManagedSSLModeUpload, privatePEM, publicPEM, nil, sslDomains(cfg))
|
||||
if err != nil {
|
||||
return normalizeUserCertificateImportError(err)
|
||||
}
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
// 手动设置证书的情况下后台地址默认不启用https
|
||||
cfg.HttpsEnabled = 1
|
||||
}
|
||||
|
||||
err = config.WriteConfig(cfg)
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// clearLegacySSLPaths 只清理新受控模式不再使用的旧聚合路径字段。
|
||||
func clearLegacySSLPaths(cfg *config.Config) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
cfg.SSLPrivateKeyPath = ""
|
||||
cfg.SSLPublicKeyPath = ""
|
||||
}
|
||||
|
||||
// applyManagedSSLReference 将证书切换结果写入内部引用,不持久化服务器路径。
|
||||
func applyManagedSSLReference(cfg *config.Config, reference config.ManagedSSLReference) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
clearLegacySSLPaths(cfg)
|
||||
cfg.SSL = config.SSLConfig{
|
||||
Mode: reference.Mode,
|
||||
DefaultDirectory: "config/ssl",
|
||||
CertificateRef: reference.CertificateRef,
|
||||
PrivateKeyRef: reference.PrivateKeyRef,
|
||||
}
|
||||
if reference.Mode == config.ManagedSSLModeUpload {
|
||||
cfg.SSL.CustomDirectory = "config/ssl/managed/upload"
|
||||
}
|
||||
}
|
||||
|
||||
func isAbsoluteUserCertificatePath(value string) bool {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
if filepath.IsAbs(value) {
|
||||
return true
|
||||
}
|
||||
volume := filepath.VolumeName(value)
|
||||
return volume != "" || strings.HasPrefix(value, `\\`) || strings.HasPrefix(value, "//")
|
||||
}
|
||||
|
||||
func validateUserCertificatePaths(privatePath, publicPath string) (string, string, error) {
|
||||
rootPath, err := filepath.Abs(filepath.Clean(config.ROOT_PATH))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
resolve := func(value string) (string, []byte, error) {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return "", nil, newUserCertificateError("请填写 SSL 证书和私钥路径")
|
||||
}
|
||||
path := strings.TrimSpace(value)
|
||||
if isAbsoluteUserCertificatePath(path) {
|
||||
if filepath.VolumeName(path) != "" && !filepath.IsAbs(path) {
|
||||
return "", nil, newUserCertificateError("SSL 路径必须是完整的绝对路径")
|
||||
}
|
||||
} else {
|
||||
path = filepath.Join(rootPath, path)
|
||||
}
|
||||
path, err = filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return "", nil, newUserCertificateError("SSL 文件不存在或无权读取")
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > 1<<20 {
|
||||
return "", nil, newUserCertificateError("SSL 文件无效或大小超过限制")
|
||||
}
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil || len(content) == 0 || len(content) > 1<<20 {
|
||||
return "", nil, newUserCertificateError("SSL 文件读取失败或内容无效")
|
||||
}
|
||||
return path, content, nil
|
||||
}
|
||||
|
||||
privatePath, privatePEM, err := resolve(privatePath)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
publicPath, publicPEM, err := resolve(publicPath)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
keyPair, err := tls.X509KeyPair(publicPEM, privatePEM)
|
||||
if err != nil || len(keyPair.Certificate) == 0 {
|
||||
return "", "", newUserCertificateError("SSL 证书与私钥不匹配")
|
||||
}
|
||||
certificate, err := x509.ParseCertificate(keyPair.Certificate[0])
|
||||
if err != nil || time.Now().Before(certificate.NotBefore) || !time.Now().Before(certificate.NotAfter) {
|
||||
return "", "", newUserCertificateError("SSL 证书无效、尚未生效或已经过期")
|
||||
}
|
||||
switch publicKey := certificate.PublicKey.(type) {
|
||||
case *rsa.PublicKey:
|
||||
if publicKey.N.BitLen() < 2048 {
|
||||
return "", "", newUserCertificateError("SSL 证书密钥强度不能低于 2048 位")
|
||||
}
|
||||
case *ecdsa.PublicKey:
|
||||
if publicKey.Curve == nil || publicKey.Curve.Params().BitSize < 256 {
|
||||
return "", "", newUserCertificateError("SSL 证书密钥强度不能低于 256 位 ECDSA")
|
||||
}
|
||||
default:
|
||||
return "", "", newUserCertificateError("不支持当前 SSL 证书密钥类型")
|
||||
}
|
||||
privateInfo, err := os.Stat(privatePath)
|
||||
if err != nil {
|
||||
return "", "", newUserCertificateError("SSL 私钥不存在或无权读取")
|
||||
}
|
||||
if runtime.GOOS != "windows" && privateInfo.Mode().Perm()&0007 != 0 {
|
||||
return "", "", newUserCertificateError("SSL 私钥不能允许其他用户读取或写入")
|
||||
}
|
||||
return privatePath, publicPath, nil
|
||||
}
|
||||
|
||||
func writeCertificateFiles(cfg *config.Config, privateKey, certificate, issuer []byte) error {
|
||||
if cfg == nil {
|
||||
return errors.New("SSL 配置不能为空")
|
||||
}
|
||||
reference, err := config.ImportManagedSSL(config.ManagedSSLModeDefault, privateKey, certificate, issuer, certificateDomains(cfg))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
if err := config.WriteConfig(cfg); err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sslDomains(cfg *config.Config) []string {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
domains := make([]string, 0, len(cfg.Domains)*3+1)
|
||||
appendDomain := func(domain string) {
|
||||
domain = strings.TrimSpace(domain)
|
||||
if domain == "" {
|
||||
return
|
||||
}
|
||||
if _, exists := seen[domain]; exists {
|
||||
return
|
||||
}
|
||||
seen[domain] = struct{}{}
|
||||
domains = append(domains, domain)
|
||||
}
|
||||
appendDomain(cfg.WebDomain)
|
||||
appendDomain(cfg.Domain)
|
||||
for _, domain := range cfg.Domains {
|
||||
appendDomain(domain)
|
||||
appendDomain("smtp." + domain)
|
||||
appendDomain("pop." + domain)
|
||||
appendDomain("imap." + domain)
|
||||
}
|
||||
return domains
|
||||
}
|
||||
func wildcardCertificateDomains(cfg *config.Config) []string {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
domain := strings.TrimSpace(cfg.Domain)
|
||||
domain = strings.TrimSuffix(domain, ".")
|
||||
domain = strings.TrimPrefix(domain, "*.")
|
||||
if domain == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
return []string{"*." + domain}
|
||||
}
|
||||
|
||||
func certificateDomains(cfg *config.Config) []string {
|
||||
if cfg != nil && cfg.SSLType == config.SSLTypeAutoDNS {
|
||||
return wildcardCertificateDomains(cfg)
|
||||
}
|
||||
return sslDomains(cfg)
|
||||
}
|
||||
|
||||
func renewCertificate(privateKey *ecdsa.PrivateKey, cfg *config.Config) error {
|
||||
|
||||
myUser := MyUser{
|
||||
Email: "SSLMaster@" + cfg.Domain,
|
||||
key: privateKey,
|
||||
}
|
||||
|
||||
conf := lego.NewConfig(&myUser)
|
||||
conf.UserAgent = "Smail"
|
||||
conf.Certificate.KeyType = certcrypto.RSA2048
|
||||
|
||||
// A client facilitates communication with the CA server.
|
||||
client, err := lego.NewClient(conf)
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
if cfg.SSLType == config.SSLTypeAutoHTTP {
|
||||
err = client.Challenge.SetHTTP01Provider(GetHttpChallengeInstance())
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
} else if cfg.SSLType == config.SSLTypeAutoDNS {
|
||||
err = client.Challenge.SetDNS01Provider(GetDnsChallengeInstance(), dns01.AddDNSTimeout(60*time.Minute))
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
log.Errorf("Please Set DNS Record/请将以下内容添加到DNS记录中:\n")
|
||||
for _, item := range GetDnsChallengeInstance().GetDNSSettings(nil) {
|
||||
log.Errorf("Type:%s\tHost:%s\tValue generated\n", item.Type, item.Host)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var reg *registration.Resource
|
||||
|
||||
reg, err = client.Registration.ResolveAccountByKey()
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
myUser.Registration = reg
|
||||
|
||||
domains := certificateDomains(cfg)
|
||||
|
||||
request := certificate.ObtainRequest{
|
||||
Domains: domains,
|
||||
Bundle: true,
|
||||
}
|
||||
|
||||
log.Infof("wait ssl renew")
|
||||
certificates, err := client.Certificate.Obtain(request)
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
if err = writeCertificateFiles(cfg, certificates.PrivateKey, certificates.Certificate, certificates.IssuerCertificate); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateCertificate(privateKey *ecdsa.PrivateKey, cfg *config.Config, newAccount bool) error {
|
||||
|
||||
myUser := MyUser{
|
||||
Email: "i@" + cfg.Domain,
|
||||
key: privateKey,
|
||||
}
|
||||
|
||||
conf := lego.NewConfig(&myUser)
|
||||
conf.UserAgent = "Smail"
|
||||
conf.Certificate.KeyType = certcrypto.RSA2048
|
||||
|
||||
// A client facilitates communication with the CA server.
|
||||
client, err := lego.NewClient(conf)
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
if cfg.SSLType == config.SSLTypeAutoHTTP {
|
||||
err = client.Challenge.SetHTTP01Provider(GetHttpChallengeInstance())
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
} else if cfg.SSLType == config.SSLTypeAutoDNS {
|
||||
err = client.Challenge.SetDNS01Provider(GetDnsChallengeInstance(), dns01.AddDNSTimeout(60*time.Minute))
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
}
|
||||
|
||||
var reg *registration.Resource
|
||||
|
||||
if newAccount {
|
||||
reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
} else {
|
||||
reg, err = client.Registration.ResolveAccountByKey()
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
}
|
||||
|
||||
myUser.Registration = reg
|
||||
|
||||
domains := certificateDomains(cfg)
|
||||
|
||||
request := certificate.ObtainRequest{
|
||||
Domains: domains,
|
||||
Bundle: true,
|
||||
}
|
||||
|
||||
as := async.New(nil)
|
||||
|
||||
as.Process(func(params any) {
|
||||
log.Infof("wait ssl")
|
||||
certificates, err := client.Certificate.Obtain(request)
|
||||
if err != nil {
|
||||
log.WithError(err).Error("certificate issuance failed")
|
||||
return
|
||||
}
|
||||
log.Infof("证书校验通过!")
|
||||
if err := writeCertificateFiles(cfg, certificates.PrivateKey, certificates.Certificate, certificates.IssuerCertificate); err != nil {
|
||||
log.WithError(err).Error("certificate storage failed")
|
||||
return
|
||||
}
|
||||
|
||||
if err := setup.Finish(); err != nil {
|
||||
log.WithError(err).Error("finish setup after certificate issuance failed")
|
||||
return
|
||||
}
|
||||
|
||||
}, nil)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenSSL(update bool) error {
|
||||
|
||||
cfg, err := config.ReadConfig()
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
if !update {
|
||||
privatePath, publicPath, pathErr := config.ResolveRuntimeSSLPaths(cfg)
|
||||
privateFile, errpi := os.ReadFile(privatePath)
|
||||
public, errpu := os.ReadFile(publicPath)
|
||||
if pathErr != nil {
|
||||
errpi = pathErr
|
||||
errpu = pathErr
|
||||
}
|
||||
// 当前存在证书数据,就不生成了
|
||||
if errpi == nil && errpu == nil && len(privateFile) > 0 && len(public) > 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
privateKey, newAccount, err := config.ReadPrivateKey()
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
|
||||
if !update {
|
||||
return generateCertificate(privateKey, cfg, newAccount)
|
||||
}
|
||||
|
||||
return renewCertificate(privateKey, cfg)
|
||||
}
|
||||
|
||||
// CheckSSLCrtInfo 返回证书过期剩余天数
|
||||
func CheckSSLCrtInfo() (int, time.Time, bool, error) {
|
||||
|
||||
cfg, err := config.ReadConfig()
|
||||
if err != nil {
|
||||
return -1, time.Now(), true, errors.Wrap(err)
|
||||
}
|
||||
// load cert and key by tls.LoadX509KeyPair
|
||||
tlsCert, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
if err != nil {
|
||||
return -1, time.Now(), true, errors.Wrap(err)
|
||||
}
|
||||
|
||||
cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
|
||||
|
||||
if err != nil {
|
||||
return -1, time.Now(), true, errors.Wrap(err)
|
||||
}
|
||||
|
||||
nameMatchFail := true
|
||||
for _, name := range cert.DNSNames {
|
||||
if strings.Contains(name, "imap") {
|
||||
nameMatchFail = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 检查过期时间
|
||||
hours := cert.NotAfter.Sub(time.Now()).Hours()
|
||||
|
||||
if hours <= 0 {
|
||||
return -1, time.Now(), nameMatchFail, errors.New("Certificate has expired")
|
||||
}
|
||||
|
||||
return cast.ToInt(hours / 24), cert.NotAfter, nameMatchFail, nil
|
||||
}
|
||||
|
||||
func Update(needRestart bool) {
|
||||
cfg := config.CurrentConfig()
|
||||
if cfg != nil && cfg.IsSetupReady() && (cfg.SSLType == config.SSLTypeAutoHTTP || cfg.SSLType == config.SSLTypeAutoDNS) {
|
||||
days, _, nameMatchFail, err := CheckSSLCrtInfo()
|
||||
|
||||
if days < 30 || err != nil || nameMatchFail {
|
||||
if err != nil {
|
||||
log.Errorf("SSL Check Error, Update SSL Certificate. Error Info :%+v", err)
|
||||
} else {
|
||||
log.Infof("SSL certificate remaining time is only %d days, renew SSL certificate.", days)
|
||||
}
|
||||
err = GenSSL(true)
|
||||
if err != nil {
|
||||
log.Errorf("SSL Update Error! %+v", err)
|
||||
return
|
||||
}
|
||||
if needRestart {
|
||||
// 更新完证书,重启服务
|
||||
signal.RestartChan <- true
|
||||
}
|
||||
} else {
|
||||
log.Debugf("SSL Check.")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCheckSSLCrtInfo(t *testing.T) {
|
||||
if err := config.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, got1, match, err := CheckSSLCrtInfo()
|
||||
|
||||
fmt.Println(got, got1, match, err)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/utils/atomicfile"
|
||||
securefile "git.pcux.cn/xuans/Smail/utils/file"
|
||||
)
|
||||
|
||||
func writeCertificateBundle(cfg *config.Config, privateKey, certificate, issuer []byte) error {
|
||||
if cfg == nil {
|
||||
return errors.New("SSL configuration is required")
|
||||
}
|
||||
if len(privateKey) == 0 || len(certificate) == 0 || len(privateKey) > 4<<20 || len(certificate) > 4<<20 || len(issuer) > 4<<20 {
|
||||
return errors.New("invalid SSL certificate data")
|
||||
}
|
||||
if _, err := tls.X509KeyPair(certificate, privateKey); err != nil {
|
||||
return errors.New("SSL certificate and private key do not match")
|
||||
}
|
||||
rootPath, err := filepath.Abs(filepath.Clean(config.ROOT_PATH))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
workspaceRoot, err := os.OpenRoot(rootPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer workspaceRoot.Close()
|
||||
baseRelative := filepath.Join("config", "ssl")
|
||||
if err := ensureSecureRootDirectory(workspaceRoot, baseRelative); err != nil {
|
||||
return err
|
||||
}
|
||||
sslRoot, err := workspaceRoot.OpenRoot(baseRelative)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sslRoot.Close()
|
||||
basePath := filepath.Join(rootPath, baseRelative)
|
||||
|
||||
files := []struct {
|
||||
path string
|
||||
data []byte
|
||||
}{
|
||||
{path: cfg.SSLPrivateKeyPath, data: privateKey},
|
||||
{path: cfg.SSLPublicKeyPath, data: certificate},
|
||||
{path: filepath.Join(filepath.Dir(cfg.SSLPublicKeyPath), "issuerCert.crt"), data: issuer},
|
||||
}
|
||||
seen := make(map[string]struct{}, len(files))
|
||||
for _, item := range files {
|
||||
if strings.TrimSpace(item.path) == "" {
|
||||
return errors.New("SSL file path is empty")
|
||||
}
|
||||
relativePath, err := securefile.ControlledRelativePath(basePath, item.path)
|
||||
if err != nil {
|
||||
return errors.New("SSL file path must stay inside config/ssl")
|
||||
}
|
||||
if _, exists := seen[relativePath]; exists {
|
||||
return errors.New("SSL file paths must be unique")
|
||||
}
|
||||
seen[relativePath] = struct{}{}
|
||||
if err := ensureSecureRootDirectory(sslRoot, filepath.Dir(relativePath)); err != nil {
|
||||
return err
|
||||
}
|
||||
if info, statErr := sslRoot.Lstat(relativePath); statErr == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
|
||||
return errors.New("invalid SSL file")
|
||||
}
|
||||
} else if !os.IsNotExist(statErr) {
|
||||
return statErr
|
||||
}
|
||||
if err := atomicfile.WriteRoot(sslRoot, relativePath, item.data, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureSecureRootDirectory(root *os.Root, name string) error {
|
||||
if name == "." || name == "" {
|
||||
return nil
|
||||
}
|
||||
current := ""
|
||||
for _, part := range strings.Split(filepath.Clean(name), string(filepath.Separator)) {
|
||||
if part == "" || part == "." || part == ".." {
|
||||
return errors.New("invalid secure directory")
|
||||
}
|
||||
current = filepath.Join(current, part)
|
||||
if err := root.Mkdir(current, 0700); err != nil && !os.IsExist(err) {
|
||||
return err
|
||||
}
|
||||
info, err := root.Lstat(current)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
|
||||
return errors.New("invalid secure directory")
|
||||
}
|
||||
if err := root.Chmod(current, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
)
|
||||
|
||||
func TestWriteCertificateBundleUsesRestrictedAtomicStorage(t *testing.T) {
|
||||
privateKey, certificate := readTestCertificatePair(t)
|
||||
oldRoot := config.ROOT_PATH
|
||||
root := t.TempDir()
|
||||
config.ROOT_PATH = root + string(os.PathSeparator)
|
||||
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
|
||||
basePath := filepath.Join(root, "config", "ssl")
|
||||
cfg := &config.Config{
|
||||
SSLPrivateKeyPath: filepath.Join(basePath, "private.key"),
|
||||
SSLPublicKeyPath: filepath.Join(basePath, "public.crt"),
|
||||
}
|
||||
issuer := []byte("issuer-certificate")
|
||||
if err := writeCertificateBundle(cfg, privateKey, certificate, issuer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writeCertificateBundle(cfg, privateKey, certificate, issuer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for path, expected := range map[string][]byte{
|
||||
cfg.SSLPrivateKeyPath: privateKey,
|
||||
cfg.SSLPublicKeyPath: certificate,
|
||||
filepath.Join(basePath, "issuerCert.crt"): issuer,
|
||||
} {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(data, expected) {
|
||||
t.Fatalf("SSL 文件内容不完整: %s", path)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
info, statErr := os.Stat(path)
|
||||
if statErr != nil {
|
||||
t.Fatal(statErr)
|
||||
}
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Fatalf("SSL 文件权限为 %o,期望 600", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
for _, directory := range []string{filepath.Join(root, "config"), basePath} {
|
||||
info, err := os.Stat(directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0700 {
|
||||
t.Fatalf("SSL 目录权限为 %o,期望 700", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
}
|
||||
entries, err := os.ReadDir(basePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if strings.HasPrefix(entry.Name(), ".private.key-") || strings.HasPrefix(entry.Name(), ".public.crt-") || strings.HasPrefix(entry.Name(), ".issuerCert.crt-") {
|
||||
t.Fatalf("残留 SSL 临时文件: %s", entry.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteCertificateBundleRejectsSymlinkDirectory(t *testing.T) {
|
||||
privateKey, certificate := readTestCertificatePair(t)
|
||||
oldRoot := config.ROOT_PATH
|
||||
root := t.TempDir()
|
||||
config.ROOT_PATH = root + string(os.PathSeparator)
|
||||
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
|
||||
configDirectory := filepath.Join(root, "config")
|
||||
if err := os.Mkdir(configDirectory, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := t.TempDir()
|
||||
basePath := filepath.Join(configDirectory, "ssl")
|
||||
if err := os.Symlink(outside, basePath); err != nil {
|
||||
t.Skipf("当前环境不支持符号链接测试: %v", err)
|
||||
}
|
||||
cfg := &config.Config{
|
||||
SSLPrivateKeyPath: filepath.Join(basePath, "private.key"),
|
||||
SSLPublicKeyPath: filepath.Join(basePath, "public.crt"),
|
||||
}
|
||||
if err := writeCertificateBundle(cfg, privateKey, certificate, nil); err == nil {
|
||||
t.Fatal("SSL 符号链接目录应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteCertificateBundleRejectsSymlinkFile(t *testing.T) {
|
||||
privateKey, certificate := readTestCertificatePair(t)
|
||||
oldRoot := config.ROOT_PATH
|
||||
root := t.TempDir()
|
||||
config.ROOT_PATH = root + string(os.PathSeparator)
|
||||
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
|
||||
basePath := filepath.Join(root, "config", "ssl")
|
||||
if err := os.MkdirAll(basePath, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outsidePath := filepath.Join(t.TempDir(), "outside.key")
|
||||
original := []byte("outside-private-key")
|
||||
if err := os.WriteFile(outsidePath, original, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
privatePath := filepath.Join(basePath, "private.key")
|
||||
if err := os.Symlink(outsidePath, privatePath); err != nil {
|
||||
t.Skipf("当前环境不支持符号链接测试: %v", err)
|
||||
}
|
||||
cfg := &config.Config{
|
||||
SSLPrivateKeyPath: privatePath,
|
||||
SSLPublicKeyPath: filepath.Join(basePath, "public.crt"),
|
||||
}
|
||||
if err := writeCertificateBundle(cfg, privateKey, certificate, nil); err == nil {
|
||||
t.Fatal("SSL 私钥符号链接应被拒绝")
|
||||
}
|
||||
outsideData, err := os.ReadFile(outsidePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(outsideData, original) {
|
||||
t.Fatal("拒绝 SSL 符号链接时不应修改外部文件")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteCertificateBundleRejectsMismatchedPair(t *testing.T) {
|
||||
privateKey, _ := readTestCertificatePair(t)
|
||||
_, otherCertificate := readTestCertificatePair(t)
|
||||
oldRoot := config.ROOT_PATH
|
||||
root := t.TempDir()
|
||||
config.ROOT_PATH = root + string(os.PathSeparator)
|
||||
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
|
||||
basePath := filepath.Join(root, "config", "ssl")
|
||||
cfg := &config.Config{
|
||||
SSLPrivateKeyPath: filepath.Join(basePath, "private.key"),
|
||||
SSLPublicKeyPath: filepath.Join(basePath, "public.crt"),
|
||||
}
|
||||
if err := writeCertificateBundle(cfg, privateKey, otherCertificate, nil); err == nil {
|
||||
t.Fatal("不匹配的证书和私钥应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func readTestCertificatePair(t *testing.T) ([]byte, []byte) {
|
||||
t.Helper()
|
||||
keyPath, certPath := writeTestCertificate(t, t.TempDir(), 2048)
|
||||
privateKey, err := os.ReadFile(keyPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certificate, err := os.ReadFile(certPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return privateKey, certificate
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
)
|
||||
|
||||
func writeTestCertificate(t *testing.T, root string, bits int) (string, string) {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, bits)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "mail.example.com"},
|
||||
DNSNames: []string{"mail.example.com"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
directory := filepath.Join(root, "config", "ssl")
|
||||
if err := os.MkdirAll(directory, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyPath := filepath.Join(directory, "private.key")
|
||||
certPath := filepath.Join(directory, "public.crt")
|
||||
if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return keyPath, certPath
|
||||
}
|
||||
|
||||
func TestIsAbsoluteUserCertificatePathRecognizesWindowsPaths(t *testing.T) {
|
||||
cases := []string{
|
||||
`C:\outside\private.key`,
|
||||
`D:/outside/public.crt`,
|
||||
`\\server\share\private.key`,
|
||||
`//server/share/public.crt`,
|
||||
}
|
||||
for _, value := range cases {
|
||||
if !isAbsoluteUserCertificatePath(value) {
|
||||
t.Errorf("path %q was accepted", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsAbsoluteUserCertificatePathRejectsEmptyAndAcceptsRelative(t *testing.T) {
|
||||
if isAbsoluteUserCertificatePath("") {
|
||||
t.Fatal("empty path must not be treated as absolute")
|
||||
}
|
||||
if isAbsoluteUserCertificatePath(`config/ssl/upload/private.key`) {
|
||||
t.Fatal("controlled relative path must not be treated as absolute")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyManagedSSLReferenceDoesNotPersistLegacyPaths(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
SSLPrivateKeyPath: "config/ssl/private.key",
|
||||
SSLPublicKeyPath: "config/ssl/public.crt",
|
||||
}
|
||||
reference := config.ManagedSSLReference{
|
||||
Mode: config.ManagedSSLModeUpload,
|
||||
CertificateRef: "config/ssl/managed/upload/current/public.crt",
|
||||
PrivateKeyRef: "config/ssl/managed/upload/current/private.key",
|
||||
CertificatePath: `C:\server\config\ssl\managed\upload\current\public.crt`,
|
||||
PrivateKeyPath: `C:\server\config\ssl\managed\upload\current\private.key`,
|
||||
}
|
||||
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
|
||||
if cfg.SSLPrivateKeyPath != "" || cfg.SSLPublicKeyPath != "" {
|
||||
t.Fatal("新受控 SSL 配置不应保留旧聚合路径")
|
||||
}
|
||||
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 != "config/ssl/managed/upload" {
|
||||
t.Fatalf("自定义受控目录写入错误: %s", cfg.SSL.CustomDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeUserCertificateImportError(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
message string
|
||||
}{
|
||||
{name: "certificate mismatch", err: config.ErrSSLCertificateMismatch, message: "SSL 证书与私钥不匹配"},
|
||||
{name: "domain mismatch", err: fmt.Errorf("%w: web.xuan.com", config.ErrSSLCertificateDomain), message: "SSL 证书与已配置域名不匹配,请检查主域名、Web 域名和附加域名"},
|
||||
{name: "certificate expired", err: config.ErrSSLCertificateExpired, message: "SSL 证书无效、尚未生效或已经过期"},
|
||||
{name: "private key permission", err: config.ErrSSLPrivateKeyPermission, message: "SSL 私钥权限过于宽松,请限制为仅 Smail 运行用户可读取"},
|
||||
{name: "invalid material", err: config.ErrInvalidSSLMaterial, message: "SSL 证书或私钥文件无效"},
|
||||
{name: "unsafe file", err: config.ErrUnsafeSSLFile, message: "SSL 证书或私钥文件无效"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
message := UserCertificateErrorMessage(normalizeUserCertificateImportError(test.err))
|
||||
if message != test.message {
|
||||
t.Fatalf("证书错误提示不匹配: got %q, want %q", message, test.message)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
unknown := fmt.Errorf("unknown certificate import error")
|
||||
if normalized := normalizeUserCertificateImportError(unknown); normalized != unknown {
|
||||
t.Fatalf("未知错误不应被替换: %v", normalized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateUserCertificatePaths(t *testing.T) {
|
||||
oldRoot := config.ROOT_PATH
|
||||
root := t.TempDir()
|
||||
config.ROOT_PATH = root + string(os.PathSeparator)
|
||||
t.Cleanup(func() {
|
||||
config.ROOT_PATH = oldRoot
|
||||
})
|
||||
|
||||
keyPath, certPath := writeTestCertificate(t, root, 2048)
|
||||
if _, _, err := validateUserCertificatePaths(keyPath, certPath); err != nil {
|
||||
t.Fatalf("valid certificate was rejected: %v", err)
|
||||
}
|
||||
externalSourceRoot := t.TempDir()
|
||||
externalKey, externalCert := writeTestCertificate(t, externalSourceRoot, 2048)
|
||||
if _, _, err := validateUserCertificatePaths(externalKey, externalCert); err != nil {
|
||||
t.Fatalf("certificate in an arbitrary directory was rejected: %v", err)
|
||||
}
|
||||
relativeKey, err := filepath.Rel(root, externalKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
relativeCert, err := filepath.Rel(root, externalCert)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := validateUserCertificatePaths(relativeKey, relativeCert); err != nil {
|
||||
t.Fatalf("certificate in an arbitrary relative directory was rejected: %v", err)
|
||||
}
|
||||
weakKey, weakCert := writeTestCertificate(t, root, 1024)
|
||||
if _, _, err := validateUserCertificatePaths(weakKey, weakCert); err == nil {
|
||||
t.Fatal("weak certificate was accepted")
|
||||
}
|
||||
invalid := filepath.Join(t.TempDir(), "invalid.key")
|
||||
if err := os.WriteFile(invalid, []byte("invalid"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := validateUserCertificatePaths(invalid, certPath); err == nil {
|
||||
t.Fatal("invalid certificate data was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateUserCertificatePathsAcceptsParentSymlink(t *testing.T) {
|
||||
oldRoot := config.ROOT_PATH
|
||||
root := t.TempDir()
|
||||
config.ROOT_PATH = root + string(os.PathSeparator)
|
||||
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
|
||||
|
||||
sslDirectory := filepath.Join(root, "config", "ssl")
|
||||
if err := os.MkdirAll(sslDirectory, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outsideRoot := t.TempDir()
|
||||
outsideKey, outsideCert := writeTestCertificate(t, outsideRoot, 2048)
|
||||
linkPath := filepath.Join(sslDirectory, "linked")
|
||||
if err := os.Symlink(filepath.Dir(outsideKey), linkPath); err != nil {
|
||||
t.Skipf("symlink creation is unavailable: %v", err)
|
||||
}
|
||||
linkedKey := filepath.Join(linkPath, filepath.Base(outsideKey))
|
||||
linkedCert := filepath.Join(linkPath, filepath.Base(outsideCert))
|
||||
if _, _, err := validateUserCertificatePaths(linkedKey, linkedCert); err != nil {
|
||||
t.Fatalf("certificate paths through a parent symlink were rejected: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package ssl
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
)
|
||||
|
||||
func TestWildcardCertificateDomains(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
config *config.Config
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "configured domain",
|
||||
config: &config.Config{Domain: "xuans.com", WebDomain: "web.xuans.com", Domains: []string{"xuans.com", "other.example"}},
|
||||
want: []string{"*.xuans.com"},
|
||||
},
|
||||
{
|
||||
name: "trimmed wildcard domain",
|
||||
config: &config.Config{Domain: " *.xuans.com. "},
|
||||
want: []string{"*.xuans.com"},
|
||||
},
|
||||
{
|
||||
name: "empty domain",
|
||||
config: &config.Config{},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "nil config",
|
||||
config: nil,
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := wildcardCertificateDomains(test.config)
|
||||
if len(got) != len(test.want) {
|
||||
t.Fatalf("got %d domains, want %d: %v", len(got), len(test.want), got)
|
||||
}
|
||||
for index := range test.want {
|
||||
if got[index] != test.want[index] {
|
||||
t.Fatalf("got domain %q, want %q", got[index], test.want[index])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateDomainsFollowChallengeMode(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Domain: "xuans.com",
|
||||
WebDomain: "web.xuans.com",
|
||||
Domains: []string{"xuans.com"},
|
||||
}
|
||||
|
||||
cfg.SSLType = config.SSLTypeAutoHTTP
|
||||
httpDomains := certificateDomains(cfg)
|
||||
if len(httpDomains) != 5 {
|
||||
t.Fatalf("got %d HTTP domains, want 5: %v", len(httpDomains), httpDomains)
|
||||
}
|
||||
if httpDomains[0] != "web.xuans.com" || httpDomains[1] != "xuans.com" {
|
||||
t.Fatalf("unexpected HTTP domains: %v", httpDomains)
|
||||
}
|
||||
|
||||
cfg.SSLType = config.SSLTypeAutoDNS
|
||||
dnsDomains := certificateDomains(cfg)
|
||||
if len(dnsDomains) != 1 || dnsDomains[0] != "*.xuans.com" {
|
||||
t.Fatalf("unexpected DNS domains: %v", dnsDomains)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSChallengeWildcardProducesSingleRecord(t *testing.T) {
|
||||
challenge := &DNSChallenge{authInfo: map[string]*authInfo{}}
|
||||
if err := challenge.Present("*.xuans.com", "token", "key-auth"); err != nil {
|
||||
t.Fatalf("Present returned an error: %v", err)
|
||||
}
|
||||
|
||||
records := challenge.GetDNSSettings(nil)
|
||||
if len(records) != 1 {
|
||||
t.Fatalf("got %d DNS records, want 1", len(records))
|
||||
}
|
||||
if records[0].Type != "TXT" {
|
||||
t.Fatalf("got record type %q, want TXT", records[0].Type)
|
||||
}
|
||||
if strings.TrimSuffix(records[0].Host, ".") != "_acme-challenge.xuans.com" {
|
||||
t.Fatalf("got record host %q, want _acme-challenge.xuans.com", records[0].Host)
|
||||
}
|
||||
if records[0].Value == "" {
|
||||
t.Fatal("DNS record value must not be empty")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user