sing-box/common/tls/std_server.go

251 lines
6.3 KiB
Go
Raw Normal View History

2022-09-09 18:45:10 +08:00
package tls
2022-07-25 08:14:09 +08:00
import (
"context"
2022-07-25 08:14:09 +08:00
"crypto/tls"
2022-09-09 18:45:10 +08:00
"net"
2022-07-25 08:14:09 +08:00
"os"
2023-08-29 19:28:26 +08:00
"strings"
2022-07-25 08:14:09 +08:00
"github.com/sagernet/fswatch"
2022-07-30 22:00:04 +08:00
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
2022-07-25 08:14:09 +08:00
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
2022-07-25 08:14:09 +08:00
E "github.com/sagernet/sing/common/exceptions"
2023-08-29 13:43:42 +08:00
"github.com/sagernet/sing/common/ntp"
2022-07-25 08:14:09 +08:00
)
var errInsecureUnused = E.New("tls: insecure unused")
2022-09-09 18:45:10 +08:00
type STDServerConfig struct {
2022-07-30 22:00:04 +08:00
config *tls.Config
logger log.Logger
acmeService adapter.Service
2022-07-30 22:00:04 +08:00
certificate []byte
key []byte
certificatePath string
keyPath string
watcher *fswatch.Watcher
2022-07-30 22:00:04 +08:00
}
func (c *STDServerConfig) ServerName() string {
return c.config.ServerName
}
func (c *STDServerConfig) SetServerName(serverName string) {
c.config.ServerName = serverName
}
func (c *STDServerConfig) NextProtos() []string {
2023-12-24 18:01:12 +08:00
if c.acmeService != nil && len(c.config.NextProtos) > 1 && c.config.NextProtos[0] == ACMETLS1Protocol {
return c.config.NextProtos[1:]
} else {
return c.config.NextProtos
}
}
func (c *STDServerConfig) SetNextProtos(nextProto []string) {
2023-12-24 18:01:12 +08:00
if c.acmeService != nil && len(c.config.NextProtos) > 1 && c.config.NextProtos[0] == ACMETLS1Protocol {
c.config.NextProtos = append(c.config.NextProtos[:1], nextProto...)
} else {
c.config.NextProtos = nextProto
}
}
2022-09-09 18:45:10 +08:00
func (c *STDServerConfig) Config() (*STDConfig, error) {
return c.config, nil
}
func (c *STDServerConfig) Client(conn net.Conn) (Conn, error) {
return tls.Client(conn, c.config), nil
2022-07-30 22:00:04 +08:00
}
func (c *STDServerConfig) Server(conn net.Conn) (Conn, error) {
return tls.Server(conn, c.config), nil
2022-09-09 18:45:10 +08:00
}
func (c *STDServerConfig) Clone() Config {
return &STDServerConfig{
config: c.config.Clone(),
}
}
2022-09-09 18:45:10 +08:00
func (c *STDServerConfig) Start() error {
if c.acmeService != nil {
return c.acmeService.Start()
} else {
if c.certificatePath == "" && c.keyPath == "" {
return nil
}
err := c.startWatcher()
if err != nil {
c.logger.Warn("create fsnotify watcher: ", err)
}
2022-07-30 22:00:04 +08:00
return nil
}
}
2022-09-09 18:45:10 +08:00
func (c *STDServerConfig) startWatcher() error {
var watchPath []string
2022-07-30 22:00:04 +08:00
if c.certificatePath != "" {
watchPath = append(watchPath, c.certificatePath)
2022-07-30 22:00:04 +08:00
}
if c.keyPath != "" {
watchPath = append(watchPath, c.keyPath)
2022-07-30 22:00:04 +08:00
}
watcher, err := fswatch.NewWatcher(fswatch.Options{
Path: watchPath,
Callback: func(path string) {
err := c.certificateUpdated(path)
2022-07-30 22:00:04 +08:00
if err != nil {
c.logger.Error(err)
2022-07-30 22:00:04 +08:00
}
},
})
if err != nil {
return err
2022-07-30 22:00:04 +08:00
}
2024-11-20 11:32:43 +08:00
err = watcher.Start()
if err != nil {
return err
}
c.watcher = watcher
return nil
2022-07-30 22:00:04 +08:00
}
func (c *STDServerConfig) certificateUpdated(path string) error {
if path == c.certificatePath {
2022-07-30 22:00:04 +08:00
certificate, err := os.ReadFile(c.certificatePath)
if err != nil {
return E.Cause(err, "reload certificate from ", c.certificatePath)
}
c.certificate = certificate
} else if path == c.keyPath {
2022-07-30 22:00:04 +08:00
key, err := os.ReadFile(c.keyPath)
if err != nil {
return E.Cause(err, "reload key from ", c.keyPath)
}
c.key = key
}
keyPair, err := tls.X509KeyPair(c.certificate, c.key)
if err != nil {
return E.Cause(err, "reload key pair")
}
c.config.Certificates = []tls.Certificate{keyPair}
c.logger.Info("reloaded TLS certificate")
return nil
}
2022-09-09 18:45:10 +08:00
func (c *STDServerConfig) Close() error {
if c.acmeService != nil {
return c.acmeService.Close()
}
2022-07-30 22:00:04 +08:00
if c.watcher != nil {
return c.watcher.Close()
}
return nil
}
2023-08-29 13:43:42 +08:00
func NewSTDServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
if !options.Enabled {
return nil, nil
}
var tlsConfig *tls.Config
var acmeService adapter.Service
var err error
if options.ACME != nil && len(options.ACME.Domain) > 0 {
//nolint:staticcheck
2023-07-23 14:42:19 +08:00
tlsConfig, acmeService, err = startACME(ctx, common.PtrValueOrDefault(options.ACME))
if err != nil {
return nil, err
}
if options.Insecure {
return nil, errInsecureUnused
}
} else {
tlsConfig = &tls.Config{}
}
2023-08-29 13:43:42 +08:00
tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
if options.ServerName != "" {
tlsConfig.ServerName = options.ServerName
}
if len(options.ALPN) > 0 {
2023-04-11 11:38:53 +08:00
tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...)
}
if options.MinVersion != "" {
minVersion, err := ParseTLSVersion(options.MinVersion)
if err != nil {
return nil, E.Cause(err, "parse min_version")
}
tlsConfig.MinVersion = minVersion
}
if options.MaxVersion != "" {
maxVersion, err := ParseTLSVersion(options.MaxVersion)
if err != nil {
return nil, E.Cause(err, "parse max_version")
}
tlsConfig.MaxVersion = maxVersion
}
if options.CipherSuites != nil {
find:
for _, cipherSuite := range options.CipherSuites {
for _, tlsCipherSuite := range tls.CipherSuites() {
if cipherSuite == tlsCipherSuite.Name {
tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
continue find
}
}
return nil, E.New("unknown cipher_suite: ", cipherSuite)
}
}
var certificate []byte
var key []byte
if acmeService == nil {
2023-08-29 19:28:26 +08:00
if len(options.Certificate) > 0 {
certificate = []byte(strings.Join(options.Certificate, "\n"))
} else if options.CertificatePath != "" {
content, err := os.ReadFile(options.CertificatePath)
if err != nil {
return nil, E.Cause(err, "read certificate")
}
certificate = content
}
2023-08-29 19:28:26 +08:00
if len(options.Key) > 0 {
key = []byte(strings.Join(options.Key, "\n"))
} else if options.KeyPath != "" {
content, err := os.ReadFile(options.KeyPath)
if err != nil {
return nil, E.Cause(err, "read key")
}
key = content
}
if certificate == nil && key == nil && options.Insecure {
tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
2023-10-21 12:00:00 +08:00
return GenerateCertificate(ntp.TimeFuncFromContext(ctx), info.ServerName)
}
} else {
if certificate == nil {
return nil, E.New("missing certificate")
} else if key == nil {
return nil, E.New("missing key")
}
keyPair, err := tls.X509KeyPair(certificate, key)
if err != nil {
return nil, E.Cause(err, "parse x509 key pair")
}
tlsConfig.Certificates = []tls.Certificate{keyPair}
}
}
return &STDServerConfig{
config: tlsConfig,
logger: logger,
acmeService: acmeService,
certificate: certificate,
key: key,
certificatePath: options.CertificatePath,
keyPath: options.KeyPath,
}, nil
}