config.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // +build !confonly
  2. package tls
  3. import (
  4. "crypto/hmac"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/v2fly/v2ray-core/v4/common/net"
  12. "github.com/v2fly/v2ray-core/v4/common/protocol/tls/cert"
  13. "github.com/v2fly/v2ray-core/v4/transport/internet"
  14. )
  15. var globalSessionCache = tls.NewLRUClientSessionCache(128)
  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. func (c *Config) verifyPeerCert(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  145. if c.PinnedPeerCertificateChainSha256 != nil {
  146. hashValue := GenerateCertChainHash(rawCerts)
  147. for _, v := range c.PinnedPeerCertificateChainSha256 {
  148. if hmac.Equal(hashValue, v) {
  149. return nil
  150. }
  151. }
  152. return newError("peer cert is unrecognized: ", base64.StdEncoding.EncodeToString(hashValue))
  153. }
  154. return nil
  155. }
  156. // GetTLSConfig converts this Config into tls.Config.
  157. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  158. root, err := c.getCertPool()
  159. if err != nil {
  160. newError("failed to load system root certificate").AtError().Base(err).WriteToLog()
  161. }
  162. if c == nil {
  163. return &tls.Config{
  164. ClientSessionCache: globalSessionCache,
  165. RootCAs: root,
  166. InsecureSkipVerify: false,
  167. NextProtos: nil,
  168. SessionTicketsDisabled: true,
  169. }
  170. }
  171. config := &tls.Config{
  172. ClientSessionCache: globalSessionCache,
  173. RootCAs: root,
  174. InsecureSkipVerify: c.AllowInsecure,
  175. NextProtos: c.NextProtocol,
  176. SessionTicketsDisabled: !c.EnableSessionResumption,
  177. VerifyPeerCertificate: c.verifyPeerCert,
  178. }
  179. for _, opt := range opts {
  180. opt(config)
  181. }
  182. config.Certificates = c.BuildCertificates()
  183. config.BuildNameToCertificate()
  184. caCerts := c.getCustomCA()
  185. if len(caCerts) > 0 {
  186. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  187. }
  188. if sn := c.parseServerName(); len(sn) > 0 {
  189. config.ServerName = sn
  190. }
  191. if len(config.NextProtos) == 0 {
  192. config.NextProtos = []string{"h2", "http/1.1"}
  193. }
  194. return config
  195. }
  196. // Option for building TLS config.
  197. type Option func(*tls.Config)
  198. // WithDestination sets the server name in TLS config.
  199. func WithDestination(dest net.Destination) Option {
  200. return func(config *tls.Config) {
  201. if dest.Address.Family().IsDomain() && config.ServerName == "" {
  202. config.ServerName = dest.Address.Domain()
  203. }
  204. }
  205. }
  206. // WithNextProto sets the ALPN values in TLS config.
  207. func WithNextProto(protocol ...string) Option {
  208. return func(config *tls.Config) {
  209. if len(config.NextProtos) == 0 {
  210. config.NextProtos = protocol
  211. }
  212. }
  213. }
  214. // ConfigFromStreamSettings fetches Config from stream settings. Nil if not found.
  215. func ConfigFromStreamSettings(settings *internet.MemoryStreamConfig) *Config {
  216. if settings == nil {
  217. return nil
  218. }
  219. config, ok := settings.SecuritySettings.(*Config)
  220. if !ok {
  221. return nil
  222. }
  223. return config
  224. }