forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_command.go
208 lines (175 loc) · 5.84 KB
/
token_command.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
/*
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"
"sort"
"strings"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/asciitable"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/service"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/gravitational/kingpin"
)
// TokenCommand implements `tctl token` group of commands
type TokenCommand struct {
config *service.Config
// tokenType is the type of token. For example, "trusted_cluster".
tokenType string
// Value is the value of the token. Can be used to either act on a
// token (for example, delete a token) or used to create a token with a
// specific value.
value string
// ttl is how long the token will live for.
ttl time.Duration
// tokenAdd is used to add a token.
tokenAdd *kingpin.CmdClause
// tokenDel is used to delete a token.
tokenDel *kingpin.CmdClause
// tokenList is used to view all tokens that Teleport knows about.
tokenList *kingpin.CmdClause
}
// Initialize allows TokenCommand to plug itself into the CLI parser
func (c *TokenCommand) Initialize(app *kingpin.Application, config *service.Config) {
c.config = config
tokens := app.Command("tokens", "List or revoke invitation tokens")
// tctl tokens add ..."
c.tokenAdd = tokens.Command("add", "Create a invitation token")
c.tokenAdd.Flag("type", "Type of token to add").Required().StringVar(&c.tokenType)
c.tokenAdd.Flag("value", "Value of token to add").StringVar(&c.value)
c.tokenAdd.Flag("ttl", fmt.Sprintf("Set expiration time for token, default is %v hour, maximum is %v hours",
int(defaults.SignupTokenTTL/time.Hour), int(defaults.MaxSignupTokenTTL/time.Hour))).
Default(fmt.Sprintf("%v", defaults.SignupTokenTTL)).DurationVar(&c.ttl)
// "tctl tokens rm ..."
c.tokenDel = tokens.Command("rm", "Delete/revoke an invitation token").Alias("del")
c.tokenDel.Arg("token", "Token to delete").StringVar(&c.value)
// "tctl tokens ls"
c.tokenList = tokens.Command("ls", "List node and user invitation tokens")
}
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it.
func (c *TokenCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error) {
switch cmd {
case c.tokenAdd.FullCommand():
err = c.Add(client)
case c.tokenDel.FullCommand():
err = c.Del(client)
case c.tokenList.FullCommand():
err = c.List(client)
default:
return false, nil
}
return true, trace.Wrap(err)
}
// Add is called to execute "tokens add ..." command.
func (c *TokenCommand) Add(client auth.ClientI) error {
// Parse string to see if it's a type of role that Teleport supports.
roles, err := teleport.ParseRoles(c.tokenType)
if err != nil {
return trace.Wrap(err)
}
// Generate token.
token, err := client.GenerateToken(auth.GenerateTokenRequest{
Roles: roles,
TTL: c.ttl,
Token: c.value,
})
if err != nil {
return trace.Wrap(err)
}
// Calculate the CA pin for this cluster. The CA pin is used by the client
// to verify the identity of the Auth Server.
caPin, err := calculateCAPin(client)
if err != nil {
return trace.Wrap(err)
}
// Get list of auth servers. Used to print friendly signup message.
authServers, err := client.GetAuthServers()
if err != nil {
return trace.Wrap(err)
}
if len(authServers) == 0 {
return trace.Errorf("this cluster has no auth servers")
}
// Print signup message.
switch {
case roles.Include(teleport.RoleTrustedCluster), roles.Include(teleport.LegacyClusterTokenType):
fmt.Printf(trustedClusterMessage,
token,
int(c.ttl.Minutes()))
default:
fmt.Printf(nodeMessage,
token,
int(c.ttl.Minutes()),
strings.ToLower(roles.String()),
token,
caPin,
authServers[0].GetAddr(),
int(c.ttl.Minutes()),
authServers[0].GetAddr())
}
return nil
}
// Del is called to execute "tokens del ..." command.
func (c *TokenCommand) Del(client auth.ClientI) error {
if c.value == "" {
return trace.Errorf("Need an argument: token")
}
if err := client.DeleteToken(c.value); err != nil {
return trace.Wrap(err)
}
fmt.Printf("Token %s has been deleted\n", c.value)
return nil
}
// List is called to execute "tokens ls" command.
func (c *TokenCommand) List(client auth.ClientI) error {
tokens, err := client.GetTokens()
if err != nil {
return trace.Wrap(err)
}
if len(tokens) == 0 {
fmt.Println("No active tokens found.")
return nil
}
// Sort by expire time.
sort.Slice(tokens, func(i, j int) bool { return tokens[i].Expires.Unix() < tokens[j].Expires.Unix() })
tokensView := func() string {
table := asciitable.MakeTable([]string{"Token", "Type", "Expiry Time (UTC)"})
for _, t := range tokens {
expiry := "never"
if t.Expires.Unix() > 0 {
expiry = t.Expires.Format(time.RFC822)
}
table.AddRow([]string{t.Token, t.Roles.String(), expiry})
}
return table.AsBuffer().String()
}
fmt.Printf(tokensView())
return nil
}
// calculateCAPin returns the SKPI pin for the local cluster.
func calculateCAPin(client auth.ClientI) (string, error) {
localCA, err := client.GetClusterCACert()
if err != nil {
return "", trace.Wrap(err)
}
tlsCA, err := tlsca.ParseCertificatePEM(localCA.TLSCA)
if err != nil {
return "", trace.Wrap(err)
}
return utils.CalculateSKPI(tlsCA), nil
}