| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289 |
- package tls
- import (
- "crypto/tls"
- "crypto/x509"
- "strings"
- "sync"
- "time"
- "github.com/xtls/xray-core/common/net"
- "github.com/xtls/xray-core/common/protocol/tls/cert"
- "github.com/xtls/xray-core/transport/internet"
- )
- var (
- globalSessionCache = tls.NewLRUClientSessionCache(128)
- )
- const exp8357 = "experiment:8357"
- // ParseCertificate converts a cert.Certificate to Certificate.
- func ParseCertificate(c *cert.Certificate) *Certificate {
- if c != nil {
- certPEM, keyPEM := c.ToPEM()
- return &Certificate{
- Certificate: certPEM,
- Key: keyPEM,
- }
- }
- return nil
- }
- func (c *Config) loadSelfCertPool() (*x509.CertPool, error) {
- root := x509.NewCertPool()
- for _, cert := range c.Certificate {
- if !root.AppendCertsFromPEM(cert.Certificate) {
- return nil, newError("failed to append cert").AtWarning()
- }
- }
- return root, nil
- }
- // BuildCertificates builds a list of TLS certificates from proto definition.
- func (c *Config) BuildCertificates() []tls.Certificate {
- certs := make([]tls.Certificate, 0, len(c.Certificate))
- for _, entry := range c.Certificate {
- if entry.Usage != Certificate_ENCIPHERMENT {
- continue
- }
- keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key)
- if err != nil {
- newError("ignoring invalid X509 key pair").Base(err).AtWarning().WriteToLog()
- continue
- }
- certs = append(certs, keyPair)
- }
- return certs
- }
- func isCertificateExpired(c *tls.Certificate) bool {
- if c.Leaf == nil && len(c.Certificate) > 0 {
- if pc, err := x509.ParseCertificate(c.Certificate[0]); err == nil {
- c.Leaf = pc
- }
- }
- // If leaf is not there, the certificate is probably not used yet. We trust user to provide a valid certificate.
- return c.Leaf != nil && c.Leaf.NotAfter.Before(time.Now().Add(-time.Minute))
- }
- func issueCertificate(rawCA *Certificate, domain string) (*tls.Certificate, error) {
- parent, err := cert.ParseCertificate(rawCA.Certificate, rawCA.Key)
- if err != nil {
- return nil, newError("failed to parse raw certificate").Base(err)
- }
- newCert, err := cert.Generate(parent, cert.CommonName(domain), cert.DNSNames(domain))
- if err != nil {
- return nil, newError("failed to generate new certificate for ", domain).Base(err)
- }
- newCertPEM, newKeyPEM := newCert.ToPEM()
- cert, err := tls.X509KeyPair(newCertPEM, newKeyPEM)
- return &cert, err
- }
- func (c *Config) getCustomCA() []*Certificate {
- certs := make([]*Certificate, 0, len(c.Certificate))
- for _, certificate := range c.Certificate {
- if certificate.Usage == Certificate_AUTHORITY_ISSUE {
- certs = append(certs, certificate)
- }
- }
- return certs
- }
- func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
- var access sync.RWMutex
- return func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
- domain := hello.ServerName
- certExpired := false
- access.RLock()
- certificate, found := c.NameToCertificate[domain]
- access.RUnlock()
- if found {
- if !isCertificateExpired(certificate) {
- return certificate, nil
- }
- certExpired = true
- }
- if certExpired {
- newCerts := make([]tls.Certificate, 0, len(c.Certificates))
- access.Lock()
- for _, certificate := range c.Certificates {
- if !isCertificateExpired(&certificate) {
- newCerts = append(newCerts, certificate)
- }
- }
- c.Certificates = newCerts
- access.Unlock()
- }
- var issuedCertificate *tls.Certificate
- // Create a new certificate from existing CA if possible
- for _, rawCert := range ca {
- if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
- newCert, err := issueCertificate(rawCert, domain)
- if err != nil {
- newError("failed to issue new certificate for ", domain).Base(err).WriteToLog()
- continue
- }
- access.Lock()
- c.Certificates = append(c.Certificates, *newCert)
- issuedCertificate = &c.Certificates[len(c.Certificates)-1]
- access.Unlock()
- break
- }
- }
- if issuedCertificate == nil {
- return nil, newError("failed to create a new certificate for ", domain)
- }
- access.Lock()
- c.BuildNameToCertificate()
- access.Unlock()
- return issuedCertificate, nil
- }
- }
- func (c *Config) IsExperiment8357() bool {
- return strings.HasPrefix(c.ServerName, exp8357)
- }
- func (c *Config) parseServerName() string {
- if c.IsExperiment8357() {
- return c.ServerName[len(exp8357):]
- }
- return c.ServerName
- }
- // GetTLSConfig converts this Config into tls.Config.
- func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
- root, err := c.getCertPool()
- if err != nil {
- newError("failed to load system root certificate").AtError().Base(err).WriteToLog()
- }
- if c == nil {
- return &tls.Config{
- ClientSessionCache: globalSessionCache,
- RootCAs: root,
- InsecureSkipVerify: false,
- NextProtos: nil,
- SessionTicketsDisabled: false,
- }
- }
- config := &tls.Config{
- ClientSessionCache: globalSessionCache,
- RootCAs: root,
- InsecureSkipVerify: c.AllowInsecure,
- NextProtos: c.NextProtocol,
- SessionTicketsDisabled: c.DisableSessionResumption,
- }
- for _, opt := range opts {
- opt(config)
- }
- config.Certificates = c.BuildCertificates()
- config.BuildNameToCertificate()
- caCerts := c.getCustomCA()
- if len(caCerts) > 0 {
- config.GetCertificate = getGetCertificateFunc(config, caCerts)
- }
- if sn := c.parseServerName(); len(sn) > 0 {
- config.ServerName = sn
- }
- if len(config.NextProtos) == 0 {
- config.NextProtos = []string{"h2", "http/1.1"}
- }
- switch c.MinVersion {
- case "1.0":
- config.MinVersion = tls.VersionTLS10
- case "1.1":
- config.MinVersion = tls.VersionTLS11
- case "1.2":
- config.MinVersion = tls.VersionTLS12
- case "1.3":
- config.MinVersion = tls.VersionTLS13
- }
- switch c.MaxVersion {
- case "1.0":
- config.MaxVersion = tls.VersionTLS10
- case "1.1":
- config.MaxVersion = tls.VersionTLS11
- case "1.2":
- config.MaxVersion = tls.VersionTLS12
- case "1.3":
- config.MaxVersion = tls.VersionTLS13
- }
- var cipherSuites []uint16
- if len(c.CipherSuites) > 0 {
- cipherSuitesArray := strings.Split(c.CipherSuites, ":")
- if len(cipherSuitesArray) > 0 {
- all := tls.CipherSuites()
- for _, suite := range cipherSuitesArray {
- for _, s := range all {
- if s.Name == suite {
- cipherSuites = append(cipherSuites, s.ID)
- break
- }
- }
- }
- }
- }
- config.CipherSuites = cipherSuites
- config.PreferServerCipherSuites = c.PreferServerCipherSuites
- return config
- }
- // Option for building TLS config.
- type Option func(*tls.Config)
- // WithDestination sets the server name in TLS config.
- func WithDestination(dest net.Destination) Option {
- return func(config *tls.Config) {
- if dest.Address.Family().IsDomain() && config.ServerName == "" {
- config.ServerName = dest.Address.Domain()
- }
- }
- }
- // WithNextProto sets the ALPN values in TLS config.
- func WithNextProto(protocol ...string) Option {
- return func(config *tls.Config) {
- if len(config.NextProtos) == 0 {
- config.NextProtos = protocol
- }
- }
- }
- // ConfigFromStreamSettings fetches Config from stream settings. Nil if not found.
- func ConfigFromStreamSettings(settings *internet.MemoryStreamConfig) *Config {
- if settings == nil {
- return nil
- }
- config, ok := settings.SecuritySettings.(*Config)
- if !ok {
- return nil
- }
- return config
- }
|