config.go 11 KB

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