config.go 6.7 KB

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