-
Notifications
You must be signed in to change notification settings - Fork 0
/
configuration.go
573 lines (532 loc) · 15.1 KB
/
configuration.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
/*
Copyright 2015-16 Gravitational, Inc.
Licensed 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 config
import (
"io/ioutil"
"net"
"os"
"path/filepath"
"strings"
"time"
"unicode"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/backend/etcdbk"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/limiter"
"github.com/gravitational/teleport/lib/service"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
log "github.com/Sirupsen/logrus"
"github.com/kardianos/osext"
)
// CommandLineFlags stores command line flag values, it's a much simplified subset
// of Teleport configuration (which is fully expressed via YAML config file)
type CommandLineFlags struct {
// --name flag
NodeName string
// --auth-server flag
AuthServerAddr string
// --token flag
AuthToken string
// --listen-ip flag
ListenIP net.IP
// --advertise-ip flag
AdvertiseIP net.IP
// --config flag
ConfigFile string
// ConfigString is a base64 encoded configuration string
// set by --config-string or TELEPORT_CONFIG environment variable
ConfigString string
// --roles flag
Roles string
// -d flag
Debug bool
// --labels flag
Labels string
// --httpprofile hidden flag
HTTPProfileEndpoint bool
// --pid-file flag
PIDFile string
}
// readConfigFile reads /etc/teleport.yaml (or whatever is passed via --config flag)
// and overrides values in 'cfg' structure
func readConfigFile(cliConfigPath string) (*FileConfig, error) {
configFilePath := defaults.ConfigFilePath
// --config tells us to use a specific conf. file:
if cliConfigPath != "" {
configFilePath = cliConfigPath
if !fileExists(configFilePath) {
return nil, trace.Errorf("file not found: %s", configFilePath)
}
}
// default config doesn't exist? quietly return:
if !fileExists(configFilePath) {
log.Info("not using a config file")
return nil, nil
}
log.Debug("reading config file: ", configFilePath)
return ReadFromFile(configFilePath)
}
// ApplyFileConfig applies confniguration from a YAML file to Teleport
// runtime config
func ApplyFileConfig(fc *FileConfig, cfg *service.Config) error {
// no config file? no problem
if fc == nil {
return nil
}
// merge file-based config with defaults in 'cfg'
if fc.Auth.Disabled() {
cfg.Auth.Enabled = false
}
if fc.SSH.Disabled() {
cfg.SSH.Enabled = false
}
if fc.Proxy.Disabled() {
cfg.Proxy.Enabled = false
}
applyString(fc.NodeName, &cfg.Hostname)
// apply "advertise_ip" setting:
advertiseIP := fc.AdvertiseIP
if advertiseIP != nil {
if err := validateAdvertiseIP(advertiseIP); err != nil {
return trace.Wrap(err)
}
cfg.AdvertiseIP = advertiseIP
}
cfg.PIDFile = fc.PIDFile
// config file has auth servers in there?
if len(fc.AuthServers) > 0 {
cfg.AuthServers = make([]utils.NetAddr, 0, len(fc.AuthServers))
for _, as := range fc.AuthServers {
addr, err := utils.ParseAddr(as)
if err != nil {
return trace.Errorf("cannot parse auth server address: '%v'", as)
}
cfg.AuthServers = append(cfg.AuthServers, *addr)
}
}
cfg.ApplyToken(fc.AuthToken)
cfg.Auth.DomainName = fc.Auth.DomainName
// configure storage:
switch fc.Storage.Type {
case teleport.BoltBackendType:
cfg.ConfigureBolt(fc.Storage.DirName)
case teleport.ETCDBackendType:
if err := cfg.ConfigureETCD(
fc.Storage.DirName, etcdbk.Config{
Nodes: fc.Storage.Peers,
Key: fc.Storage.Prefix,
TLSKeyFile: fc.Storage.TLSKeyFile,
TLSCertFile: fc.Storage.TLSCertFile,
TLSCAFile: fc.Storage.TLSCAFile,
}); err != nil {
return trace.Wrap(err)
}
case "":
break // not set
default:
return trace.BadParameter("unsupported storage type: '%v'", fc.Storage.Type)
}
// apply logger settings
switch fc.Logger.Output {
case "":
break // not set
case "stderr", "error", "2":
log.SetOutput(os.Stderr)
case "stdout", "out", "1":
log.SetOutput(os.Stdout)
default:
// assume it's a file path:
logFile, err := os.Create(fc.Logger.Output)
if err != nil {
return trace.Wrap(err, "failed to create the log file")
}
log.SetOutput(logFile)
}
switch strings.ToLower(fc.Logger.Severity) {
case "":
break // not set
case "info":
log.SetLevel(log.InfoLevel)
case "err", "error":
log.SetLevel(log.ErrorLevel)
case "debug":
log.SetLevel(log.DebugLevel)
case "warn", "warning":
log.SetLevel(log.WarnLevel)
default:
return trace.Errorf("unsupported logger severity: '%v'", fc.Logger.Severity)
}
// apply connection throttling:
limiters := []limiter.LimiterConfig{
cfg.SSH.Limiter,
cfg.Auth.Limiter,
cfg.Proxy.Limiter,
}
for _, l := range limiters {
if fc.Limits.MaxConnections > 0 {
l.MaxConnections = fc.Limits.MaxConnections
}
if fc.Limits.MaxUsers > 0 {
l.MaxNumberOfUsers = fc.Limits.MaxUsers
}
for _, rate := range fc.Limits.Rates {
l.Rates = append(l.Rates, limiter.Rate{
Period: rate.Period,
Average: rate.Average,
Burst: rate.Burst,
})
}
}
// add static signed keypairs supplied from configs
for i := range fc.Global.Keys {
identity, err := fc.Global.Keys[i].Identity()
if err != nil {
return trace.Wrap(err)
}
cfg.Identities = append(cfg.Identities, identity)
}
// add reverse tunnels supplied from configs
for _, t := range fc.Auth.ReverseTunnels {
tun, err := t.Tunnel()
if err != nil {
return trace.Wrap(err)
}
cfg.ReverseTunnels = append(cfg.ReverseTunnels, *tun)
}
// add oidc connectors supplied from configs
for _, c := range fc.Auth.OIDCConnectors {
conn, err := c.Parse()
if err != nil {
return trace.Wrap(err)
}
cfg.OIDCConnectors = append(cfg.OIDCConnectors, *conn)
}
// apply "proxy_service" section
if fc.Proxy.ListenAddress != "" {
addr, err := utils.ParseHostPortAddr(fc.Proxy.ListenAddress, int(defaults.SSHProxyListenPort))
if err != nil {
return trace.Wrap(err)
}
cfg.Proxy.SSHAddr = *addr
}
if fc.Proxy.WebAddr != "" {
addr, err := utils.ParseHostPortAddr(fc.Proxy.WebAddr, int(defaults.HTTPListenPort))
if err != nil {
return trace.Wrap(err)
}
cfg.Proxy.WebAddr = *addr
}
if fc.Proxy.KeyFile != "" {
if !fileExists(fc.Proxy.KeyFile) {
return trace.Errorf("https key does not exist: %s", fc.Proxy.KeyFile)
}
cfg.Proxy.TLSKey = fc.Proxy.KeyFile
}
if fc.Proxy.CertFile != "" {
if !fileExists(fc.Proxy.CertFile) {
return trace.Errorf("https cert does not exist: %s", fc.Proxy.CertFile)
}
cfg.Proxy.TLSCert = fc.Proxy.CertFile
}
// apply "auth_service" section
if fc.Auth.ListenAddress != "" {
addr, err := utils.ParseHostPortAddr(fc.Auth.ListenAddress, int(defaults.AuthListenPort))
if err != nil {
return trace.Wrap(err)
}
cfg.Auth.SSHAddr = *addr
}
for _, authority := range fc.Auth.Authorities {
ca, err := authority.Parse()
if err != nil {
return trace.Wrap(err)
}
cfg.Auth.Authorities = append(cfg.Auth.Authorities, *ca)
}
// apply "ssh_service" section
if fc.SSH.ListenAddress != "" {
addr, err := utils.ParseHostPortAddr(fc.SSH.ListenAddress, int(defaults.SSHServerListenPort))
if err != nil {
return trace.Wrap(err)
}
cfg.SSH.Addr = *addr
}
if fc.SSH.Labels != nil {
cfg.SSH.Labels = make(map[string]string)
for k, v := range fc.SSH.Labels {
cfg.SSH.Labels[k] = v
}
}
if fc.SSH.Commands != nil {
cfg.SSH.CmdLabels = make(services.CommandLabels)
for _, cmdLabel := range fc.SSH.Commands {
cfg.SSH.CmdLabels[cmdLabel.Name] = services.CommandLabel{
Period: cmdLabel.Period,
Command: cmdLabel.Command,
Result: "",
}
}
}
return nil
}
// applyString takes 'src' and overwrites target with it, unless 'src' is empty
// returns 'True' if 'src' was not empty
func applyString(src string, target *string) bool {
if src != "" {
*target = src
return true
}
return false
}
// Configure merges command line arguments with what's in a configuration file
// with CLI commands taking precedence
func Configure(clf *CommandLineFlags, cfg *service.Config) error {
// load /etc/teleport.yaml and apply it's values:
fileConf, err := readConfigFile(clf.ConfigFile)
if err != nil {
return trace.Wrap(err)
}
// if configuration is passed as an environment variable,
// try to decode it and override the config file
if clf.ConfigString != "" {
fileConf, err = ReadFromString(clf.ConfigString)
if err != nil {
return trace.Wrap(err)
}
}
if err = ApplyFileConfig(fileConf, cfg); err != nil {
return trace.Wrap(err)
}
// apply --debug flag:
if clf.Debug {
cfg.Console = ioutil.Discard
utils.InitLoggerDebug()
}
// apply --roles flag:
if clf.Roles != "" {
if err := validateRoles(clf.Roles); err != nil {
return trace.Wrap(err)
}
cfg.SSH.Enabled = strings.Index(clf.Roles, defaults.RoleNode) != -1
cfg.Auth.Enabled = strings.Index(clf.Roles, defaults.RoleAuthService) != -1
cfg.Proxy.Enabled = strings.Index(clf.Roles, defaults.RoleProxy) != -1
}
// apply --auth-server flag:
if clf.AuthServerAddr != "" {
if cfg.Auth.Enabled {
log.Warnf("not starting the local auth service. --auth-server flag tells to connect to another auth server")
cfg.Auth.Enabled = false
}
addr, err := utils.ParseHostPortAddr(clf.AuthServerAddr, int(defaults.AuthListenPort))
if err != nil {
return trace.Wrap(err)
}
log.Infof("Using auth server: %v", addr.FullAddress())
cfg.AuthServers = []utils.NetAddr{*addr}
}
// apply --name flag:
if clf.NodeName != "" {
cfg.Hostname = clf.NodeName
}
// apply --token flag:
cfg.ApplyToken(clf.AuthToken)
// apply --listen-ip flag:
if clf.ListenIP != nil {
applyListenIP(clf.ListenIP, cfg)
}
// --advertise-ip flag
if clf.AdvertiseIP != nil {
if err := validateAdvertiseIP(clf.AdvertiseIP); err != nil {
return trace.Wrap(err)
}
cfg.AdvertiseIP = clf.AdvertiseIP
}
// apply --labels flag
if err = parseLabels(clf.Labels, &cfg.SSH); err != nil {
return trace.Wrap(err)
}
// locate web assets if web proxy is enabled
if cfg.Proxy.Enabled {
cfg.Proxy.AssetsDir, err = LocateWebAssets()
if err != nil {
return trace.Wrap(err)
}
}
// --pid-file:
if clf.PIDFile != "" {
cfg.PIDFile = clf.PIDFile
}
return nil
}
// parseLabels takes the value of --labels flag and tries to correctly populate
// sshConf.Labels and sshConf.CmdLabels
func parseLabels(spec string, sshConf *service.SSHConfig) error {
if spec == "" {
return nil
}
// base syntax parsing, the spec must be in the form of 'key=value,more="better"`
lmap, err := client.ParseLabelSpec(spec)
if err != nil {
return trace.Wrap(err)
}
if len(lmap) > 0 {
sshConf.CmdLabels = make(services.CommandLabels, 0)
sshConf.Labels = make(map[string]string, 0)
}
// see which labels are actually command labels:
for key, value := range lmap {
cmdLabel, err := isCmdLabelSpec(value)
if err != nil {
return trace.Wrap(err)
}
if cmdLabel != nil {
sshConf.CmdLabels[key] = *cmdLabel
} else {
sshConf.Labels[key] = value
}
}
return nil
}
// isCmdLabelSpec tries to interpret a given string as a "command label" spec.
// A command label spec looks like [time_duration:command param1 param2 ...] where
// time_duration is in "1h2m1s" form.
//
// Example of a valid spec: "[1h:/bin/uname -m]"
func isCmdLabelSpec(spec string) (*services.CommandLabel, error) {
// command spec? (surrounded by brackets?)
if len(spec) > 5 && spec[0] == '[' && spec[len(spec)-1] == ']' {
invalidSpecError := trace.BadParameter(
"invalid command label spec: '%s'", spec)
spec = strings.Trim(spec, "[]")
idx := strings.IndexRune(spec, ':')
if idx < 0 {
return nil, trace.Wrap(invalidSpecError)
}
periodSpec := spec[:idx]
period, err := time.ParseDuration(periodSpec)
if err != nil {
return nil, trace.Wrap(invalidSpecError)
}
cmdSpec := spec[idx+1:]
if len(cmdSpec) < 1 {
return nil, trace.Wrap(invalidSpecError)
}
var openQuote bool = false
return &services.CommandLabel{
Period: period,
Command: strings.FieldsFunc(cmdSpec, func(c rune) bool {
if c == '"' {
openQuote = !openQuote
}
return unicode.IsSpace(c) && !openQuote
}),
}, nil
}
// not a valid spec
return nil, nil
}
// applyListenIP replaces all 'listen addr' settings for all services with
// a given IP
func applyListenIP(ip net.IP, cfg *service.Config) {
listeningAddresses := []*utils.NetAddr{
&cfg.Auth.SSHAddr,
&cfg.Auth.SSHAddr,
&cfg.Proxy.SSHAddr,
&cfg.Proxy.WebAddr,
&cfg.SSH.Addr,
&cfg.Proxy.ReverseTunnelListenAddr,
}
for _, addr := range listeningAddresses {
replaceHost(addr, ip.String())
}
}
// replaceHost takes utils.NetAddr and replaces the hostname in it, preserving
// the original port
func replaceHost(addr *utils.NetAddr, newHost string) {
_, port, err := net.SplitHostPort(addr.Addr)
if err != nil {
log.Errorf("failed parsing address: '%v'", addr.Addr)
}
addr.Addr = net.JoinHostPort(newHost, port)
}
func fileExists(fp string) bool {
_, err := os.Stat(fp)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
// validateRoles makes sure that value upassed to --roles flag is valid
func validateRoles(roles string) error {
for _, role := range strings.Split(roles, ",") {
switch role {
case defaults.RoleAuthService,
defaults.RoleNode,
defaults.RoleProxy:
break
default:
return trace.Errorf("unknown role: '%s'", role)
}
}
return nil
}
func validateAdvertiseIP(advertiseIP net.IP) error {
if advertiseIP.IsLoopback() || advertiseIP.IsUnspecified() || advertiseIP.IsMulticast() {
return trace.BadParameter("unreachable advertise IP: %v", advertiseIP)
}
return nil
}
// DirsToLookForWebAssets defines the locations where teleport proxy looks for
// its web assets
var DirsToLookForWebAssets = []string{
"/usr/local/share/teleport",
"/usr/share/teleport",
"/opt/teleport",
}
// LocateWebAssets locates the web assets required for the Proxy to start. Retursn the full path
// to web assets directory
func LocateWebAssets() (string, error) {
const errorMessage = "Cannot determine location of web assets."
assetsToCheck := []string{
"index.html",
"/app/app.js",
}
// checker function to determine if dirPath contains the web assets
locateAssets := func(dirPath string) bool {
for _, af := range assetsToCheck {
if !fileExists(filepath.Join(dirPath, af)) {
return false
}
}
return true
}
// check the directory where teleport binary is located first:
exeDir, err := osext.ExecutableFolder()
if err != nil {
return "", trace.Wrap(err)
}
if locateAssets(exeDir) {
return exeDir, nil
}
// look in other possible locations:
for _, dir := range DirsToLookForWebAssets {
if locateAssets(dir) {
return dir, nil
}
}
return "",
trace.Errorf("Cannot find web assets. Unable to locate %v", filepath.Join(exeDir, assetsToCheck[0]))
}