config.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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*2))
  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. } else if cert.Leaf != nil {
  106. expTime := cert.Leaf.NotAfter.Format(time.RFC3339)
  107. newError("old certificate for ", domain, " (expire on ", expTime, ") discard").AtInfo().WriteToLog()
  108. }
  109. }
  110. c.Certificates = newCerts
  111. access.Unlock()
  112. }
  113. var issuedCertificate *tls.Certificate
  114. // Create a new certificate from existing CA if possible
  115. for _, rawCert := range ca {
  116. if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
  117. newCert, err := issueCertificate(rawCert, domain)
  118. if err != nil {
  119. newError("failed to issue new certificate for ", domain).Base(err).WriteToLog()
  120. continue
  121. }
  122. parsed, err := x509.ParseCertificate(newCert.Certificate[0])
  123. if err == nil {
  124. newCert.Leaf = parsed
  125. expTime := parsed.NotAfter.Format(time.RFC3339)
  126. newError("new certificate for ", domain, " (expire on ", expTime, ") issued").AtInfo().WriteToLog()
  127. } else {
  128. newError("failed to parse new certificate for ", domain).Base(err).WriteToLog()
  129. }
  130. access.Lock()
  131. c.Certificates = append(c.Certificates, *newCert)
  132. issuedCertificate = &c.Certificates[len(c.Certificates)-1]
  133. access.Unlock()
  134. break
  135. }
  136. }
  137. if issuedCertificate == nil {
  138. return nil, newError("failed to create a new certificate for ", domain)
  139. }
  140. access.Lock()
  141. c.BuildNameToCertificate()
  142. access.Unlock()
  143. return issuedCertificate, nil
  144. }
  145. }
  146. func (c *Config) IsExperiment8357() bool {
  147. return strings.HasPrefix(c.ServerName, exp8357)
  148. }
  149. func (c *Config) parseServerName() string {
  150. if c.IsExperiment8357() {
  151. return c.ServerName[len(exp8357):]
  152. }
  153. return c.ServerName
  154. }
  155. func (c *Config) verifyPeerCert(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  156. if c.PinnedPeerCertificateChainSha256 != nil {
  157. hashValue := GenerateCertChainHash(rawCerts)
  158. for _, v := range c.PinnedPeerCertificateChainSha256 {
  159. if hmac.Equal(hashValue, v) {
  160. return nil
  161. }
  162. }
  163. return newError("peer cert is unrecognized: ", base64.StdEncoding.EncodeToString(hashValue))
  164. }
  165. return nil
  166. }
  167. // GetTLSConfig converts this Config into tls.Config.
  168. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  169. root, err := c.getCertPool()
  170. if err != nil {
  171. newError("failed to load system root certificate").AtError().Base(err).WriteToLog()
  172. }
  173. if c == nil {
  174. return &tls.Config{
  175. ClientSessionCache: globalSessionCache,
  176. RootCAs: root,
  177. InsecureSkipVerify: false,
  178. NextProtos: nil,
  179. SessionTicketsDisabled: true,
  180. }
  181. }
  182. config := &tls.Config{
  183. ClientSessionCache: globalSessionCache,
  184. RootCAs: root,
  185. InsecureSkipVerify: c.AllowInsecure,
  186. NextProtos: c.NextProtocol,
  187. SessionTicketsDisabled: !c.EnableSessionResumption,
  188. VerifyPeerCertificate: c.verifyPeerCert,
  189. }
  190. for _, opt := range opts {
  191. opt(config)
  192. }
  193. config.Certificates = c.BuildCertificates()
  194. config.BuildNameToCertificate()
  195. caCerts := c.getCustomCA()
  196. if len(caCerts) > 0 {
  197. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  198. }
  199. if sn := c.parseServerName(); len(sn) > 0 {
  200. config.ServerName = sn
  201. }
  202. if len(config.NextProtos) == 0 {
  203. config.NextProtos = []string{"h2", "http/1.1"}
  204. }
  205. return config
  206. }
  207. // Option for building TLS config.
  208. type Option func(*tls.Config)
  209. // WithDestination sets the server name in TLS config.
  210. func WithDestination(dest net.Destination) Option {
  211. return func(config *tls.Config) {
  212. if dest.Address.Family().IsDomain() && config.ServerName == "" {
  213. config.ServerName = dest.Address.Domain()
  214. }
  215. }
  216. }
  217. // WithNextProto sets the ALPN values in TLS config.
  218. func WithNextProto(protocol ...string) Option {
  219. return func(config *tls.Config) {
  220. if len(config.NextProtos) == 0 {
  221. config.NextProtos = protocol
  222. }
  223. }
  224. }
  225. // ConfigFromStreamSettings fetches Config from stream settings. Nil if not found.
  226. func ConfigFromStreamSettings(settings *internet.MemoryStreamConfig) *Config {
  227. if settings == nil {
  228. return nil
  229. }
  230. config, ok := settings.SecuritySettings.(*Config)
  231. if !ok {
  232. return nil
  233. }
  234. return config
  235. }