This repository has been archived by the owner on Feb 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
230 lines (204 loc) · 6.6 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
package main
/*
* OneLogin AWS Role
* Copyright (c) 2020-2021 Aaron Turner <aturner at synfin dot net>
*
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or with the authors permission any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import (
"fmt"
"github.com/Songmu/prompter"
"github.com/alecthomas/kong"
"github.com/davecgh/go-spew/spew"
log "github.com/sirupsen/logrus"
"github.com/synfinatic/onelogin-aws-role/aws"
"github.com/synfinatic/onelogin-aws-role/onelogin"
)
// These variables are defined in the Makefile
var Version = "unknown"
var Buildinfos = "unknown"
var Tag = "NO-TAG"
var CommitID = "unknown"
var Delta = ""
type RunContext struct {
OneLogin *onelogin.OneLogin
Kctx *kong.Context
Cli *CLI
Config *ConfigFile
}
type CLI struct {
// Common Arguments
LogLevel string `kong:"optional,short='L',name='loglevel',default='info',enum='error,warn,info,debug',help='Logging level [error|warn|info|debug]'"`
Lines bool `kong:"optional,name='lines',help='Print line number in logs'"`
// have to hard code CONFIG_YAML value here because no way to do string interpolation in a strcture tag.
ConfigFile string `kong:"optional,short='c',name='config',default='~/.onelogin-aws-role.yaml',help='Config file'"`
// AWS Params
Region string `kong:"optional,short='r',help='AWS Region',env='AWS_DEFAULT_REGION'"`
Duration int64 `kong:"optional,short='d',help='AWS Session duration in minutes (default 60)',default=60,env=ONELOGIN_AWS_DURATION"`
PromptMfa bool `kong:"optional,short='m',name='prompt-mfa',help='Force prompt for which MFA to use'"`
// Commands
// Role RoleCmd `kong:"cmd,help='Fetch & cache AWS STS Token for a given Role/Profile'"`
// App AppCmd `kong:"cmd,help='Fetch & cache all AWS STS Tokens for a given OneLogin AppID'"`
Exec ExecCmd `kong:"cmd,help='Execute command using specified AWS Role/Profile'"`
List ListCmd `kong:"cmd,help='List all role / appid aliases (default command)',default='1'"`
Oauth OauthCmd `kong:"cmd,help='Manage OneLogin Oauth credentials'"`
Expire ExpireCmd `kong:"cmd,help='Force expire of AWS Role/Profile credentials from keychain'"`
// Revoke -- much later
Version VersionCmd `kong:"cmd,help='Print version and exit'"`
}
func parse_args(cli *CLI) *kong.Context {
op := kong.Description("Utility to manage temporary AWS API Credentials issued via OneLogin")
ctx := kong.Parse(cli, op)
switch cli.LogLevel {
case "debug":
log.SetLevel(log.DebugLevel)
case "info":
log.SetLevel(log.InfoLevel)
case "warn":
log.SetLevel(log.WarnLevel)
case "error":
log.SetLevel(log.ErrorLevel)
}
if cli.Lines {
log.SetReportCaller(true)
}
return ctx
}
func main() {
cli := CLI{}
ctx := parse_args(&cli)
c, err := LoadConfigFile(GetPath(cli.ConfigFile))
if err != nil {
log.Fatalf("Unable to load config: %s", err.Error())
}
if cli.PromptMfa {
// forget we have a MFA defined
c.Mfa = 0
}
// c.MergeCLI(&cli)
run_ctx := RunContext{
OneLogin: nil,
Kctx: ctx,
Cli: &cli,
Config: c,
}
err = ctx.Run(&run_ctx)
if err != nil {
log.Fatalf("Error running command: %s", err.Error())
}
}
func GetSession(ctx *RunContext, profile string) (aws.STSSession, error) {
session := aws.STSSession{}
kr, err := OpenKeyring(nil)
if err != nil {
log.WithError(err).Warn("Unable to retrieve STS Session from Keychain")
} else {
err = kr.GetSTSSession(profile, &session)
if err != nil {
log.WithError(err).Warn("Unable to read STS Session from Keychain")
}
if session.Expired() {
log.Warn("Cached STS SessionToken has expired")
}
}
if session.Expired() {
session, err = Login(ctx, profile)
if err != nil {
log.WithError(err).Fatal("Unable to get STSSession")
}
err = kr.SaveSTSSession(profile, session)
if err != nil {
log.WithError(err).Warn("Unable to cache STS Session in Keychain")
}
}
return session, nil
}
func Login(ctx *RunContext, profile string) (aws.STSSession, error) {
cli := *ctx.Cli
kr, err := OpenKeyring(nil)
if err != nil {
return aws.STSSession{}, fmt.Errorf("Unable to open KeyChain for OneLogin Oauth: %s", err)
}
oauth := OauthConfig{}
err = kr.GetOauthConfig(&oauth)
if err != nil {
return aws.STSSession{}, fmt.Errorf("Please configure Oauth credentials")
}
o, err := onelogin.NewOneLogin(oauth.ClientId, oauth.Secret, ctx.Config.Region)
if err != nil {
log.WithError(err).Fatal("Unable to connect to OneLogin")
}
log.Debugf("config = %s", spew.Sdump(ctx.Config))
appid, err := ctx.Config.GetAppIdForRole(profile)
if err != nil {
return aws.STSSession{}, err
}
ols := &onelogin.OneLoginSAML{}
need_mfa := false
passwd_auth_pass := false
for !passwd_auth_pass {
passwd := prompter.Password("Enter your OneLogin password")
if passwd == "" {
return aws.STSSession{}, fmt.Errorf("OneLogin authentication aborted")
}
ols = onelogin.NewOneLoginSAML(o)
need_mfa, err = ols.GetAssertion(ctx.Config.Username, passwd, ctx.Config.Subdomain, appid, "")
if err == nil {
passwd_auth_pass = true
}
}
if need_mfa {
fmt.Printf("MFA Required\n")
success, err := ols.SubmitMFA(ctx.Config.Mfa, appid)
if err != nil {
log.Fatal(err)
}
if !success {
log.Fatalf("MFA auth failed.")
}
}
assertion, err := ols.OneLogin.Cache.GetAssertion(appid)
if err != nil {
log.Fatalf("Unable to get SAML Assertion: %s", err.Error())
} else {
log.Debugf("Got SAML Assertion:\n%s", assertion)
}
role, err := ctx.Config.GetRoleArn(profile)
if err != nil {
log.Fatal(err)
}
var region string
if cli.Region != "" {
region = cli.Region
} else {
region, err = ctx.Config.GetRoleRegion(profile)
if err != nil {
log.WithError(err).Warn("Unable to set default AWS region, falling back to us-east-1")
region = "us-east-1"
}
}
return aws.GetSTSSession(assertion, role, region, cli.Duration*60)
}
type VersionCmd struct {
}
func (cc *VersionCmd) Run(ctx *RunContext) error {
delta := ""
if len(Delta) > 0 {
delta = fmt.Sprintf(" [%s delta]", Delta)
Tag = "Unknown"
}
fmt.Printf("OneLogin AWS Role Version %s%s -- Copyright 2021 Aaron Turner\n", Version, delta)
fmt.Printf("%s (%s) built at %s\n", CommitID, Tag, Buildinfos)
return nil
}