config.go 8.9 KB

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