-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
459 lines (398 loc) · 13.3 KB
/
main.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/bobziuchkovski/writ"
)
var (
out = os.Stdout
errout = os.Stderr
)
var version = ""
var date = ""
const (
configFilePath = ".limes/config"
domainSocketPath = ".limes/socket"
profileDefault = "default"
)
//go:generate protoc -I proto/ proto/ims.proto --go_out=plugins=grpc:proto
// add "port" to configuration file
// rewrite .aws/config to match current profile
// add assumable/protected directive
// limes up => start web server
// limes down => stop web server
//
// These are not well suited for multi-user systems
// ipfw show
// ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in
// ipfw flush
//
// iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
// iptables -t nat -I OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-ports 8080
// iptables -t nat --line-numbers -n -L
//
// pf on Mac
// echo "
// rdr pass inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080
// rdr pass inet proto tcp from any to any port 443 -> 127.0.0.1 port 8443
// " | sudo pfctl -ef
// Limes defines the cli commands
type Limes struct {
Start Start `command:"start" description:"Start the Instance Metadata Service"`
Stop Stop `command:"stop" description:"Stop the Instance Metadata Service"`
Status Status `command:"status" description:"Get current status of the service"`
SwitchProfile SwitchProfile `command:"assume" alias:"profile" description:"Assume IAM role"`
RunCmd RunCmd `command:"run" description:"Run a command with the specified profile"`
ShowCmd ShowCmd `command:"show" description:"List/show information"`
Env Env `command:"env" description:"Set/clear environment variables"`
Fix Fix `command:"fix" description:"Fix configuration"`
Profile string `option:"profile" default:"" description:"Profile to assume"`
ConfigFile string `option:"c, config" default:"" description:"Configuration file"`
Address string `option:"address" default:"" description:"Address to connect to"`
Logging bool `flag:"verbose" description:"Enable verbose output"`
Version bool `flag:"v" description:"Show version"`
}
// Start defines the "start" command cli flags and options
type Start struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
Fake bool `flag:"fake" description:"Do not connect to AWS"`
MFA string `option:"m, mfa" description:"MFA token to start up server"`
Port int `option:"p, port" default:"" description:"Port used by the metadata service, default: 80"`
}
// Stop defines the "stop" command cli flags and options
type Stop struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
}
// Status defines the "status" command cli flags and options
type Status struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
Verbose bool `flag:"v, verbose" description:"enables verbose output"`
}
// Fix defines the "fix" subcommand cli flags and options
type Fix struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
Restore bool `flag:"restore" description:"Restores AWS configuration files"`
}
// SwitchProfile defines the "profile" command cli flags and options
type SwitchProfile struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
}
// RunCmd defines the "run" command cli flags ands options
type RunCmd struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
Profile string `option:"profile" default:"" description:"Profile to assume"`
}
// ShowCmd defines the "show" command cli flags ands options
type ShowCmd struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
}
// Env defines the "env" subcommand cli flags and options
type Env struct {
HelpFlag bool `flag:"h, help" description:"Display this message and exit"`
Clear bool `flag:"clear" description:"Clear environment variables"`
}
// Run is the main cli handler
func (g *Limes) Run(cmd *Limes, p writ.Path, positional []string) {
if g.Version {
fmt.Printf("limes %v compiled on %v\n", version, date)
return
}
p.Last().ExitHelp(errors.New("COMMAND is required"))
}
// Run is the handler for the start command
func (l *Start) Run(cmd *Limes, p writ.Path, positional []string) {
if l.HelpFlag {
p.Last().ExitHelp(nil)
}
if cmd.Profile == "" {
cmd.Profile = profileDefault
}
StartService(cmd.ConfigFile, cmd.Address, cmd.Profile, l.MFA, l.Port, l.Fake)
}
// Run is the handler for the stop command
func (l *Stop) Run(cmd *Limes, p writ.Path, positional []string) {
if l.HelpFlag {
p.Last().ExitHelp(nil)
}
rpc := newCliClient(cmd.Address)
defer rpc.close()
rpc.stop(l)
}
// Run is the handler for the status command
func (l *Status) Run(cmd *Limes, p writ.Path, positional []string) {
if l.HelpFlag {
p.Last().ExitHelp(nil)
}
rpc := newCliClient(cmd.Address)
defer rpc.close()
rpc.printStatus(l)
}
// Run is the handler for the fix command
func (l *Fix) Run(cmd *Limes, p writ.Path, positional []string) {
if l.HelpFlag {
p.Last().ExitHelp(nil)
}
home, err := homeDir()
if err != nil {
fmt.Fprintf(errout, "unable to fetch user information: %v\n", err)
os.Exit(1)
}
exitOnErr := func(err error) {
if err != nil {
fmt.Fprintf(errout, "error: %v\n", err)
os.Exit(1)
}
}
exists := func(path string) bool {
_, staterr := os.Stat(path)
if staterr != nil {
return false
}
return true
}
if l.Restore == true {
originalPath := filepath.Join(home, awsConfDir, awsCredentialsFile)
movedPath := filepath.Join(home, awsConfDir, awsRenamePrefix+awsCredentialsFile)
fmt.Printf("loooking for: %v\n", movedPath)
if exists(movedPath) {
fmt.Fprintf(out, "# restoring: %v\n", originalPath)
exitOnErr(os.Rename(movedPath, originalPath))
}
originalPath = filepath.Join(home, awsConfDir, awsConfigFile)
movedPath = filepath.Join(home, awsConfDir, awsRenamePrefix+awsConfigFile)
fmt.Printf("loooking for: %v\n", movedPath)
if exists(movedPath) {
fmt.Fprintf(out, "# restoring: %v\n", originalPath)
exitOnErr(os.Rename(movedPath, originalPath))
}
return
}
if err = checkActiveAWSConfig(); err == nil {
fmt.Fprintf(out, "# configuration ok, nothing to fix\n")
os.Exit(0)
}
for err := checkActiveAWSConfig(); err != nil; err = checkActiveAWSConfig() {
switch err {
case errKeyPairInAWSCredentialsFile:
originalPath := filepath.Join(home, awsConfDir, awsCredentialsFile)
movedPath := filepath.Join(home, awsConfDir, awsRenamePrefix+awsCredentialsFile)
fmt.Fprintf(out, "# moving: %v => %v\n", originalPath, movedPath)
exitOnErr(os.Rename(originalPath, movedPath))
case errKeyPairInAWSConfigFile:
originalPath := filepath.Join(home, awsConfDir, awsConfigFile)
movedPath := filepath.Join(home, awsConfDir, awsRenamePrefix+awsConfigFile)
fmt.Fprintf(out, "# moving: %v => %v\n", originalPath, movedPath)
exitOnErr(os.Rename(originalPath, movedPath))
case errActiveAWSEnvironment:
fmt.Fprintf(out, "# You have active AWS Environment variables\n")
fmt.Fprintf(out, "# Either run the code bellow in your shell or excute it with\n")
fmt.Fprintf(out, "# eval \"$(limes fix)\"\n")
fmt.Fprintf(out, "unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN")
default:
fmt.Fprintf(out, "unable to fix: %v\n", err)
}
}
}
// Run is the handler for the profile command
func (l *SwitchProfile) Run(cmd *Limes, p writ.Path, positional []string) {
if l.HelpFlag {
p.Last().ExitHelp(nil)
}
if len(positional) != 1 {
p.Last().ExitHelp(errors.New("profile name is required"))
}
rpc := newCliClient(cmd.Address)
defer rpc.close()
rpc.assumeRole(positional[0], "")
}
// Run is the handler for the run command
func (l *RunCmd) Run(cmd *Limes, p writ.Path, positional []string) {
if l.HelpFlag || len(positional) == 0 {
p.Last().ExitHelp(nil)
}
command := exec.Command(positional[0], positional[1:]...)
rpc := newCliClient(cmd.Address)
defer rpc.close()
if cmd.Profile != "" {
creds, err := rpc.retreiveAWSEnv(cmd.Profile, "")
if err != nil {
fmt.Fprintf(errout, "error retreving profile: %v", err)
os.Exit(1)
}
command.Env = append(os.Environ(),
"AWS_ACCESS_KEY_ID="+creds.AccessKeyID,
"AWS_SECRET_ACCESS_KEY="+creds.SecretAccessKey,
"AWS_SESSION_TOKEN="+creds.SessionToken,
"AWS_DEFAULT_REGION="+creds.Region,
"AWS_REGION="+creds.Region,
)
} else {
r, err := rpc.status()
if err != nil || r.AccessKeyId == "" {
fmt.Fprintf(errout, "error retreving profile: %v", err)
os.Exit(1)
}
command.Env = append(os.Environ(),
"AWS_ACCESS_KEY_ID="+r.AccessKeyId,
"AWS_SECRET_ACCESS_KEY="+r.SecretAccessKey,
"AWS_SESSION_TOKEN="+r.SessionToken,
"AWS_DEFAULT_REGION="+r.Region,
"AWS_REGION="+r.Region,
)
}
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
err := command.Run()
if err != nil {
// TODO: Handle exit error
}
}
// Run is the handler for the show subcommand
func (l *ShowCmd) Run(cmd *Limes, p writ.Path, positional []string) {
options := []string{"profiles"}
msg := fmt.Errorf("valid components: %v\n", strings.Join(options, ", "))
if l.HelpFlag {
p.Last().ExitHelp(msg)
}
if len(positional) == 0 {
p.Last().ExitHelp(msg)
}
switch positional[0] {
case "profiles":
rpc := newCliClient(cmd.Address)
defer rpc.close()
roles, err := rpc.listRoles()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
fmt.Printf("%v\n", strings.Join(roles, "\n"))
default:
p.Last().ExitHelp(msg)
}
}
// Run is the handler for the env subcommand
func (l *Env) Run(cmd *Limes, p writ.Path, positional []string) {
if l.HelpFlag {
p.Last().ExitHelp(nil)
}
profile := ""
if cmd.Profile != "" {
profile = cmd.Profile
}
if len(positional) == 1 {
profile = positional[0]
}
rpc := newCliClient(cmd.Address)
defer rpc.close()
if profile == "" {
r, err := rpc.status()
if err != nil {
p.Last().ExitHelp(fmt.Errorf(lookupCorrection(err)))
}
profile = r.Role
if profile == "" {
p.Last().ExitHelp(nil)
}
}
credentials, err := rpc.retreiveAWSEnv(profile, "")
if err != nil {
fmt.Fprintf(errout, "error retreiving profile: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(out, "export AWS_ACCESS_KEY_ID=%v\n", credentials.AccessKeyID)
fmt.Fprintf(out, "export AWS_SECRET_ACCESS_KEY=%v\n", credentials.SecretAccessKey)
fmt.Fprintf(out, "export AWS_SESSION_TOKEN=%v\n", credentials.SessionToken)
fmt.Fprintf(out, "export AWS_DEFAULT_REGION=%v\n", credentials.Region)
fmt.Fprintf(out, "export AWS_REGION=%v\n", credentials.Region)
fmt.Fprintf(out, "# Run this command to configure your shell:\n")
fmt.Fprintf(out, "# eval \"$(limes env %s)\"\n", profile)
}
func setDefaultSocketAddress(address string) string {
if address != "" {
return address
}
home, err := homeDir()
if err != nil {
log.Fatalf("unable to extract user information: %v", err)
}
return filepath.Join(home, domainSocketPath)
}
func setDefaultConfigPath(path string) string {
if path != "" {
return path
}
home, err := homeDir()
if err != nil {
log.Fatalf("unable to extract user information: %v", err)
}
return filepath.Join(home, configFilePath)
}
func injectCmdBreak(needle string, args []string) []string {
ret := make([]string, 0, len(args)+1)
for _, arg := range os.Args {
ret = append(ret, arg)
if arg == needle {
ret = append(ret, "--")
}
}
return ret
}
func main() {
limes := &Limes{}
cmd := writ.New("limes", limes)
cmd.Help.Usage = "Usage: limes [OPTIONS]... COMMAND [OPTION]... [ARG]..."
cmd.Subcommand("start").Help.Usage = "Usage: limes start"
cmd.Subcommand("stop").Help.Usage = "Usage: limes stop"
cmd.Subcommand("status").Help.Usage = "Usage: limes status"
cmd.Subcommand("fix").Help.Usage = "Usage: limes fix [--restore]"
cmd.Subcommand("assume").Help.Usage = "Usage: limes assume <profile>"
cmd.Subcommand("show").Help.Usage = "Usage: limes show [component]"
cmd.Subcommand("env").Help.Usage = "Usage: limes env <profile>"
cmd.Subcommand("run").Help.Usage = "Usage: limes [--profile <name>] run <cmd> [arg...]"
path, positional, err := cmd.Decode(os.Args[1:])
if err != nil {
if path.String() != "limes run" {
path.Last().ExitHelp(err)
}
os.Args = injectCmdBreak("run", os.Args)
path, positional, err = cmd.Decode(os.Args[1:])
if err != nil {
path.Last().ExitHelp(err)
}
}
limes.Address = setDefaultSocketAddress(limes.Address)
limes.ConfigFile = setDefaultConfigPath(limes.ConfigFile)
if !limes.Logging {
log.SetOutput(ioutil.Discard)
}
switch path.String() {
case "limes":
limes.Run(limes, path, positional)
case "limes start":
limes.Start.Run(limes, path, positional)
case "limes stop":
limes.Stop.Run(limes, path, positional)
case "limes status":
limes.Status.Run(limes, path, positional)
case "limes fix":
limes.Fix.Run(limes, path, positional)
case "limes assume":
limes.SwitchProfile.Run(limes, path, positional)
case "limes show":
limes.ShowCmd.Run(limes, path, positional)
case "limes env":
limes.Env.Run(limes, path, positional)
case "limes run":
limes.RunCmd.Run(limes, path, positional)
default:
log.Fatalf("bug: sub command has not been setup: %v", path.String())
}
}