This repository has been archived by the owner on Apr 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
okta.go
325 lines (265 loc) · 6.88 KB
/
okta.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
package main
import "fmt"
import "bytes"
import "io"
import "io/ioutil"
import "errors"
import "encoding/json"
import "encoding/xml"
import "encoding/base64"
import "github.com/tj/go-debug"
import "github.com/PuerkitoBio/goquery"
import (
"net/http"
"github.com/havoc-io/go-keytar"
)
var noMfaError = errors.New("MFA required to use this tool")
var wrongMfaError = errors.New("No valid mfa congfigured for your account!")
var loginFailedError = errors.New("login failed")
var debugOkta = debug.Debug("oktad:okta")
type OktaLoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Options map[string]interface{}
}
type OktaLoginResponse struct {
ExpiresAt string
SessionToken string
Status string
StateToken string
Embedded struct {
Factors []OktaMfaFactor
} `json:"_embedded"`
}
type OktaMfaFactor struct {
Id string
FactorType string
Provider string
Status string
Links map[string]HalLink `json:"_links"`
}
type HalLink struct {
Href string
}
// what the hell XML,
// what the hell.
type OktaSamlResponse struct {
raw string
XMLname xml.Name `xml:"Response"`
Attributes []struct {
Name string `xml:",attr"`
NameFormat string `xml:",attr"`
Value string `xml:"AttributeValue"`
} `xml:"Assertion>AttributeStatement>Attribute"`
}
func newLoginRequest(user, pass string) OktaLoginRequest {
return OktaLoginRequest{
user,
pass,
map[string]interface{}{
"multiOptionalFactorEnroll": false,
"warnBeforePasswordExpired": false,
},
}
}
// begins the login process by authenticating
// with okta
func login(cfg *OktaConfig, user, pass string) (*OktaLoginResponse, error) {
debugOkta("let the login dance begin")
pr, err := http.NewRequest(
http.MethodPost,
fmt.Sprintf(
// TODO: run some checks on this URL
"%sapi/v1/authn",
cfg.BaseURL,
),
getOktaLoginBody(cfg, user, pass),
)
if err != nil {
debugOkta("caught an error building the first request to okta")
return nil, err
}
ajs := "application/json"
pr.Header.Set("Content-Type", ajs)
pr.Header.Set("Accept", ajs)
res, err := http.DefaultClient.Do(pr)
if err != nil {
debugOkta("caught error on first request to okta")
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, loginFailedError
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
debugOkta("login response body %s", string(b))
var ores OktaLoginResponse
err = json.Unmarshal(b, &ores)
if err != nil {
return nil, err
}
return &ores, nil
}
// convenience function to get the request body for the okta request
// just need a buffer, man.
// or, really, an io.Reader
func getOktaLoginBody(cfg *OktaConfig, user, pass string) io.Reader {
return makeRequestBody(newLoginRequest(user, pass))
}
// turns a thing (a variable of some sort) into an io.Reader for
// reading into a request bodygit
func makeRequestBody(t interface{}) io.Reader {
debug := debug.Debug("oktad:makeRequestBody")
var b bytes.Buffer
enc := json.NewEncoder(&b)
err := enc.Encode(t)
if err != nil {
debug("Error encoding json! %s", err)
}
return &b
}
// pulls the factor we should use out of the response
func extractTokenFactor(ores *OktaLoginResponse) (*OktaMfaFactor, error) {
factors := ores.Embedded.Factors
if len(factors) == 0 {
return nil, errors.New("MFA factors not present in response")
}
var tokenFactor OktaMfaFactor
for _, factor := range factors {
// need to assert that this is a map
// since I don't know the structure enough
// to make a struct for it
if factor.FactorType == "token:software:totp" {
debugOkta("software totp token found!")
tokenFactor = factor
break
}
}
if tokenFactor.Id == "" {
return nil, wrongMfaError
}
return &tokenFactor, nil
}
// do that mfa stuff
//
// returns the okta session token and an error if any)
func doMfa(ores *OktaLoginResponse, tf *OktaMfaFactor, mfaToken string) (string, error) {
var url string
var st string
if ores == nil || tf == nil || mfaToken == "" {
return st, errors.New("invalid params!")
}
vObj, ok := tf.Links["verify"]
if !ok {
return st, errors.New("Invalid token factor, no 'verify' link found")
}
type body struct {
StateToken string `json:"stateToken"`
PassCode string `json:"passCode"`
}
url = vObj.Href
debugOkta("mfa verify url is %s", url)
req, _ := http.NewRequest(
"POST",
url,
makeRequestBody(body{ores.StateToken, mfaToken}),
)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return st, err
}
var mfares OktaLoginResponse
b, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
return st, err
}
err = json.Unmarshal(b, &mfares)
if err != nil {
return st, err
}
debugOkta("response body when MFAing was %s", string(b))
if mfares.Status != "SUCCESS" {
return st, errors.New("MFA did not succeed!")
}
st = mfares.SessionToken
return st, nil
}
// fetches the SAML we need for AWS round 1
func getSaml(cfg *OktaConfig, sessionToken string) (*OktaSamlResponse, error) {
res, err := http.Get(
fmt.Sprintf(
"%s?%s=%s",
cfg.AppURL,
"onetimetoken",
sessionToken,
),
)
if err != nil {
return nil, err
}
return processSamlResponse(res)
}
func getSamlSession(cfg *OktaConfig, cookie *http.Cookie) (*OktaSamlResponse, error) {
client := http.Client{}
req, err := http.NewRequest("GET", cfg.AppURL, nil)
req.AddCookie(cookie)
res, err := client.Do(req)
if err != nil {
return nil, err
}
return processSamlResponse(res)
}
func processSamlResponse(res *http.Response) (*OktaSamlResponse, error) {
var osres OktaSamlResponse
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return &osres, err
}
sel := doc.Find(`input[name="SAMLResponse"]`)
if sel.Length() < 1 {
debugOkta("didn't find saml response element")
return &osres, errors.New("Invalid saml response!")
}
saml, ok := sel.First().Attr("value")
if !ok {
return &osres, errors.New("Invalid saml response!")
}
osres.raw = saml
b, err := decodeBase64(saml)
if err != nil {
debugOkta("error decoding saml base64, %s", err)
return &osres, err
}
err = xml.Unmarshal(b, &osres)
if err != nil {
debugOkta("error decoding saml XML, %s", err)
return &osres, err
}
keyStore, err := keytar.GetKeychain()
if err != nil {
debugOkta("error getting keychain access %s", err)
}
var sessionCookie *http.Cookie
for _, cookie := range res.Cookies() {
if cookie.Name == "sid" {
sessionCookie = cookie
}
}
encCookie, err := encodePasswordStruct(sessionCookie)
if err != nil {
fmt.Println("Failed to write cookie to keystore")
debugOkta("error was %s", err)
}
keytar.ReplacePassword(keyStore, APPNAME, SESSION_COOKIE, encCookie)
return &osres, nil
}
func decodeBase64(b64 string) ([]byte, error) {
dec := base64.StdEncoding
return dec.DecodeString(b64)
}