config.go 6.2 KB

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