-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathconfig.go
439 lines (375 loc) · 12.1 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package smokescreen
import (
"context"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strconv"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
acl "github.com/stripe/smokescreen/pkg/smokescreen/acl/v1"
"github.com/stripe/smokescreen/pkg/smokescreen/conntrack"
"github.com/stripe/smokescreen/pkg/smokescreen/metrics"
)
type RuleRange struct {
Net net.IPNet
Port int
}
// Resolver implements the interface needed by smokescreen and implemented by *net.Resolver
// This will allow different resolvers to also be provided
type Resolver interface {
LookupPort(ctx context.Context, network, service string) (port int, err error)
LookupIP(ctx context.Context, network, host string) ([]net.IP, error)
}
type Config struct {
Ip string
Port uint16
Listener net.Listener
DenyRanges []RuleRange
AllowRanges []RuleRange
Resolver Resolver
ConnectTimeout time.Duration
ExitTimeout time.Duration
MetricsClient metrics.MetricsClientInterface
EgressACL acl.Decider
SupportProxyProtocol bool
TlsConfig *tls.Config
CrlByAuthorityKeyId map[string]*pkix.CertificateList
RoleFromRequest func(subject *http.Request) (string, error)
clientCasBySubjectKeyId map[string]*x509.Certificate
AdditionalErrorMessageOnDeny string
Log *log.Logger
DisabledAclPolicyActions []string
AllowMissingRole bool
StatsSocketDir string
StatsSocketFileMode os.FileMode
StatsServer *StatsServer // StatsServer
ConnTracker conntrack.TrackerInterface
Healthcheck http.Handler // User defined http.Handler for optional requests to a /healthcheck endpoint
ShuttingDown atomic.Value // Stores a boolean value indicating whether the proxy is actively shutting down
// Network type to use when performing DNS lookups. Must be one of "ip", "ip4" or "ip6".
Network string
// A connection is idle if it has been inactive (no bytes in/out) for this many seconds.
IdleTimeout time.Duration
// These are *only* used for traditional HTTP proxy requests
TransportMaxIdleConns int
TransportMaxIdleConnsPerHost int
// These are the http and https address for the upstream proxy
UpstreamHttpProxyAddr string
UpstreamHttpsProxyAddr string
// Used for logging connection time
TimeConnect bool
// Custom Dial Timeout function to be called
ProxyDialTimeout func(ctx context.Context, network, address string, timeout time.Duration) (net.Conn, error)
// Custom handler to allow clients to modify reject responses
RejectResponseHandler func(*http.Response)
// Custom handler to allow clients to modify successful CONNECT responses
AcceptResponseHandler func(*SmokescreenContext, *http.Response) error
// UnsafeAllowPrivateRanges inverts the default behavior, telling smokescreen to allow private IP
// ranges by default (exempting loopback and unicast ranges)
// This setting can be used to configure Smokescreen with a blocklist, rather than an allowlist
UnsafeAllowPrivateRanges bool
// Custom handler for users to allow running code per requests, users can pass in custom methods to verify requests based
// on headers, code for metrics etc.
// If smokescreen denies a request, this handler is not called.
// If the handler returns an error, smokescreen will deny the request.
PostDecisionRequestHandler func(*http.Request) error
}
type missingRoleError struct {
error
}
func MissingRoleError(s string) error {
return missingRoleError{errors.New(s)}
}
func IsMissingRoleError(err error) bool {
_, ok := err.(missingRoleError)
return ok
}
func parseRanges(rangeStrings []string) ([]RuleRange, error) {
outRanges := make([]RuleRange, len(rangeStrings))
for i, str := range rangeStrings {
_, ipnet, err := net.ParseCIDR(str)
if err != nil {
return outRanges, err
}
outRanges[i].Net = *ipnet
}
return outRanges, nil
}
func parseAddresses(addressStrings []string) ([]RuleRange, error) {
outRanges := make([]RuleRange, len(addressStrings))
for i, str := range addressStrings {
ip := net.ParseIP(str)
if ip == nil {
ipStr, portStr, err := net.SplitHostPort(str)
if err != nil {
return outRanges, fmt.Errorf("address must be in the form ip[:port], got %s", str)
}
ip = net.ParseIP(ipStr)
if ip == nil {
return outRanges, fmt.Errorf("invalid IP address '%s'", ipStr)
}
port, err := strconv.Atoi(portStr)
if err != nil {
return outRanges, fmt.Errorf("invalid port number '%s'", portStr)
}
outRanges[i].Port = port
}
var mask net.IPMask
if ip.To4() != nil {
mask = net.CIDRMask(32, 32)
} else {
mask = net.CIDRMask(128, 128)
}
outRanges[i].Net = net.IPNet{
IP: ip,
Mask: mask,
}
}
return outRanges, nil
}
func (config *Config) SetDenyRanges(rangeStrings []string) error {
var err error
ranges, err := parseRanges(rangeStrings)
if err != nil {
return err
}
config.DenyRanges = append(config.DenyRanges, ranges...)
return nil
}
func (config *Config) SetAllowRanges(rangeStrings []string) error {
var err error
ranges, err := parseRanges(rangeStrings)
if err != nil {
return err
}
config.AllowRanges = append(config.AllowRanges, ranges...)
return nil
}
func (config *Config) SetDenyAddresses(addressStrings []string) error {
var err error
ranges, err := parseAddresses(addressStrings)
if err != nil {
return err
}
config.DenyRanges = append(config.DenyRanges, ranges...)
return nil
}
func (config *Config) SetAllowAddresses(addressStrings []string) error {
var err error
ranges, err := parseAddresses(addressStrings)
if err != nil {
return err
}
config.AllowRanges = append(config.AllowRanges, ranges...)
return nil
}
func (config *Config) SetResolverAddresses(resolverAddresses []string) error {
// TODO: support round-robin between multiple addresses
if len(resolverAddresses) > 1 {
return fmt.Errorf("only one resolver address allowed, %d provided", len(resolverAddresses))
}
// No resolver specified, use the system resolver
if len(resolverAddresses) == 0 {
return nil
}
addr := resolverAddresses[0]
_, _, err := net.SplitHostPort(addr)
if err != nil {
return err
}
r := net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
d := net.Dialer{}
return d.DialContext(ctx, "udp", addr)
},
}
config.Resolver = &r
return nil
}
// RFC 5280, 4.2.1.1
type authKeyId struct {
Id []byte `asn1:"optional,tag:0"`
}
func NewConfig() *Config {
log.SetFormatter(&log.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
})
return &Config{
Resolver: &net.Resolver{},
CrlByAuthorityKeyId: make(map[string]*pkix.CertificateList),
clientCasBySubjectKeyId: make(map[string]*x509.Certificate),
Log: log.New(),
Port: 4750,
ExitTimeout: 500 * time.Minute,
StatsSocketFileMode: os.FileMode(0700),
ShuttingDown: atomic.Value{},
MetricsClient: metrics.NewNoOpMetricsClient(),
Network: "ip",
}
}
func (config *Config) SetupCrls(crlFiles []string) error {
for _, crlFile := range crlFiles {
crlBytes, err := ioutil.ReadFile(crlFile)
if err != nil {
return err
}
certList, err := x509.ParseCRL(crlBytes)
if err != nil {
log.Printf("Failed to parse CRL in '%s': %#v\n", crlFile, err)
}
// find the X509v3 Authority Key Identifier in the extensions (2.5.29.35)
crlIssuerId := ""
extensionOid := []int{2, 5, 29, 35}
for _, v := range certList.TBSCertList.Extensions {
if v.Id.Equal(extensionOid) { // Hurray, we found it
// Boo, it's ASN.1.
var crlAuthorityKey authKeyId
_, err := asn1.Unmarshal(v.Value, &crlAuthorityKey)
if err != nil {
fmt.Printf("error: Failed to read AuthorityKey: %#v\n", err)
continue
}
crlIssuerId = string(crlAuthorityKey.Id)
break
}
}
if crlIssuerId == "" {
log.Print(fmt.Errorf("error: CRL from '%s' has no Authority Key Identifier: ignoring it\n", crlFile))
continue
}
// Make sure we have a CA for this CRL or warn
caCert, ok := config.clientCasBySubjectKeyId[crlIssuerId]
if !ok {
log.Printf("warn: CRL loaded for issuer '%s' but no such CA loaded: ignoring it\n", hex.EncodeToString([]byte(crlIssuerId)))
fmt.Printf("%#v loaded certs\n", len(config.clientCasBySubjectKeyId))
continue
}
// At this point, we have the CA certificate and the CRL. All that's left before evicting the CRL we currently trust is to verify the new CRL's signature
err = caCert.CheckCRLSignature(certList)
if err != nil {
fmt.Printf("error: Could not trust CRL. Error during signature check: %#v\n", err)
continue
}
// At this point, we have a new CRL which we trust. Let's evict the old one.
config.CrlByAuthorityKeyId[crlIssuerId] = certList
fmt.Printf("info: Loaded CRL for Authority ID '%s'\n", hex.EncodeToString([]byte(crlIssuerId)))
}
// Verify that all CAs loaded have a CRL
for k := range config.clientCasBySubjectKeyId {
_, ok := config.CrlByAuthorityKeyId[k]
if !ok {
fmt.Printf("warn: no CRL loaded for Authority ID '%s'\n", hex.EncodeToString([]byte(k)))
}
}
return nil
}
func (config *Config) SetupStatsdWithNamespace(addr, namespace string) error {
if addr == "" {
fmt.Println("warn: no statsd addr provided, using noop client")
config.MetricsClient = metrics.NewNoOpMetricsClient()
return nil
}
mc, err := metrics.NewStatsdMetricsClient(addr, namespace)
if err != nil {
return err
}
config.MetricsClient = mc
return nil
}
func (config *Config) SetupStatsd(addr string) error {
return config.SetupStatsdWithNamespace(addr, DefaultStatsdNamespace)
}
func (config *Config) SetupPrometheus(endpoint string, port string, listenAddr string) error {
metricsClient, err := metrics.NewPrometheusMetricsClient(endpoint, port, listenAddr)
if err != nil {
return err
}
config.MetricsClient = metricsClient
return nil
}
func (config *Config) SetupEgressAcl(aclFile string) error {
if aclFile == "" {
config.EgressACL = nil
return nil
}
log.Printf("Loading egress ACL from %s", aclFile)
egressACL, err := acl.New(config.Log, acl.NewYAMLLoader(aclFile), config.DisabledAclPolicyActions)
if err != nil {
log.Print(err)
return err
}
config.EgressACL = egressACL
return nil
}
func addCertsFromFile(config *Config, pool *x509.CertPool, fileName string) error {
data, err := ioutil.ReadFile(fileName)
//TODO this is a bit awkward
config.populateClientCaMap(data)
if err != nil {
return err
}
ok := pool.AppendCertsFromPEM(data)
if !ok {
return fmt.Errorf("Failed to load any certificates from file '%s'", fileName)
}
return nil
}
// certFile and keyFile may be the same file containing concatenated PEM blocks
func (config *Config) SetupTls(certFile, keyFile string, clientCAFiles []string) error {
if certFile == "" || keyFile == "" {
return errors.New("both certificate and key files must be specified to set up TLS")
}
serverCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
clientAuth := tls.NoClientCert
clientCAs := x509.NewCertPool()
if len(clientCAFiles) != 0 {
clientAuth = tls.VerifyClientCertIfGiven
for _, caFile := range clientCAFiles {
err = addCertsFromFile(config, clientCAs, caFile)
if err != nil {
return err
}
}
}
config.TlsConfig = &tls.Config{
Certificates: []tls.Certificate{serverCert},
ClientAuth: clientAuth,
ClientCAs: clientCAs,
}
return nil
}
func (config *Config) populateClientCaMap(pemCerts []byte) (ok bool) {
for len(pemCerts) > 0 {
var block *pem.Block
block, pemCerts = pem.Decode(pemCerts)
if block == nil {
break
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
continue
}
fmt.Printf("info: Loaded CA with Authority ID '%s'\n", hex.EncodeToString(cert.SubjectKeyId))
config.clientCasBySubjectKeyId[string(cert.SubjectKeyId)] = cert
ok = true
}
return
}