config.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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) getCustomCA() []*Certificate {
  54. certs := make([]*Certificate, 0, len(c.Certificate))
  55. for _, certificate := range c.Certificate {
  56. if certificate.Usage == Certificate_AUTHORITY_ISSUE {
  57. certs = append(certs, certificate)
  58. }
  59. }
  60. return certs
  61. }
  62. func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  63. return func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  64. domain := hello.ServerName
  65. certExpired := false
  66. if certificate, found := c.NameToCertificate[domain]; found {
  67. if !isCertificateExpired(certificate) {
  68. return certificate, nil
  69. }
  70. certExpired = true
  71. }
  72. if certExpired {
  73. newCerts := make([]tls.Certificate, 0, len(c.Certificates))
  74. for _, certificate := range c.Certificates {
  75. if !isCertificateExpired(&certificate) {
  76. newCerts = append(newCerts, certificate)
  77. }
  78. }
  79. c.Certificates = newCerts
  80. }
  81. var issuedCertificate *tls.Certificate
  82. // Create a new certificate from existing CA if possible
  83. for _, rawCert := range ca {
  84. if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
  85. newCert, err := issueCertificate(rawCert, domain)
  86. if err != nil {
  87. newError("failed to issue new certificate for ", domain).Base(err).WriteToLog()
  88. continue
  89. }
  90. c.Certificates = append(c.Certificates, *newCert)
  91. issuedCertificate = &c.Certificates[len(c.Certificates)-1]
  92. break
  93. }
  94. }
  95. if issuedCertificate == nil {
  96. return nil, newError("failed to create a new certificate for ", domain)
  97. }
  98. c.BuildNameToCertificate()
  99. return issuedCertificate, nil
  100. }
  101. }
  102. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  103. config := &tls.Config{
  104. ClientSessionCache: globalSessionCache,
  105. RootCAs: c.GetCertPool(),
  106. }
  107. if c == nil {
  108. return config
  109. }
  110. for _, opt := range opts {
  111. opt(config)
  112. }
  113. config.InsecureSkipVerify = c.AllowInsecure
  114. config.Certificates = c.BuildCertificates()
  115. config.BuildNameToCertificate()
  116. caCerts := c.getCustomCA()
  117. if len(caCerts) > 0 {
  118. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  119. }
  120. if len(c.ServerName) > 0 {
  121. config.ServerName = c.ServerName
  122. }
  123. if len(c.NextProtocol) > 0 {
  124. config.NextProtos = c.NextProtocol
  125. }
  126. if len(config.NextProtos) == 0 {
  127. config.NextProtos = []string{"http/1.1"}
  128. }
  129. return config
  130. }
  131. type Option func(*tls.Config)
  132. func WithDestination(dest net.Destination) Option {
  133. return func(config *tls.Config) {
  134. if dest.Address.Family().IsDomain() && len(config.ServerName) == 0 {
  135. config.ServerName = dest.Address.Domain()
  136. }
  137. }
  138. }
  139. func WithNextProto(protocol ...string) Option {
  140. return func(config *tls.Config) {
  141. if len(config.NextProtos) == 0 {
  142. config.NextProtos = protocol
  143. }
  144. }
  145. }
  146. func ConfigFromContext(ctx context.Context) *Config {
  147. securitySettings := internet.SecuritySettingsFromContext(ctx)
  148. if securitySettings == nil {
  149. return nil
  150. }
  151. config, ok := securitySettings.(*Config)
  152. if !ok {
  153. return nil
  154. }
  155. return config
  156. }