config.go 4.4 KB

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