config.go 8.6 KB

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