config.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. // +build !confonly
  2. package tls
  3. import (
  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. func (c *Config) IsExperiment8357() bool {
  121. return c.ServerName == "experiment:8357"
  122. }
  123. // GetTLSConfig converts this Config into tls.Config.
  124. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  125. config := &tls.Config{
  126. ClientSessionCache: globalSessionCache,
  127. RootCAs: c.getCertPool(),
  128. SessionTicketsDisabled: c.DisableSessionResumption,
  129. }
  130. if c == nil {
  131. return config
  132. }
  133. for _, opt := range opts {
  134. opt(config)
  135. }
  136. if !c.AllowInsecureCiphers && len(config.CipherSuites) == 0 {
  137. config.CipherSuites = []uint16{
  138. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  139. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  140. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  141. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  142. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  143. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  144. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  145. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  146. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  147. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  148. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  149. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  150. }
  151. }
  152. config.InsecureSkipVerify = c.AllowInsecure
  153. config.Certificates = c.BuildCertificates()
  154. config.BuildNameToCertificate()
  155. caCerts := c.getCustomCA()
  156. if len(caCerts) > 0 {
  157. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  158. }
  159. if len(c.ServerName) > 0 && c.ServerName != "experiment:8357" {
  160. config.ServerName = c.ServerName
  161. }
  162. if len(c.NextProtocol) > 0 {
  163. config.NextProtos = c.NextProtocol
  164. }
  165. if len(config.NextProtos) == 0 {
  166. config.NextProtos = []string{"http/1.1"}
  167. }
  168. return config
  169. }
  170. // Option for building TLS config.
  171. type Option func(*tls.Config)
  172. // WithDestination sets the server name in TLS config.
  173. func WithDestination(dest net.Destination) Option {
  174. return func(config *tls.Config) {
  175. if dest.Address.Family().IsDomain() && len(config.ServerName) == 0 {
  176. config.ServerName = dest.Address.Domain()
  177. }
  178. }
  179. }
  180. // WithNextProto sets the ALPN values in TLS config.
  181. func WithNextProto(protocol ...string) Option {
  182. return func(config *tls.Config) {
  183. if len(config.NextProtos) == 0 {
  184. config.NextProtos = protocol
  185. }
  186. }
  187. }
  188. // ConfigFromStreamSettings fetches Config from stream settings. Nil if not found.
  189. func ConfigFromStreamSettings(settings *internet.MemoryStreamConfig) *Config {
  190. if settings == nil {
  191. return nil
  192. }
  193. config, ok := settings.SecuritySettings.(*Config)
  194. if !ok {
  195. return nil
  196. }
  197. return config
  198. }