config.go 7.0 KB

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