-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_context.go
262 lines (244 loc) · 6.96 KB
/
tls_context.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mtls
import (
"crypto/x509"
"fmt"
"strings"
"sofastack.io/sofa-mosn/pkg/api/v2"
"sofastack.io/sofa-mosn/pkg/log"
"sofastack.io/sofa-mosn/pkg/mtls/crypto/tls"
"sofastack.io/sofa-mosn/pkg/types"
)
type secretInfo struct {
Certificate string
PrivateKey string
Validation string // root ca
}
// full returns whether the secret info is full enough for a tls config
func (info *secretInfo) full() bool {
return info.Certificate != "" && info.PrivateKey != "" && info.Validation != ""
}
// tlsContext is an implmentation of basic provider
type tlsContext struct {
serverName string
ticket string
matches map[string]struct{}
client *tls.Config
server *tls.Config
}
func (ctx *tlsContext) buildMatch() {
if ctx.server == nil {
return
}
matches := make(map[string]struct{})
certs := ctx.server.Certificates
for i := range certs {
cert := certs[i]
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
continue
}
if len(x509Cert.Subject.CommonName) > 0 {
matches[x509Cert.Subject.CommonName] = struct{}{}
}
for _, san := range x509Cert.DNSNames {
matches[san] = struct{}{}
}
}
for _, protocol := range ctx.server.NextProtos {
matches[protocol] = struct{}{}
}
matches[ctx.serverName] = struct{}{}
ctx.matches = matches
}
func (ctx *tlsContext) setServerConfig(tmpl tls.Config, cfg *v2.TLSConfig, hooks ConfigHooks) {
tlsConfig := &tmpl
// no certificate should be set no server tls config
if len(tlsConfig.Certificates) == 0 {
return
}
if !cfg.RequireClientCert {
tlsConfig.ClientAuth = tls.NoClientCert
} else {
if cfg.VerifyClient {
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
} else {
tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
}
}
tlsConfig.VerifyPeerCertificate = hooks.ServerHandshakeVerify(tlsConfig)
ctx.server = tlsConfig
// build matches
ctx.buildMatch()
}
func (ctx *tlsContext) setClientConfig(tmpl tls.Config, cfg *v2.TLSConfig, hooks ConfigHooks) {
tlsConfig := &tmpl
tlsConfig.ServerName = cfg.ServerName
tlsConfig.VerifyPeerCertificate = hooks.ClientHandshakeVerify(tlsConfig)
if tlsConfig.VerifyPeerCertificate != nil {
// use self verify, skip normal verify
tlsConfig.InsecureSkipVerify = true
}
if cfg.InsecureSkip {
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyPeerCertificate = nil
}
ctx.client = tlsConfig
}
func (ctx *tlsContext) MatchedServerName(sn string) bool {
name := strings.ToLower(sn)
// e.g. www.example.com will be first matched against www.example.com, then *.example.com, then *.com
for len(name) > 0 && name[len(name)-1] == '.' {
name = name[:len(name)-1]
}
if _, ok := ctx.matches[name]; ok {
return true
}
labels := strings.Split(name, ".")
for i := 0; i < len(labels)-1; i++ {
labels[i] = "*"
candidate := strings.Join(labels[i:], ".")
if _, ok := ctx.matches[candidate]; ok {
return true
}
}
return false
}
func (ctx *tlsContext) MatchedALPN(protos []string) bool {
for _, protocol := range protos {
protocol = strings.ToLower(protocol)
if _, ok := ctx.matches[protocol]; ok {
return true
}
}
return false
}
func (ctx *tlsContext) GetTLSConfig(client bool) *tls.Config {
if client {
return ctx.client.Clone()
} else {
if ctx.server == nil {
return nil
}
return ctx.server.Clone()
}
}
func newTLSContext(cfg *v2.TLSConfig, secret *secretInfo) (*tlsContext, error) {
// basic template
tmpl, err := tlsConfigTemplate(cfg)
if err != nil {
return nil, err
}
// extension config
factory := getFactory(cfg.Type)
hooks := factory.CreateConfigHooks(cfg.ExtendVerify)
// pool can be nil, if it is nil, TLS uses the host's root CA set.
pool, err := hooks.GetX509Pool(secret.Validation)
if err != nil {
return nil, err
}
tmpl.RootCAs = pool
tmpl.ClientCAs = pool
// set tls context
ctx := &tlsContext{
serverName: cfg.ServerName,
ticket: cfg.Ticket,
}
cert, err := hooks.GetCertificate(secret.Certificate, secret.PrivateKey)
switch err {
case ErrorNoCertConfigure:
// no certificate
case nil:
tmpl.Certificates = append(tmpl.Certificates, cert)
default:
// get certificate failed, if fallback is configured, it is ok
if !cfg.Fallback {
return nil, err
} else {
log.DefaultLogger.Alertf(types.ErrorKeyTLSFallback, "get certificate failed: %v, fallback tls", err)
}
}
// needs copy template config
if len(tmpl.Certificates) > 0 {
ctx.setServerConfig(*tmpl, cfg, hooks)
}
ctx.setClientConfig(*tmpl, cfg, hooks)
return ctx, nil
}
func tlsConfigTemplate(c *v2.TLSConfig) (*tls.Config, error) {
tlsConfig := &tls.Config{}
// prefer server cipher suites by default
tlsConfig.PreferServerCipherSuites = true
if c.CipherSuites != "" {
ciphers := strings.Split(c.CipherSuites, ":")
for _, s := range ciphers {
cipher, ok := ciphersMap[s]
if !ok {
return nil, fmt.Errorf("cipher %s is not supported", s)
}
tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, cipher)
}
if len(tlsConfig.CipherSuites) == 0 {
tlsConfig.CipherSuites = defaultCiphers
}
}
if c.EcdhCurves != "" {
curves := strings.Split(c.EcdhCurves, ",")
for _, s := range curves {
curve, ok := allCurves[strings.ToLower(s)]
if !ok {
return nil, fmt.Errorf("curve %s is not supported", s)
}
tlsConfig.CurvePreferences = append(tlsConfig.CurvePreferences, curve)
}
if len(tlsConfig.CurvePreferences) == 0 {
tlsConfig.CurvePreferences = defaultCurves
}
}
tlsConfig.MaxVersion = maxProtocols
if c.MaxVersion != "" {
protocol, ok := version[strings.ToLower(c.MaxVersion)]
if !ok {
return nil, fmt.Errorf("tls protocol %s is not supported", c.MaxVersion)
}
if protocol != 0 {
tlsConfig.MaxVersion = protocol
}
}
tlsConfig.MinVersion = minProtocols
if c.MinVersion != "" {
protocol, ok := version[strings.ToLower(c.MinVersion)]
if !ok {
return nil, fmt.Errorf("tls protocol %s is not supported", c.MaxVersion)
}
if protocol != 0 {
tlsConfig.MinVersion = protocol
}
}
if c.ALPN != "" {
protocols := strings.Split(c.ALPN, ",")
for _, p := range protocols {
_, ok := alpn[strings.ToLower(p)]
if !ok {
return nil, fmt.Errorf("ALPN %s is not supported", p)
}
tlsConfig.NextProtos = append(tlsConfig.NextProtos, p)
}
}
return tlsConfig, nil
}