config.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. InsecureSkipVerify: c.AllowInsecure,
  150. NextProtos: c.NextProtocol,
  151. SessionTicketsDisabled: c.DisableSessionResumption,
  152. }
  153. if c == nil {
  154. return config
  155. }
  156. for _, opt := range opts {
  157. opt(config)
  158. }
  159. config.Certificates = c.BuildCertificates()
  160. config.BuildNameToCertificate()
  161. caCerts := c.getCustomCA()
  162. if len(caCerts) > 0 {
  163. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  164. }
  165. if sn := c.parseServerName(); len(sn) > 0 {
  166. config.ServerName = sn
  167. }
  168. if len(config.NextProtos) == 0 {
  169. config.NextProtos = []string{"h2", "http/1.1"}
  170. }
  171. return config
  172. }
  173. // Option for building TLS config.
  174. type Option func(*tls.Config)
  175. // WithDestination sets the server name in TLS config.
  176. func WithDestination(dest net.Destination) Option {
  177. return func(config *tls.Config) {
  178. if dest.Address.Family().IsDomain() && config.ServerName == "" {
  179. config.ServerName = dest.Address.Domain()
  180. }
  181. }
  182. }
  183. // WithNextProto sets the ALPN values in TLS config.
  184. func WithNextProto(protocol ...string) Option {
  185. return func(config *tls.Config) {
  186. if len(config.NextProtos) == 0 {
  187. config.NextProtos = protocol
  188. }
  189. }
  190. }
  191. // ConfigFromStreamSettings fetches Config from stream settings. Nil if not found.
  192. func ConfigFromStreamSettings(settings *internet.MemoryStreamConfig) *Config {
  193. if settings == nil {
  194. return nil
  195. }
  196. config, ok := settings.SecuritySettings.(*Config)
  197. if !ok {
  198. return nil
  199. }
  200. return config
  201. }