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