config.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "time"
  7. "v2ray.com/core/common/net"
  8. "v2ray.com/core/common/protocol/tls/cert"
  9. "v2ray.com/core/transport/internet"
  10. )
  11. var (
  12. globalSessionCache = tls.NewLRUClientSessionCache(128)
  13. )
  14. // ParseCertificate converts a cert.Certificate to Certificate.
  15. func ParseCertificate(c *cert.Certificate) *Certificate {
  16. certPEM, keyPEM := c.ToPEM()
  17. return &Certificate{
  18. Certificate: certPEM,
  19. Key: keyPEM,
  20. }
  21. }
  22. func (c *Config) GetCertPool() *x509.CertPool {
  23. pool, err := x509.SystemCertPool()
  24. if err != nil {
  25. newError("failed to get system cert pool.").Base(err).WriteToLog()
  26. return nil
  27. }
  28. if pool != nil {
  29. for _, cert := range c.Certificate {
  30. if cert.Usage == Certificate_AUTHORITY_VERIFY {
  31. pool.AppendCertsFromPEM(cert.Certificate)
  32. }
  33. }
  34. }
  35. return pool
  36. }
  37. func (c *Config) BuildCertificates() []tls.Certificate {
  38. certs := make([]tls.Certificate, 0, len(c.Certificate))
  39. for _, entry := range c.Certificate {
  40. if entry.Usage != Certificate_ENCIPHERMENT {
  41. continue
  42. }
  43. keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key)
  44. if err != nil {
  45. newError("ignoring invalid X509 key pair").Base(err).AtWarning().WriteToLog()
  46. continue
  47. }
  48. certs = append(certs, keyPair)
  49. }
  50. return certs
  51. }
  52. func isCertificateExpired(c *tls.Certificate) bool {
  53. // If leaf is not there, the certificate is probably not used yet. We trust user to provide a valid certificate.
  54. return c.Leaf != nil && c.Leaf.NotAfter.After(time.Now().Add(-time.Minute))
  55. }
  56. func issueCertificate(rawCA *Certificate, domain string) (*tls.Certificate, error) {
  57. parent, err := cert.ParseCertificate(rawCA.Certificate, rawCA.Key)
  58. if err != nil {
  59. return nil, newError("failed to parse raw certificate").Base(err)
  60. }
  61. newCert, err := cert.Generate(parent, cert.CommonName(domain), cert.DNSNames(domain))
  62. if err != nil {
  63. return nil, newError("failed to generate new certificate for ", domain).Base(err)
  64. }
  65. newCertPEM, newKeyPEM := newCert.ToPEM()
  66. cert, err := tls.X509KeyPair(newCertPEM, newKeyPEM)
  67. return &cert, err
  68. }
  69. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  70. config := &tls.Config{
  71. ClientSessionCache: globalSessionCache,
  72. RootCAs: c.GetCertPool(),
  73. }
  74. if c == nil {
  75. return config
  76. }
  77. for _, opt := range opts {
  78. opt(config)
  79. }
  80. config.InsecureSkipVerify = c.AllowInsecure
  81. config.Certificates = c.BuildCertificates()
  82. config.BuildNameToCertificate()
  83. config.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  84. domain := hello.ServerName
  85. certExpired := false
  86. if certificate, found := config.NameToCertificate[domain]; found {
  87. if !isCertificateExpired(certificate) {
  88. return certificate, nil
  89. }
  90. certExpired = true
  91. }
  92. if certExpired {
  93. newCerts := make([]tls.Certificate, 0, len(config.Certificates))
  94. for _, certificate := range config.Certificates {
  95. if !isCertificateExpired(&certificate) {
  96. newCerts = append(newCerts, certificate)
  97. }
  98. }
  99. config.Certificates = newCerts
  100. }
  101. var issuedCertificate *tls.Certificate
  102. // Create a new certificate from existing CA if possible
  103. for _, rawCert := range c.Certificate {
  104. if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
  105. newCert, err := issueCertificate(rawCert, domain)
  106. if err != nil {
  107. newError("failed to issue new certificate for ", domain).Base(err).WriteToLog()
  108. continue
  109. }
  110. config.Certificates = append(config.Certificates, *newCert)
  111. issuedCertificate = &config.Certificates[len(config.Certificates)-1]
  112. break
  113. }
  114. }
  115. if issuedCertificate == nil {
  116. return nil, newError("failed to create a new certificate for ", domain)
  117. }
  118. config.BuildNameToCertificate()
  119. return issuedCertificate, nil
  120. }
  121. if len(c.ServerName) > 0 {
  122. config.ServerName = c.ServerName
  123. }
  124. if len(c.NextProtocol) > 0 {
  125. config.NextProtos = c.NextProtocol
  126. }
  127. if len(config.NextProtos) == 0 {
  128. config.NextProtos = []string{"http/1.1"}
  129. }
  130. return config
  131. }
  132. type Option func(*tls.Config)
  133. func WithDestination(dest net.Destination) Option {
  134. return func(config *tls.Config) {
  135. if dest.Address.Family().IsDomain() && len(config.ServerName) == 0 {
  136. config.ServerName = dest.Address.Domain()
  137. }
  138. }
  139. }
  140. func WithNextProto(protocol ...string) Option {
  141. return func(config *tls.Config) {
  142. if len(config.NextProtos) == 0 {
  143. config.NextProtos = protocol
  144. }
  145. }
  146. }
  147. func ConfigFromContext(ctx context.Context) *Config {
  148. securitySettings := internet.SecuritySettingsFromContext(ctx)
  149. if securitySettings == nil {
  150. return nil
  151. }
  152. config, ok := securitySettings.(*Config)
  153. if !ok {
  154. return nil
  155. }
  156. return config
  157. }