config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package tls
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "os"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/xtls/xray-core/common/errors"
  14. "github.com/xtls/xray-core/common/net"
  15. "github.com/xtls/xray-core/common/ocsp"
  16. "github.com/xtls/xray-core/common/platform/filesystem"
  17. "github.com/xtls/xray-core/common/protocol/tls/cert"
  18. "github.com/xtls/xray-core/transport/internet"
  19. )
  20. var globalSessionCache = tls.NewLRUClientSessionCache(128)
  21. // ParseCertificate converts a cert.Certificate to Certificate.
  22. func ParseCertificate(c *cert.Certificate) *Certificate {
  23. if c != nil {
  24. certPEM, keyPEM := c.ToPEM()
  25. return &Certificate{
  26. Certificate: certPEM,
  27. Key: keyPEM,
  28. }
  29. }
  30. return nil
  31. }
  32. func (c *Config) loadSelfCertPool() (*x509.CertPool, error) {
  33. root := x509.NewCertPool()
  34. for _, cert := range c.Certificate {
  35. if !root.AppendCertsFromPEM(cert.Certificate) {
  36. return nil, errors.New("failed to append cert").AtWarning()
  37. }
  38. }
  39. return root, nil
  40. }
  41. // BuildCertificates builds a list of TLS certificates from proto definition.
  42. func (c *Config) BuildCertificates() []*tls.Certificate {
  43. certs := make([]*tls.Certificate, 0, len(c.Certificate))
  44. for _, entry := range c.Certificate {
  45. if entry.Usage != Certificate_ENCIPHERMENT {
  46. continue
  47. }
  48. getX509KeyPair := func() *tls.Certificate {
  49. keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key)
  50. if err != nil {
  51. errors.LogWarningInner(context.Background(), err, "ignoring invalid X509 key pair")
  52. return nil
  53. }
  54. keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
  55. if err != nil {
  56. errors.LogWarningInner(context.Background(), err, "ignoring invalid certificate")
  57. return nil
  58. }
  59. return &keyPair
  60. }
  61. if keyPair := getX509KeyPair(); keyPair != nil {
  62. certs = append(certs, keyPair)
  63. } else {
  64. continue
  65. }
  66. index := len(certs) - 1
  67. setupOcspTicker(entry, func(isReloaded, isOcspstapling bool) {
  68. cert := certs[index]
  69. if isReloaded {
  70. if newKeyPair := getX509KeyPair(); newKeyPair != nil {
  71. cert = newKeyPair
  72. } else {
  73. return
  74. }
  75. }
  76. if isOcspstapling {
  77. if newOCSPData, err := ocsp.GetOCSPForCert(cert.Certificate); err != nil {
  78. errors.LogWarningInner(context.Background(), err, "ignoring invalid OCSP")
  79. } else if string(newOCSPData) != string(cert.OCSPStaple) {
  80. cert.OCSPStaple = newOCSPData
  81. }
  82. }
  83. certs[index] = cert
  84. })
  85. }
  86. return certs
  87. }
  88. func setupOcspTicker(entry *Certificate, callback func(isReloaded, isOcspstapling bool)) {
  89. go func() {
  90. if entry.OneTimeLoading {
  91. return
  92. }
  93. var isOcspstapling bool
  94. hotReloadCertInterval := uint64(3600)
  95. if entry.OcspStapling != 0 {
  96. hotReloadCertInterval = entry.OcspStapling
  97. isOcspstapling = true
  98. }
  99. t := time.NewTicker(time.Duration(hotReloadCertInterval) * time.Second)
  100. for {
  101. var isReloaded bool
  102. if entry.CertificatePath != "" && entry.KeyPath != "" {
  103. newCert, err := filesystem.ReadFile(entry.CertificatePath)
  104. if err != nil {
  105. errors.LogErrorInner(context.Background(), err, "failed to parse certificate")
  106. return
  107. }
  108. newKey, err := filesystem.ReadFile(entry.KeyPath)
  109. if err != nil {
  110. errors.LogErrorInner(context.Background(), err, "failed to parse key")
  111. return
  112. }
  113. if string(newCert) != string(entry.Certificate) || string(newKey) != string(entry.Key) {
  114. entry.Certificate = newCert
  115. entry.Key = newKey
  116. isReloaded = true
  117. }
  118. }
  119. callback(isReloaded, isOcspstapling)
  120. <-t.C
  121. }
  122. }()
  123. }
  124. func isCertificateExpired(c *tls.Certificate) bool {
  125. if c.Leaf == nil && len(c.Certificate) > 0 {
  126. if pc, err := x509.ParseCertificate(c.Certificate[0]); err == nil {
  127. c.Leaf = pc
  128. }
  129. }
  130. // If leaf is not there, the certificate is probably not used yet. We trust user to provide a valid certificate.
  131. return c.Leaf != nil && c.Leaf.NotAfter.Before(time.Now().Add(time.Minute*2))
  132. }
  133. func issueCertificate(rawCA *Certificate, domain string) (*tls.Certificate, error) {
  134. parent, err := cert.ParseCertificate(rawCA.Certificate, rawCA.Key)
  135. if err != nil {
  136. return nil, errors.New("failed to parse raw certificate").Base(err)
  137. }
  138. newCert, err := cert.Generate(parent, cert.CommonName(domain), cert.DNSNames(domain))
  139. if err != nil {
  140. return nil, errors.New("failed to generate new certificate for ", domain).Base(err)
  141. }
  142. newCertPEM, newKeyPEM := newCert.ToPEM()
  143. if rawCA.BuildChain {
  144. newCertPEM = bytes.Join([][]byte{newCertPEM, rawCA.Certificate}, []byte("\n"))
  145. }
  146. cert, err := tls.X509KeyPair(newCertPEM, newKeyPEM)
  147. return &cert, err
  148. }
  149. func (c *Config) getCustomCA() []*Certificate {
  150. certs := make([]*Certificate, 0, len(c.Certificate))
  151. for _, certificate := range c.Certificate {
  152. if certificate.Usage == Certificate_AUTHORITY_ISSUE {
  153. certs = append(certs, certificate)
  154. setupOcspTicker(certificate, func(isReloaded, isOcspstapling bool) {})
  155. }
  156. }
  157. return certs
  158. }
  159. func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  160. var access sync.RWMutex
  161. return func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  162. domain := hello.ServerName
  163. certExpired := false
  164. access.RLock()
  165. certificate, found := c.NameToCertificate[domain]
  166. access.RUnlock()
  167. if found {
  168. if !isCertificateExpired(certificate) {
  169. return certificate, nil
  170. }
  171. certExpired = true
  172. }
  173. if certExpired {
  174. newCerts := make([]tls.Certificate, 0, len(c.Certificates))
  175. access.Lock()
  176. for _, certificate := range c.Certificates {
  177. if !isCertificateExpired(&certificate) {
  178. newCerts = append(newCerts, certificate)
  179. } else if certificate.Leaf != nil {
  180. expTime := certificate.Leaf.NotAfter.Format(time.RFC3339)
  181. errors.LogInfo(context.Background(), "old certificate for ", domain, " (expire on ", expTime, ") discarded")
  182. }
  183. }
  184. c.Certificates = newCerts
  185. access.Unlock()
  186. }
  187. var issuedCertificate *tls.Certificate
  188. // Create a new certificate from existing CA if possible
  189. for _, rawCert := range ca {
  190. if rawCert.Usage == Certificate_AUTHORITY_ISSUE {
  191. newCert, err := issueCertificate(rawCert, domain)
  192. if err != nil {
  193. errors.LogInfoInner(context.Background(), err, "failed to issue new certificate for ", domain)
  194. continue
  195. }
  196. parsed, err := x509.ParseCertificate(newCert.Certificate[0])
  197. if err == nil {
  198. newCert.Leaf = parsed
  199. expTime := parsed.NotAfter.Format(time.RFC3339)
  200. errors.LogInfo(context.Background(), "new certificate for ", domain, " (expire on ", expTime, ") issued")
  201. } else {
  202. errors.LogInfoInner(context.Background(), err, "failed to parse new certificate for ", domain)
  203. }
  204. access.Lock()
  205. c.Certificates = append(c.Certificates, *newCert)
  206. issuedCertificate = &c.Certificates[len(c.Certificates)-1]
  207. access.Unlock()
  208. break
  209. }
  210. }
  211. if issuedCertificate == nil {
  212. return nil, errors.New("failed to create a new certificate for ", domain)
  213. }
  214. access.Lock()
  215. c.BuildNameToCertificate()
  216. access.Unlock()
  217. return issuedCertificate, nil
  218. }
  219. }
  220. func getNewGetCertificateFunc(certs []*tls.Certificate, rejectUnknownSNI bool) func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  221. return func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  222. if len(certs) == 0 {
  223. return nil, errNoCertificates
  224. }
  225. sni := strings.ToLower(hello.ServerName)
  226. if !rejectUnknownSNI && (len(certs) == 1 || sni == "") {
  227. return certs[0], nil
  228. }
  229. gsni := "*"
  230. if index := strings.IndexByte(sni, '.'); index != -1 {
  231. gsni += sni[index:]
  232. }
  233. for _, keyPair := range certs {
  234. if keyPair.Leaf.Subject.CommonName == sni || keyPair.Leaf.Subject.CommonName == gsni {
  235. return keyPair, nil
  236. }
  237. for _, name := range keyPair.Leaf.DNSNames {
  238. if name == sni || name == gsni {
  239. return keyPair, nil
  240. }
  241. }
  242. }
  243. if rejectUnknownSNI {
  244. return nil, errNoCertificates
  245. }
  246. return certs[0], nil
  247. }
  248. }
  249. func (c *Config) parseServerName() string {
  250. return c.ServerName
  251. }
  252. func (c *Config) verifyPeerCert(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  253. if c.PinnedPeerCertificateChainSha256 != nil {
  254. hashValue := GenerateCertChainHash(rawCerts)
  255. for _, v := range c.PinnedPeerCertificateChainSha256 {
  256. if hmac.Equal(hashValue, v) {
  257. return nil
  258. }
  259. }
  260. return errors.New("peer cert is unrecognized: ", base64.StdEncoding.EncodeToString(hashValue))
  261. }
  262. if c.PinnedPeerCertificatePublicKeySha256 != nil {
  263. for _, v := range verifiedChains {
  264. for _, cert := range v {
  265. publicHash := GenerateCertPublicKeyHash(cert)
  266. for _, c := range c.PinnedPeerCertificatePublicKeySha256 {
  267. if hmac.Equal(publicHash, c) {
  268. return nil
  269. }
  270. }
  271. }
  272. }
  273. return errors.New("peer public key is unrecognized.")
  274. }
  275. return nil
  276. }
  277. // GetTLSConfig converts this Config into tls.Config.
  278. func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
  279. root, err := c.getCertPool()
  280. if err != nil {
  281. errors.LogErrorInner(context.Background(), err, "failed to load system root certificate")
  282. }
  283. if c == nil {
  284. return &tls.Config{
  285. ClientSessionCache: globalSessionCache,
  286. RootCAs: root,
  287. InsecureSkipVerify: false,
  288. NextProtos: nil,
  289. SessionTicketsDisabled: true,
  290. }
  291. }
  292. config := &tls.Config{
  293. ClientSessionCache: globalSessionCache,
  294. RootCAs: root,
  295. InsecureSkipVerify: c.AllowInsecure,
  296. NextProtos: c.NextProtocol,
  297. SessionTicketsDisabled: !c.EnableSessionResumption,
  298. VerifyPeerCertificate: c.verifyPeerCert,
  299. }
  300. for _, opt := range opts {
  301. opt(config)
  302. }
  303. caCerts := c.getCustomCA()
  304. if len(caCerts) > 0 {
  305. config.GetCertificate = getGetCertificateFunc(config, caCerts)
  306. } else {
  307. config.GetCertificate = getNewGetCertificateFunc(c.BuildCertificates(), c.RejectUnknownSni)
  308. }
  309. if sn := c.parseServerName(); len(sn) > 0 {
  310. config.ServerName = sn
  311. }
  312. if len(c.CurvePreferences) > 0 {
  313. config.CurvePreferences = ParseCurveName(c.CurvePreferences)
  314. }
  315. if len(config.NextProtos) == 0 {
  316. config.NextProtos = []string{"h2", "http/1.1"}
  317. }
  318. switch c.MinVersion {
  319. case "1.0":
  320. config.MinVersion = tls.VersionTLS10
  321. case "1.1":
  322. config.MinVersion = tls.VersionTLS11
  323. case "1.2":
  324. config.MinVersion = tls.VersionTLS12
  325. case "1.3":
  326. config.MinVersion = tls.VersionTLS13
  327. }
  328. switch c.MaxVersion {
  329. case "1.0":
  330. config.MaxVersion = tls.VersionTLS10
  331. case "1.1":
  332. config.MaxVersion = tls.VersionTLS11
  333. case "1.2":
  334. config.MaxVersion = tls.VersionTLS12
  335. case "1.3":
  336. config.MaxVersion = tls.VersionTLS13
  337. }
  338. if len(c.CipherSuites) > 0 {
  339. id := make(map[string]uint16)
  340. for _, s := range tls.CipherSuites() {
  341. id[s.Name] = s.ID
  342. }
  343. for _, n := range strings.Split(c.CipherSuites, ":") {
  344. if id[n] != 0 {
  345. config.CipherSuites = append(config.CipherSuites, id[n])
  346. }
  347. }
  348. }
  349. if len(c.MasterKeyLog) > 0 && c.MasterKeyLog != "none" {
  350. writer, err := os.OpenFile(c.MasterKeyLog, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
  351. if err != nil {
  352. errors.LogErrorInner(context.Background(), err, "failed to open ", c.MasterKeyLog, " as master key log")
  353. } else {
  354. config.KeyLogWriter = writer
  355. }
  356. }
  357. return config
  358. }
  359. // Option for building TLS config.
  360. type Option func(*tls.Config)
  361. // WithDestination sets the server name in TLS config.
  362. // Due to the incorrect structure of GetTLSConfig(), the config.ServerName will always be empty.
  363. // So the real logic for SNI is:
  364. // set it to dest -> overwrite it with servername(if it's len>0).
  365. func WithDestination(dest net.Destination) Option {
  366. return func(config *tls.Config) {
  367. if config.ServerName == "" {
  368. config.ServerName = dest.Address.String()
  369. }
  370. }
  371. }
  372. // WithNextProto sets the ALPN values in TLS config.
  373. func WithNextProto(protocol ...string) Option {
  374. return func(config *tls.Config) {
  375. if len(config.NextProtos) == 0 {
  376. config.NextProtos = protocol
  377. }
  378. }
  379. }
  380. // ConfigFromStreamSettings fetches Config from stream settings. Nil if not found.
  381. func ConfigFromStreamSettings(settings *internet.MemoryStreamConfig) *Config {
  382. if settings == nil {
  383. return nil
  384. }
  385. config, ok := settings.SecuritySettings.(*Config)
  386. if !ok {
  387. return nil
  388. }
  389. return config
  390. }
  391. func ParseCurveName(curveNames []string) []tls.CurveID {
  392. curveMap := map[string]tls.CurveID{
  393. "curvep256": tls.CurveP256,
  394. "curvep384": tls.CurveP384,
  395. "curvep521": tls.CurveP521,
  396. "x25519": tls.X25519,
  397. "x25519kyber768draft00": 0x6399,
  398. }
  399. var curveIDs []tls.CurveID
  400. for _, name := range curveNames {
  401. if curveID, ok := curveMap[strings.ToLower(name)]; ok {
  402. curveIDs = append(curveIDs, curveID)
  403. } else {
  404. errors.LogWarning(context.Background(), "unsupported curve name: "+name)
  405. }
  406. }
  407. return curveIDs
  408. }