config.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. // BuildCertificates builds a list of TLS certificates from proto definition.
  23. func (c *Config) BuildCertificates() []tls.Certificate {
  24. certs := make([]tls.Certificate, 0, len(c.Certificate))
  25. for _, entry := range c.Certificate {
  26. if entry.Usage != Certificate_ENCIPHERMENT {
  27. continue
  28. }
  29. keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key)
  30. if err != nil {
  31. newError("ignoring invalid X509 key pair").Base(err).AtWarning().WriteToLog()
  32. continue
  33. }
  34. certs = append(certs, keyPair)
  35. }
  36. return certs
  37. }
  38. func isCertificateExpired(c *tls.Certificate) bool {
  39. if c.Leaf == nil && len(c.Certificate) > 0 {
  40. if pc, err := x509.ParseCertificate(c.Certificate[0]); err == nil {
  41. c.Leaf = pc
  42. }
  43. }
  44. // If leaf is not there, the certificate is probably not used yet. We trust user to provide a valid certificate.
  45. return c.Leaf != nil && c.Leaf.NotAfter.Before(time.Now().Add(-time.Minute))
  46. }
  47. func issueCertificate(rawCA *Certificate, domain string) (*tls.Certificate, error) {
  48. parent, err := cert.ParseCertificate(rawCA.Certificate, rawCA.Key)
  49. if err != nil {
  50. return nil, newError("failed to parse raw certificate").Base(err)
  51. }
  52. newCert, err := cert.Generate(parent, cert.CommonName(domain), cert.DNSNames(domain))
  53. if err != nil {
  54. return nil, newError("failed to generate new certificate for ", domain).Base(err)
  55. }
  56. newCertPEM, newKeyPEM := newCert.ToPEM()
  57. cert, err := tls.X509KeyPair(newCertPEM, newKeyPEM)
  58. return &cert, err
  59. }
  60. func (c *Config) getCustomCA() []*Certificate {
  61. certs := make([]*Certificate, 0, len(c.Certificate))
  62. for _, certificate := range c.Certificate {
  63. if certificate.Usage == Certificate_AUTHORITY_ISSUE {
  64. certs = append(certs, certificate)
  65. }
  66. }
  67. return certs
  68. }
  69. func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  70. return func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  71. domain := hello.ServerName
  72. certExpired := false
  73. if certificate, found := c.NameToCertificate[domain]; found {
  74. if !isCertificateExpired(certificate) {
  75. return certificate, nil
  76. }
  77. certExpired = true
  78. }
  79. if certExpired {
  80. newCerts := make([]tls.Certificate, 0, len(c.Certificates))
  81. for _, certificate := range c.Certificates {
  82. if !isCertificateExpired(&certificate) {
  83. newCerts = append(newCerts, certificate)
  84. }
  85. }
  86. c.Certificates = newCerts
  87. }
  88. var issuedCertificate *tls.Certificate
  89. // Create a new certificate from existing CA if possible
  90. for _, rawCert := range ca {
  91. if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
  92. newCert, err := issueCertificate(rawCert, domain)
  93. if err != nil {
  94. newError("failed to issue new certificate for ", domain).Base(err).WriteToLog()
  95. continue
  96. }
  97. c.Certificates = append(c.Certificates, *newCert)
  98. issuedCertificate = &c.Certificates[len(c.Certificates)-1]
  99. break
  100. }
  101. }
  102. if issuedCertificate == nil {
  103. return nil, newError("failed to create a new certificate for ", domain)
  104. }
  105. c.BuildNameToCertificate()
  106. return issuedCertificate, nil
  107. }
  108. }
  109. // GetTLSConfig converts this Config into tls.Config.
  110. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  111. config := &tls.Config{
  112. ClientSessionCache: globalSessionCache,
  113. RootCAs: c.getCertPool(),
  114. }
  115. if c == nil {
  116. return config
  117. }
  118. for _, opt := range opts {
  119. opt(config)
  120. }
  121. if c.AllowInsecureCiphers && len(config.CipherSuites) == 0 {
  122. config.CipherSuites = []uint16{
  123. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  124. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  125. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  126. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  127. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  128. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  129. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  130. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  131. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  132. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  133. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  134. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  135. }
  136. }
  137. config.InsecureSkipVerify = c.AllowInsecure
  138. config.Certificates = c.BuildCertificates()
  139. config.BuildNameToCertificate()
  140. caCerts := c.getCustomCA()
  141. if len(caCerts) > 0 {
  142. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  143. }
  144. if len(c.ServerName) > 0 {
  145. config.ServerName = c.ServerName
  146. }
  147. if len(c.NextProtocol) > 0 {
  148. config.NextProtos = c.NextProtocol
  149. }
  150. if len(config.NextProtos) == 0 {
  151. config.NextProtos = []string{"http/1.1"}
  152. }
  153. return config
  154. }
  155. // Option for building TLS config.
  156. type Option func(*tls.Config)
  157. // WithDestination sets the server name in TLS config.
  158. func WithDestination(dest net.Destination) Option {
  159. return func(config *tls.Config) {
  160. if dest.Address.Family().IsDomain() && len(config.ServerName) == 0 {
  161. config.ServerName = dest.Address.Domain()
  162. }
  163. }
  164. }
  165. // WithNextProto sets the ALPN values in TLS config.
  166. func WithNextProto(protocol ...string) Option {
  167. return func(config *tls.Config) {
  168. if len(config.NextProtos) == 0 {
  169. config.NextProtos = protocol
  170. }
  171. }
  172. }
  173. // ConfigFromContext fetches Config from context. Nil if not found.
  174. func ConfigFromContext(ctx context.Context) *Config {
  175. securitySettings := internet.SecuritySettingsFromContext(ctx)
  176. if securitySettings == nil {
  177. return nil
  178. }
  179. config, ok := securitySettings.(*Config)
  180. if !ok {
  181. return nil
  182. }
  183. return config
  184. }