Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

Configuration changes add validation

lotka5afc0dd739a
diff --git a/core/api/settings/v1/settings.go b/core/api/settings/v1/settings.go
index 2c83b992..c820fda3 100644
--- a/core/api/settings/v1/settings.go
+++ b/core/api/settings/v1/settings.go
@@ -21,6 +21,7 @@ type SSLConfig struct {
IssuerCommonName string `json:"issuer_common_name" dc:"issuer common name"`
SubjectCommonName string `json:"subject_common_name" dc:"subject common name"`
Version int `json:"version" dc:"version"`
+ Status bool `json:"status" dc:"ssl certificate status"`
}
// SystemConfig
diff --git a/core/internal/controller/settings/settings.go b/core/internal/controller/settings/settings.go
index b561da4b..4fae6a1e 100644
--- a/core/internal/controller/settings/settings.go
+++ b/core/internal/controller/settings/settings.go
@@ -11,7 +11,6 @@ import (
"crypto/x509"
"encoding/pem"
"fmt"
- "github.com/gogf/gf/v2/errors/gerror"
"os"
"path/filepath"
"strconv"
@@ -56,35 +55,56 @@ func loadEnvFile() (map[string]string, error) {
// loadSSLInfo
func loadSSLInfo() (*v1.SSLConfig, error) {
-
certPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem"))
keyPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "key.pem"))
if _, err := os.Stat(certPath); os.IsNotExist(err) {
- return nil, gerror.Newf("certificate file %s does not exist", certPath)
+ return &v1.SSLConfig{Status: false}, nil
}
if _, err := os.Stat(keyPath); os.IsNotExist(err) {
- return nil, gerror.Newf("private key file %s does not exist", keyPath)
+ return &v1.SSLConfig{Status: false}, nil
}
certData, err := os.ReadFile(certPath)
if err != nil {
- return nil, gerror.Wrapf(err, "failed to read certificate file %s", certPath)
+ return &v1.SSLConfig{Status: false}, nil
}
keyData, err := os.ReadFile(keyPath)
if err != nil {
- return nil, gerror.Wrapf(err, "failed to read private key file %s", keyPath)
+ return &v1.SSLConfig{Status: false}, nil
}
block, _ := pem.Decode(certData)
if block == nil {
- return nil, gerror.New("failed to decode PEM block containing certificate")
+ return &v1.SSLConfig{Status: false}, nil
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
- return nil, gerror.Wrap(err, "failed to parse certificate")
+ return &v1.SSLConfig{Status: false}, nil
+ }
+
+ // 检查证书是否过期
+ now := time.Now()
+ if now.Before(cert.NotBefore) || now.After(cert.NotAfter) {
+ return &v1.SSLConfig{
+ CertPath: certPath,
+ KeyPath: keyPath,
+ CertData: string(certData),
+ KeyData: string(keyData),
+ ValidUntil: cert.NotAfter.Format(time.RFC3339),
+ ValidFrom: cert.NotBefore.Format(time.RFC3339),
+ Issuer: cert.Issuer.String(),
+ Subject: cert.Subject.String(),
+ DNSNames: cert.DNSNames,
+ SerialNumber: cert.SerialNumber.String(),
+ IsCA: cert.IsCA,
+ IssuerCommonName: cert.Issuer.CommonName,
+ SubjectCommonName: cert.Subject.CommonName,
+ Version: cert.Version,
+ Status: false,
+ }, nil
}
// 返回SSL配置
@@ -99,10 +119,11 @@ func loadSSLInfo() (*v1.SSLConfig, error) {
Subject: cert.Subject.String(),
DNSNames: cert.DNSNames,
SerialNumber: cert.SerialNumber.String(),
- IsCA: cert.IsCA, // CA Certificate
+ IsCA: cert.IsCA,
IssuerCommonName: cert.Issuer.CommonName,
SubjectCommonName: cert.Subject.CommonName,
Version: cert.Version,
+ Status: true,
}, nil
}
@@ -176,3 +197,66 @@ func parseInt(s string, defaultValue int) int {
}
return defaultValue
}
+
+// validateConfigValue
+func validateConfigValue(key, value string) error {
+ // Basic length check
+ if len(value) > 1024 {
+ return fmt.Errorf("configuration value too long, maximum 1024 characters")
+ }
+
+ switch key {
+ case "ADMIN_USERNAME", "admin_username":
+ // Admin username: allowed letters, numbers, underscores, length 4-32
+ if len(value) < 4 || len(value) > 32 {
+ return fmt.Errorf("admin username length must be between 4-32")
+ }
+ if !public.IsValidUsername(value) {
+ return fmt.Errorf("admin username can only contain letters, numbers and underscores")
+ }
+
+ case "ADMIN_PASSWORD", "admin_password":
+ if len(value) < 4 {
+ return fmt.Errorf("password length must be at least 4 characters")
+ }
+
+ case "BILLIONMAIL_HOSTNAME", "billionmail_hostname":
+ // Hostname: allowed letters, numbers, dots, hyphens
+ if !public.IsValidHostname(value) {
+ return fmt.Errorf("hostname format is incorrect")
+ }
+
+ case "SMTP_PORT", "SMTPS_PORT", "SUBMISSION_PORT", "IMAP_PORT", "IMAPS_PORT", "POP_PORT", "POPS_PORT", "HTTP_PORT", "HTTPS_PORT", "REDIS_PORT",
+ "smtp", "smtps", "submission", "imap", "imaps", "pop", "pops", "http", "https", "redis_port":
+ // Port: 1-65535
+ port := public.ParseInt(value)
+ if port < 1 || port > 65535 {
+ return fmt.Errorf("port must be between 1-65535")
+ }
+
+ case "IPV4_NETWORK", "ipv4_network":
+ // IPv4 network: CIDR format
+ if !public.IsValidCIDR(value) {
+ return fmt.Errorf("IPv4 network format is incorrect, please use CIDR format (e.g. 192.168.1.0/24)")
+ }
+
+ case "TZ", "timezone":
+ // Timezone: check if it is a valid timezone
+ if !public.IsValidTimezone(value) {
+ return fmt.Errorf("invalid timezone")
+ }
+
+ case "FAIL2BAN_INIT", "fail2ban":
+ // fail2ban: only allowed y/n or 1/0
+ if value != "y" && value != "n" && value != "1" && value != "0" {
+ return fmt.Errorf("fail2ban value can only be y/n or 1/0")
+ }
+ }
+
+ // General character check: not allowed dangerous characters
+ if public.ContainsDangerousChars(value) {
+ return fmt.Errorf("configuration value contains illegal characters")
+ }
+
+ return nil
+}
diff --git a/core/internal/controller/settings/settings_v1_set_system_config.go b/core/internal/controller/settings/settings_v1_set_system_config.go
index 45b60594..eeee81f7 100644
--- a/core/internal/controller/settings/settings_v1_set_system_config.go
+++ b/core/internal/controller/settings/settings_v1_set_system_config.go
@@ -15,6 +15,32 @@ import (
func (c *ControllerV1) SetSystemConfig(ctx context.Context, req *v1.SetSystemConfigReq) (res *v1.SetSystemConfigRes, err error) {
res = &v1.SetSystemConfigRes{}
+ // Parameter validation
+ if req.AdminUsername != "" {
+ if err := validateConfigValue("ADMIN_USERNAME", req.AdminUsername); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Parameter validation failed: {}", err)))
+ return res, nil
+ }
+ }
+ if req.AdminPassword != "" {
+ if err := validateConfigValue("ADMIN_PASSWORD", req.AdminPassword); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Parameter validation failed: {}", err)))
+ return res, nil
+ }
+ }
+ if req.SafePath != "" {
+ if err := validateConfigValue("SafePath", req.SafePath); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Parameter validation failed: {}", err)))
+ return res, nil
+ }
+ }
+ if req.Hostname != "" {
+ if err := validateConfigValue("BILLIONMAIL_HOSTNAME", req.Hostname); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Parameter validation failed: {}", err)))
+ return res, nil
+ }
+ }
+
envMap, err := loadEnvFile()
if err != nil {
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read environment variable file: {}", err)))
diff --git a/core/internal/controller/settings/settings_v1_set_system_config_key.go b/core/internal/controller/settings/settings_v1_set_system_config_key.go
index 27911ecf..a42350fd 100644
--- a/core/internal/controller/settings/settings_v1_set_system_config_key.go
+++ b/core/internal/controller/settings/settings_v1_set_system_config_key.go
@@ -13,6 +13,12 @@ import (
func (c *ControllerV1) SetSystemConfigKey(ctx context.Context, req *v1.SetSystemConfigKeyReq) (res *v1.SetSystemConfigKeyRes, err error) {
res = &v1.SetSystemConfigKeyRes{}
+ // Parameter validation
+ if err := validateConfigValue(req.Key, req.Value); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Parameter validation failed: {}", err)))
+ return res, nil
+ }
+
// 1. Read the current .env file content
envMap, err := loadEnvFile()
if err != nil {
diff --git a/core/internal/service/public/validator.go b/core/internal/service/public/validator.go
index da593bf6..49552251 100644
--- a/core/internal/service/public/validator.go
+++ b/core/internal/service/public/validator.go
@@ -6,6 +6,7 @@ import (
"regexp"
"strconv"
"strings"
+ "time"
)
var (
@@ -194,3 +195,89 @@ func FileCheck(s string) bool {
func IsApiPath(s string) bool {
return reMap["api_path"].MatchString(s)
}
+
+// IsValidUsername
+// Rules: 4-32 bit characters, only allowed letters, numbers, underscores
+func IsValidUsername(username string) bool {
+ pattern := `^[a-zA-Z0-9_]{4,32}$`
+ matched, _ := regexp.MatchString(pattern, username)
+ return matched
+}
+
+// IsValidHostname
+// Rules: DNS host name format, allowed letters, numbers, hyphens and dots, but cannot start or end with a hyphen
+func IsValidHostname(hostname string) bool {
+ // Check total length
+ if len(hostname) > 255 {
+ return false
+ }
+
+ // Split into labels for checking
+ labels := strings.Split(hostname, ".")
+ for _, label := range labels {
+ // Each label rule:
+ // 1. Length between 1-63
+ // 2. Only letters, numbers and hyphens
+ // 3. Cannot start or end with a hyphen
+ if len(label) < 1 || len(label) > 63 {
+ return false
+ }
+ if strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
+ return false
+ }
+ pattern := `^[a-zA-Z0-9-]+$`
+ matched, _ := regexp.MatchString(pattern, label)
+ if !matched {
+ return false
+ }
+ }
+ return true
+}
+
+// IsValidCIDR Check if it is a valid CIDR format
+func IsValidCIDR(cidr string) bool {
+ _, _, err := net.ParseCIDR(cidr)
+ return err == nil
+}
+
+// IsValidTimezone Check if it is a valid timezone
+func IsValidTimezone(tz string) bool {
+ _, err := time.LoadLocation(tz)
+ return err == nil
+}
+
+// ContainsDangerousChars Check if it contains dangerous characters
+func ContainsDangerousChars(value string) bool {
+ dangerousChars := []string{
+ ";", "|", "&", "$", "<", ">", "`", "\\",
+ "(", ")", "{", "}", "[", "]", "!", "#",
+ "\x00",
+ }
+
+ for _, char := range dangerousChars {
+ if strings.Contains(value, char) {
+ return true
+ }
+ }
+
+ // Check if it contains control characters (ASCII 0-31, except for common tab, newline, etc.)
+ for _, r := range value {
+ if r < 32 && r != '\t' && r != '\n' && r != '\r' {
+ return true
+ }
+ }
+
+ return false
+}
+
+// ParseInt Safely convert string to integer
+func ParseInt(s string) int {
+ // Remove whitespace
+ s = strings.TrimSpace(s)
+
+ i, err := strconv.Atoi(s)
+ if err != nil {
+ return 0
+ }
+ return i
+}