config.go 6.7 KB

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