config.go 6.2 KB

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