config.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. 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) GetCertPool() *x509.CertPool {
  22. pool, err := x509.SystemCertPool()
  23. if err != nil {
  24. newError("failed to get system cert pool.").Base(err).WriteToLog()
  25. return nil
  26. }
  27. if pool != nil {
  28. for _, cert := range c.Certificate {
  29. if cert.Usage == Certificate_AUTHORITY_VERIFY {
  30. pool.AppendCertsFromPEM(cert.Certificate)
  31. }
  32. }
  33. }
  34. return pool
  35. }
  36. func (c *Config) BuildCertificates() []tls.Certificate {
  37. certs := make([]tls.Certificate, 0, len(c.Certificate))
  38. for _, entry := range c.Certificate {
  39. if entry.Usage != Certificate_ENCIPHERMENT {
  40. continue
  41. }
  42. keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key)
  43. if err != nil {
  44. newError("ignoring invalid X509 key pair").Base(err).AtWarning().WriteToLog()
  45. continue
  46. }
  47. certs = append(certs, keyPair)
  48. }
  49. return certs
  50. }
  51. func isCertificateExpired(c *tls.Certificate) bool {
  52. // If leaf is not there, the certificate is probably not used yet. We trust user to provide a valid certificate.
  53. return c.Leaf != nil && c.Leaf.NotAfter.After(time.Now().Add(-time.Minute))
  54. }
  55. func issueCertificate(rawCA *Certificate, domain string) (*tls.Certificate, error) {
  56. parent, err := cert.ParseCertificate(rawCA.Certificate, rawCA.Key)
  57. if err != nil {
  58. return nil, newError("failed to parse raw certificate").Base(err)
  59. }
  60. newCert, err := cert.Generate(parent, cert.CommonName(domain), cert.DNSNames(domain))
  61. if err != nil {
  62. return nil, newError("failed to generate new certificate for ", domain).Base(err)
  63. }
  64. newCertPEM, newKeyPEM := newCert.ToPEM()
  65. cert, err := tls.X509KeyPair(newCertPEM, newKeyPEM)
  66. return &cert, err
  67. }
  68. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  69. config := &tls.Config{
  70. ClientSessionCache: globalSessionCache,
  71. RootCAs: c.GetCertPool(),
  72. }
  73. if c == nil {
  74. return config
  75. }
  76. for _, opt := range opts {
  77. opt(config)
  78. }
  79. config.InsecureSkipVerify = c.AllowInsecure
  80. config.Certificates = c.BuildCertificates()
  81. config.BuildNameToCertificate()
  82. config.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  83. domain := hello.ServerName
  84. certExpired := false
  85. if certificate, found := config.NameToCertificate[domain]; found {
  86. if !isCertificateExpired(certificate) {
  87. return certificate, nil
  88. }
  89. certExpired = true
  90. }
  91. if certExpired {
  92. newCerts := make([]tls.Certificate, 0, len(config.Certificates))
  93. for _, certificate := range config.Certificates {
  94. if !isCertificateExpired(&certificate) {
  95. newCerts = append(newCerts, certificate)
  96. }
  97. }
  98. config.Certificates = newCerts
  99. }
  100. var issuedCertificate *tls.Certificate
  101. // Create a new certificate from existing CA if possible
  102. for _, rawCert := range c.Certificate {
  103. if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
  104. newCert, err := issueCertificate(rawCert, domain)
  105. if err != nil {
  106. newError("failed to issue new certificate for ", domain).Base(err).WriteToLog()
  107. continue
  108. }
  109. config.Certificates = append(config.Certificates, *newCert)
  110. issuedCertificate = &config.Certificates[len(config.Certificates)-1]
  111. break
  112. }
  113. }
  114. if issuedCertificate == nil {
  115. return nil, newError("failed to create a new certificate for ", domain)
  116. }
  117. config.BuildNameToCertificate()
  118. return issuedCertificate, nil
  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. }