config.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package tls
  2. import (
  3. "crypto/hmac"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/v2fly/v2ray-core/v5/common/net"
  11. "github.com/v2fly/v2ray-core/v5/common/protocol/tls/cert"
  12. "github.com/v2fly/v2ray-core/v5/transport/internet"
  13. )
  14. var globalSessionCache = tls.NewLRUClientSessionCache(128)
  15. const exp8357 = "experiment:8357"
  16. // ParseCertificate converts a cert.Certificate to Certificate.
  17. func ParseCertificate(c *cert.Certificate) *Certificate {
  18. if c != nil {
  19. certPEM, keyPEM := c.ToPEM()
  20. return &Certificate{
  21. Certificate: certPEM,
  22. Key: keyPEM,
  23. }
  24. }
  25. return nil
  26. }
  27. func (c *Config) loadSelfCertPool(usage Certificate_Usage) (*x509.CertPool, error) {
  28. root := x509.NewCertPool()
  29. for _, cert := range c.Certificate {
  30. if cert.Usage == usage {
  31. if !root.AppendCertsFromPEM(cert.Certificate) {
  32. return nil, newError("failed to append cert").AtWarning()
  33. }
  34. }
  35. }
  36. return root, nil
  37. }
  38. // BuildCertificates builds a list of TLS certificates from proto definition.
  39. func (c *Config) BuildCertificates() []tls.Certificate {
  40. certs := make([]tls.Certificate, 0, len(c.Certificate))
  41. for _, entry := range c.Certificate {
  42. if entry.Usage != Certificate_ENCIPHERMENT {
  43. continue
  44. }
  45. keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key)
  46. if err != nil {
  47. newError("ignoring invalid X509 key pair").Base(err).AtWarning().WriteToLog()
  48. continue
  49. }
  50. certs = append(certs, keyPair)
  51. }
  52. return certs
  53. }
  54. func isCertificateExpired(c *tls.Certificate) bool {
  55. if c.Leaf == nil && len(c.Certificate) > 0 {
  56. if pc, err := x509.ParseCertificate(c.Certificate[0]); err == nil {
  57. c.Leaf = pc
  58. }
  59. }
  60. // If leaf is not there, the certificate is probably not used yet. We trust user to provide a valid certificate.
  61. return c.Leaf != nil && c.Leaf.NotAfter.Before(time.Now().Add(time.Minute*2))
  62. }
  63. func issueCertificate(rawCA *Certificate, domain string) (*tls.Certificate, error) {
  64. parent, err := cert.ParseCertificate(rawCA.Certificate, rawCA.Key)
  65. if err != nil {
  66. return nil, newError("failed to parse raw certificate").Base(err)
  67. }
  68. newCert, err := cert.Generate(parent, cert.CommonName(domain), cert.DNSNames(domain))
  69. if err != nil {
  70. return nil, newError("failed to generate new certificate for ", domain).Base(err)
  71. }
  72. newCertPEM, newKeyPEM := newCert.ToPEM()
  73. cert, err := tls.X509KeyPair(newCertPEM, newKeyPEM)
  74. return &cert, err
  75. }
  76. func (c *Config) getCustomCA() []*Certificate {
  77. certs := make([]*Certificate, 0, len(c.Certificate))
  78. for _, certificate := range c.Certificate {
  79. if certificate.Usage == Certificate_AUTHORITY_ISSUE {
  80. certs = append(certs, certificate)
  81. }
  82. }
  83. return certs
  84. }
  85. func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  86. var access sync.RWMutex
  87. return func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  88. domain := hello.ServerName
  89. certExpired := false
  90. access.RLock()
  91. certificate, found := c.NameToCertificate[domain]
  92. access.RUnlock()
  93. if found {
  94. if !isCertificateExpired(certificate) {
  95. return certificate, nil
  96. }
  97. certExpired = true
  98. }
  99. if certExpired {
  100. newCerts := make([]tls.Certificate, 0, len(c.Certificates))
  101. access.Lock()
  102. for _, certificate := range c.Certificates {
  103. cert := certificate
  104. if !isCertificateExpired(&cert) {
  105. newCerts = append(newCerts, cert)
  106. } else if cert.Leaf != nil {
  107. expTime := cert.Leaf.NotAfter.Format(time.RFC3339)
  108. newError("old certificate for ", domain, " (expire on ", expTime, ") discard").AtInfo().WriteToLog()
  109. }
  110. }
  111. c.Certificates = newCerts
  112. access.Unlock()
  113. }
  114. var issuedCertificate *tls.Certificate
  115. // Create a new certificate from existing CA if possible
  116. for _, rawCert := range ca {
  117. if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
  118. newCert, err := issueCertificate(rawCert, domain)
  119. if err != nil {
  120. newError("failed to issue new certificate for ", domain).Base(err).WriteToLog()
  121. continue
  122. }
  123. parsed, err := x509.ParseCertificate(newCert.Certificate[0])
  124. if err == nil {
  125. newCert.Leaf = parsed
  126. expTime := parsed.NotAfter.Format(time.RFC3339)
  127. newError("new certificate for ", domain, " (expire on ", expTime, ") issued").AtInfo().WriteToLog()
  128. } else {
  129. newError("failed to parse new certificate for ", domain).Base(err).WriteToLog()
  130. }
  131. access.Lock()
  132. c.Certificates = append(c.Certificates, *newCert)
  133. issuedCertificate = &c.Certificates[len(c.Certificates)-1]
  134. access.Unlock()
  135. break
  136. }
  137. }
  138. if issuedCertificate == nil {
  139. return nil, newError("failed to create a new certificate for ", domain)
  140. }
  141. access.Lock()
  142. c.BuildNameToCertificate()
  143. access.Unlock()
  144. return issuedCertificate, nil
  145. }
  146. }
  147. func (c *Config) IsExperiment8357() bool {
  148. return strings.HasPrefix(c.ServerName, exp8357)
  149. }
  150. func (c *Config) parseServerName() string {
  151. if c.IsExperiment8357() {
  152. return c.ServerName[len(exp8357):]
  153. }
  154. return c.ServerName
  155. }
  156. func (c *Config) verifyPeerCert(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  157. if c.PinnedPeerCertificateChainSha256 != nil {
  158. hashValue := GenerateCertChainHash(rawCerts)
  159. for _, v := range c.PinnedPeerCertificateChainSha256 {
  160. if hmac.Equal(hashValue, v) {
  161. return nil
  162. }
  163. }
  164. return newError("peer cert is unrecognized: ", base64.StdEncoding.EncodeToString(hashValue))
  165. }
  166. return nil
  167. }
  168. // GetTLSConfig converts this Config into tls.Config.
  169. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  170. root, err := c.getCertPool()
  171. if err != nil {
  172. newError("failed to load system root certificate").AtError().Base(err).WriteToLog()
  173. }
  174. if c == nil {
  175. return &tls.Config{
  176. ClientSessionCache: globalSessionCache,
  177. RootCAs: root,
  178. InsecureSkipVerify: false,
  179. NextProtos: nil,
  180. SessionTicketsDisabled: true,
  181. }
  182. }
  183. clientRoot, err := c.loadSelfCertPool(Certificate_AUTHORITY_VERIFY_CLIENT)
  184. if err != nil {
  185. newError("failed to load client root certificate").AtError().Base(err).WriteToLog()
  186. }
  187. config := &tls.Config{
  188. ClientSessionCache: globalSessionCache,
  189. RootCAs: root,
  190. InsecureSkipVerify: c.AllowInsecure,
  191. NextProtos: c.NextProtocol,
  192. SessionTicketsDisabled: !c.EnableSessionResumption,
  193. VerifyPeerCertificate: c.verifyPeerCert,
  194. ClientCAs: clientRoot,
  195. }
  196. for _, opt := range opts {
  197. opt(config)
  198. }
  199. config.Certificates = c.BuildCertificates()
  200. config.BuildNameToCertificate()
  201. caCerts := c.getCustomCA()
  202. if len(caCerts) > 0 {
  203. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  204. }
  205. if sn := c.parseServerName(); len(sn) > 0 {
  206. config.ServerName = sn
  207. }
  208. if len(config.NextProtos) == 0 {
  209. config.NextProtos = []string{"h2", "http/1.1"}
  210. }
  211. if c.VerifyClientCertificate {
  212. config.ClientAuth = tls.RequireAndVerifyClientCert
  213. }
  214. return config
  215. }
  216. // Option for building TLS config.
  217. type Option func(*tls.Config)
  218. // WithDestination sets the server name in TLS config.
  219. func WithDestination(dest net.Destination) Option {
  220. return func(config *tls.Config) {
  221. if dest.Address.Family().IsDomain() && config.ServerName == "" {
  222. config.ServerName = dest.Address.Domain()
  223. }
  224. }
  225. }
  226. // WithNextProto sets the ALPN values in TLS config.
  227. func WithNextProto(protocol ...string) Option {
  228. return func(config *tls.Config) {
  229. if len(config.NextProtos) == 0 {
  230. config.NextProtos = protocol
  231. }
  232. }
  233. }
  234. // ConfigFromStreamSettings fetches Config from stream settings. Nil if not found.
  235. func ConfigFromStreamSettings(settings *internet.MemoryStreamConfig) *Config {
  236. if settings == nil {
  237. return nil
  238. }
  239. if settings.SecuritySettings == nil {
  240. return nil
  241. }
  242. // Fail close for unknown TLS settings type.
  243. // For TLS Clients, Security Engine should be used, instead of this.
  244. config := settings.SecuritySettings.(*Config)
  245. return config
  246. }