config.go 6.0 KB

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