-
Notifications
You must be signed in to change notification settings - Fork 0
/
tctl.go
198 lines (172 loc) · 5.76 KB
/
tctl.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
/*
Copyright 2015-2017 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 common
import (
"fmt"
"os"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/config"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/service"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/kingpin"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
// GlobalCLIFlags keeps the CLI flags that apply to all tctl commands
type GlobalCLIFlags struct {
Debug bool
ConfigFile string
ConfigString string
}
// CLICommand interface must be implemented by every CLI command
//
// This allows OSS and Enterprise Teleport editions to plug their own
// implementations of different CLI commands into the common execution
// framework
//
type CLICommand interface {
// Initialize allows a caller-defined command to plug itself into CLI
// argument parsing
Initialize(*kingpin.Application, *service.Config)
// TryRun is executed after the CLI parsing is done. The command must
// determine if selectedCommand belongs to it and return match=true
TryRun(selectedCommand string, c *auth.TunClient) (match bool, err error)
}
// Run() is the same as 'make'. It helps to share the code between different
// "distributions" like OSS or Enterprise
//
// distribution: name of the Teleport distribution
func Run(distro teleport.DistroType, commands []CLICommand) {
utils.InitLogger(utils.LoggingForCLI, logrus.WarnLevel)
lib.SetDistroType(distro)
// app is the command line parser
app := utils.InitCLIParser("tctl", GlobalHelpString)
// cfg (teleport auth server configuration) is going to be shared by all
// commands
cfg := service.MakeDefaultConfig()
// each command will add itself to the CLI parser:
for i := range commands {
commands[i].Initialize(app, cfg)
}
// these global flags apply to all commands
var ccf GlobalCLIFlags
app.Flag("debug", "Enable verbose logging to stderr").
Short('d').
BoolVar(&ccf.Debug)
app.Flag("config", fmt.Sprintf("Path to a configuration file [%v]", defaults.ConfigFilePath)).
Short('c').
ExistingFileVar(&ccf.ConfigFile)
app.Flag("config-string",
"Base64 encoded configuration string").Hidden().Envar(defaults.ConfigEnvar).StringVar(&ccf.ConfigString)
// "version" command is always available:
ver := app.Command("version", "Print the version.")
app.HelpFlag.Short('h')
// parse CLI commands+flags:
selectedCmd, err := app.Parse(os.Args[1:])
if err != nil {
utils.FatalError(err)
}
// "version" command?
if selectedCmd == ver.FullCommand() {
utils.PrintVersion(distro)
return
}
// configure all commands with Teleport configuration (they share 'cfg')
applyConfig(&ccf, cfg)
// connect to the auth sever:
client, err := connectToAuthService(cfg)
if err != nil {
utils.FatalError(err)
}
// execute whatever is selected:
var match bool
for _, c := range commands {
match, err = c.TryRun(selectedCmd, client)
if err != nil {
utils.FatalError(err)
}
if match {
break
}
}
}
// connectToAuthService creates a valid client connection to the auth service
func connectToAuthService(cfg *service.Config) (client *auth.TunClient, err error) {
// connect to the local auth server by default:
cfg.Auth.Enabled = true
if len(cfg.AuthServers) == 0 {
cfg.AuthServers = []utils.NetAddr{
*defaults.AuthConnectAddr(),
}
}
// read the host SSH keys and use them to open an SSH connection to the auth service
i, err := auth.ReadIdentity(cfg.DataDir, auth.IdentityID{Role: teleport.RoleAdmin, HostUUID: cfg.HostUUID})
if err != nil {
// the "admin" identity is not present? this means the tctl is running NOT on the auth server.
if trace.IsNotFound(err) {
return nil, trace.AccessDenied("tctl must be used on the auth server")
}
return nil, trace.Wrap(err)
}
client, err = auth.NewTunClient(
"tctl",
cfg.AuthServers,
cfg.HostUUID,
[]ssh.AuthMethod{ssh.PublicKeys(i.KeySigner)})
if err != nil {
return nil, trace.Wrap(err)
}
// check connectivity by calling something on a clinet:
_, err = client.GetDialer()()
if err != nil {
utils.Consolef(os.Stderr,
"Cannot connect to the auth server: %v.\nIs the auth server running on %v?", err, cfg.AuthServers[0].Addr)
os.Exit(1)
}
return client, nil
}
// applyConfig takes configuration values from the config file and applies
// them to 'service.Config' object
func applyConfig(ccf *GlobalCLIFlags, cfg *service.Config) error {
// load /etc/teleport.yaml and apply it's values:
fileConf, err := config.ReadConfigFile(ccf.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 ccf.ConfigString != "" {
fileConf, err = config.ReadFromString(ccf.ConfigString)
if err != nil {
return trace.Wrap(err)
}
}
if err = config.ApplyFileConfig(fileConf, cfg); err != nil {
return trace.Wrap(err)
}
// --debug flag
if ccf.Debug {
utils.InitLogger(utils.LoggingForCLI, logrus.DebugLevel)
logrus.Debugf("DEBUG loggign enabled")
}
// read a host UUID for this node
cfg.HostUUID, err = utils.ReadHostUUID(cfg.DataDir)
if err != nil {
utils.FatalError(err)
}
return nil
}