forked from segmentio/aws-okta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
duo.go
282 lines (231 loc) · 7.05 KB
/
duo.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
package lib
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
uniformResourceLocator "net/url"
"golang.org/x/net/html"
)
type DuoClient struct {
Host string
Signature string
Callback string
StateToken string
}
type StatusResp struct {
Response struct {
U2FSignRequest []struct {
Version string `json:"version"`
Challenge string `json:"challenge"`
AppID string `json:"appId"`
KeyHandle string `json:"keyHandle"`
SessionID string `json:"sessionId"`
} `json:"u2f_sign_request"`
Status string `json:"status"`
StatusCode string `json:"status_code"`
Reason string `json:"reason"`
Parent string `json:"parent"`
Cookie string `json:"cookie"`
Result string `json:"result"`
} `json:"response"`
Stat string `json:"stat"`
}
type PromptResp struct {
Response struct {
Txid string `json:"txid"`
} `json:"response"`
Stat string `json:"stat"`
}
func NewDuoClient(host, signature, callback string) *DuoClient {
return &DuoClient{
Host: host,
Signature: signature,
Callback: callback,
}
}
// ChallengeU2F performs multiple call against an obscure Duo API.
//
// Normally you use an iframe to perform those calls but here the main idea is
// to fake Duo is order to use the CLI without any browser.
//
// The function perform three successive calls to retry the challenge data.
// Wait for the user to perform the verification (Duo Push or Yubikey). And then
// call the callback url.
//
// TODO: Use a Context to gracefully shutdown the thing and have a nice timeout
func (d *DuoClient) ChallengeU2f() (err error) {
var sid, tx, txid, auth string
tx = strings.Split(d.Signature, ":")[0]
sid, err = d.DoAuth(tx, "", "")
if err != nil {
return
}
txid, err = d.DoPrompt(sid)
if err != nil {
return
}
_, err = d.DoStatus(txid, sid)
if err != nil {
return
}
// This one should block untile 2fa completed
auth, err = d.DoStatus(txid, sid)
if err != nil {
return
}
err = d.DoCallback(auth)
if err != nil {
return
}
return
}
// DoAuth sends a POST request to the Duo /frame/web/v1/auth endpoint.
// The request will not follow the redirect and retrieve the location from the HTTP header.
// From the Location we get the Duo Session ID (sid) required for the rest of the communication.
// In some integrations of Duo, an empty POST to the Duo /frame/web/v1/auth endpoint will return
// StatusOK with a form of hidden inputs. In that case, we redo the POST with data from the
// hidden inputs, which triggers the usual redirect/location flow and allows for a successful
// authentication.
//
// The function will return the sid
func (d *DuoClient) DoAuth(tx string, inputSid string, inputCertsURL string) (sid string, err error) {
var req *http.Request
var location string
url := fmt.Sprintf(
"https://%s/frame/web/v1/auth?tx=%s&parent=http://0.0.0.0:3000/duo&v=2.1",
d.Host, tx,
)
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
data := uniformResourceLocator.Values{}
if inputSid != "" && inputCertsURL != "" {
data.Set("sid", inputSid)
data.Set("certs_url", inputCertsURL)
}
req, err = http.NewRequest("POST", url, strings.NewReader(data.Encode()))
if err != nil {
return
}
req.Header.Add("Origin", "https://"+d.Host)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode == http.StatusFound {
location = res.Header.Get("Location")
if location != "" {
sid = strings.Split(location, "=")[1]
} else {
err = fmt.Errorf("Location not part of the auth header. Authentication failed ?")
}
} else if res.StatusCode == http.StatusOK && inputCertsURL == "" && inputSid == "" {
doc, err := html.Parse(res.Body)
if err != nil {
err = fmt.Errorf("Can't parse response")
}
sid, _ = GetNode(doc, "sid")
certsURL, _ := GetNode(doc, "certs_url")
sid, err = d.DoAuth(tx, sid, certsURL)
} else {
err = fmt.Errorf("Request failed or followed redirect: %d", res.StatusCode)
}
return
}
// DoPrompt sends a POST request to the Duo /frame/promt endpoint
//
// The functions returns the Duo transaction ID which is different from
// the Okta transaction ID
func (d *DuoClient) DoPrompt(sid string) (txid string, err error) {
var req *http.Request
url := "https://" + d.Host + "/frame/prompt"
client := &http.Client{}
//TODO: Here we automatically use Duo Push. The user should be able to choose
//between Duo Push and the Yubikey ("&device=u2f_token&factor=U2F+Token")
promptData := "sid=" + sid + "&device=phone1&factor=Duo+Push&out_of_date=False"
req, err = http.NewRequest("POST", url, bytes.NewReader([]byte(promptData)))
if err != nil {
return
}
req.Header.Add("Origin", "https://"+d.Host)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("X-Requested-With", "XMLHttpRequest")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("Prompt request failed: %d", res.StatusCode)
return
}
var status PromptResp
err = json.NewDecoder(res.Body).Decode(&status)
txid = status.Response.Txid
return
}
// DoStatus sends a POST request against the Duo /frame/status endpoint
//
// The function returns the auth string required for the Okta Callback if
// the request succeeded.
func (d *DuoClient) DoStatus(txid, sid string) (auth string, err error) {
var req *http.Request
url := "https://" + d.Host + "/frame/status"
client := &http.Client{}
statusData := "sid=" + sid + "&txid=" + txid
req, err = http.NewRequest("POST", url, bytes.NewReader([]byte(statusData)))
if err != nil {
return
}
req.Header.Add("Origin", "https://"+d.Host)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("X-Requested-With", "XMLHttpRequest")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("Prompt request failed: %d", res.StatusCode)
return
}
var status StatusResp
err = json.NewDecoder(res.Body).Decode(&status)
if status.Response.Result == "SUCCESS" {
auth = status.Response.Cookie
}
return
}
// DoCallback send a POST request to the Okta callback url defined in the DuoClient
//
// The callback request requires the stateToken from Okta and a sig_response built
// from the precedent requests.
func (d *DuoClient) DoCallback(auth string) (err error) {
var app string
var req *http.Request
app = strings.Split(d.Signature, ":")[1]
sigResp := auth + ":" + app
client := &http.Client{}
callbackData := "stateToken=" + d.StateToken + "&sig_response=" + sigResp
req, err = http.NewRequest("POST", d.Callback, bytes.NewReader([]byte(callbackData)))
if err != nil {
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("Prompt request failed: %d", res.StatusCode)
return
}
return
}