-
Notifications
You must be signed in to change notification settings - Fork 0
/
shibboleth.go
355 lines (281 loc) · 9.44 KB
/
shibboleth.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
package shibboleth
import (
"crypto/tls"
"fmt"
"html"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/versent/saml2aws/pkg/cfg"
"github.com/versent/saml2aws/pkg/creds"
"github.com/versent/saml2aws/pkg/prompter"
"github.com/versent/saml2aws/pkg/provider"
)
var logger = logrus.WithField("provider", "shibboleth")
// Client wrapper around Shibboleth enabling authentication and retrieval of assertions
type Client struct {
client *provider.HTTPClient
idpAccount *cfg.IDPAccount
}
// New create a new Shibboleth client
func New(idpAccount *cfg.IDPAccount) (*Client, error) {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: idpAccount.SkipVerify, Renegotiation: tls.RenegotiateFreelyAsClient},
}
client, err := provider.NewHTTPClient(tr)
if err != nil {
return nil, errors.Wrap(err, "error building http client")
}
return &Client{
client: client,
idpAccount: idpAccount,
}, nil
}
// Authenticate authenticate to Shibboleth and return the data from the body of the SAML assertion.
func (sc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) {
var authSubmitURL string
var samlAssertion string
shibbolethURL := fmt.Sprintf("%s/idp/profile/SAML2/Unsolicited/SSO?providerId=%s", loginDetails.URL, sc.idpAccount.AmazonWebservicesURN)
res, err := sc.client.Get(shibbolethURL)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving form")
}
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return samlAssertion, errors.Wrap(err, "failed to build document from response")
}
authForm := url.Values{}
doc.Find("input").Each(func(i int, s *goquery.Selection) {
updateFormData(authForm, s, loginDetails)
})
doc.Find("form").Each(func(i int, s *goquery.Selection) {
action, ok := s.Attr("action")
if !ok {
return
}
authSubmitURL = action
})
if authSubmitURL == "" {
return samlAssertion, fmt.Errorf("unable to locate IDP authentication form submit URL")
}
req, err := http.NewRequest("POST", authSubmitURL, strings.NewReader(authForm.Encode()))
if err != nil {
return samlAssertion, errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.URL.Host = res.Request.URL.Host
req.URL.Scheme = res.Request.URL.Scheme
res, err = sc.client.Do(req)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving login form results")
}
switch sc.idpAccount.MFA {
case "Auto":
b, _ := ioutil.ReadAll(res.Body)
mfaRes, err := verifyMfa(sc, loginDetails.URL, string(b))
if err != nil {
return mfaRes.Status, errors.Wrap(err, "error verifying MFA results")
}
doc, err = goquery.NewDocumentFromResponse(mfaRes)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retrieving mfa form results")
}
}
doc.Find("input").Each(func(i int, s *goquery.Selection) {
name, ok := s.Attr("name")
if !ok {
log.Fatalf("unable to locate IDP authentication form submit URL")
}
if name == "SAMLResponse" {
val, ok := s.Attr("value")
if !ok {
log.Fatalf("unable to locate saml assertion value")
}
samlAssertion = val
}
})
return samlAssertion, nil
}
func updateFormData(authForm url.Values, s *goquery.Selection, user *creds.LoginDetails) {
name, ok := s.Attr("name")
authForm.Add("_eventId_proceed", "")
if !ok {
return
}
lname := strings.ToLower(name)
if strings.Contains(lname, "user") {
authForm.Add(name, user.Username)
} else if strings.Contains(lname, "email") {
authForm.Add(name, user.Username)
} else if strings.Contains(lname, "pass") {
authForm.Add(name, user.Password)
} else {
// pass through any hidden fields
val, ok := s.Attr("value")
if !ok {
return
}
authForm.Add(name, val)
}
}
func verifyMfa(oc *Client, shibbolethHost string, resp string) (*http.Response, error) {
tx, app, duoHost, dpa := parseTokens(resp)
// initiate duo mfa to get sid
duoSubmitURL := fmt.Sprintf("https://%s/frame/web/v1/auth", duoHost)
duoForm := url.Values{}
duoForm.Add("parent", dpa)
duoForm.Add("java_version", "")
duoForm.Add("java_version", "")
duoForm.Add("flash_version", "")
duoForm.Add("screen_resolution_width", "3008")
duoForm.Add("screen_resolution_height", "1692")
duoForm.Add("color_depth", "24")
req, err := http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return nil, errors.Wrap(err, "error building authentication request")
}
q := req.URL.Query()
q.Add("tx", tx)
req.URL.RawQuery = q.Encode()
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := oc.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error retrieving verify response")
}
//try to extract sid
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return nil, errors.Wrap(err, "error parsing document")
}
duoSID, ok := doc.Find("input[name=\"sid\"]").Attr("value")
if !ok {
return nil, errors.Wrap(err, "unable to locate saml response")
}
duoSID = html.UnescapeString(duoSID)
//prompt for mfa type
//only supporting push or passcode for now
var token string
var duoMfaOptions = []string{
"Duo Push",
"Passcode",
"Phone Call",
}
duoMfaOption := prompter.Choose("Select a DUO MFA Option", duoMfaOptions)
if duoMfaOptions[duoMfaOption] == "Passcode" {
//get users DUO MFA Token
token = prompter.StringRequired("Enter passcode")
}
// send mfa auth request
duoSubmitURL = fmt.Sprintf("https://%s/frame/prompt", duoHost)
duoForm = url.Values{}
duoForm.Add("sid", duoSID)
duoForm.Add("device", "phone1")
duoForm.Add("factor", duoMfaOptions[duoMfaOption])
duoForm.Add("out_of_date", "false")
if duoMfaOptions[duoMfaOption] == "Passcode" {
duoForm.Add("passcode", token)
}
req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return nil, errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error retrieving verify response")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
duoTxStat := gjson.Get(resp, "stat").String()
duoTxID := gjson.Get(resp, "response.txid").String()
if duoTxStat != "OK" {
return nil, errors.Wrap(err, "error authenticating mfa device")
}
// // get duo cookie
duoSubmitURL = fmt.Sprintf("https://%s/frame/status", duoHost)
duoForm = url.Values{}
duoForm.Add("sid", duoSID)
duoForm.Add("txid", duoTxID)
req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return nil, errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrap(err, "error retrieving body from response")
}
resp = string(body)
duoTxResult := gjson.Get(resp, "response.result").String()
duoTxCookie := gjson.Get(resp, "response.cookie").String()
if duoTxResult != "SUCCESS" {
//poll as this is likely a push request
for {
time.Sleep(3 * time.Second)
req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode()))
if err != nil {
return nil, errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = oc.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error retrieving verify response")
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrap(err, "error retrieving body from response")
}
resp := string(body)
duoTxResult = gjson.Get(resp, "response.result").String()
duoTxCookie = gjson.Get(resp, "response.cookie").String()
fmt.Println(gjson.Get(resp, "response.status").String())
if duoTxResult == "FAILURE" {
return nil, errors.Wrap(err, "failed to authenticate device")
}
if duoTxResult == "SUCCESS" {
break
}
}
}
idpForm := url.Values{}
idpForm.Add("_eventId", "proceed")
idpForm.Add("sig_response", duoTxCookie+":"+app)
req, err = http.NewRequest("POST", dpa, strings.NewReader(idpForm.Encode()))
if err != nil {
return nil, errors.Wrap(err, "error posting multi-factor verification to shibboleth server")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.URL.Scheme = "https"
req.URL.Host = strings.Replace(shibbolethHost, "https://", "", -1)
res, err = oc.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error retrieving verify response")
}
return res, errors.New("no mfa options provided")
}
func parseTokens(blob string) (string, string, string, string) {
hostRgx := regexp.MustCompile(`data-host=\"(.*?)\"`)
sigRgx := regexp.MustCompile(`data-sig-request=\"(.*?)\"`)
dpaRgx := regexp.MustCompile(`data-post-action=\"(.*?)\"`)
rs := sigRgx.FindStringSubmatch(blob)
host := hostRgx.FindStringSubmatch(blob)
dpa := dpaRgx.FindStringSubmatch(blob)
duoSignatures := strings.Split(rs[1], ":")
return duoSignatures[0], duoSignatures[1], host[1], dpa[1]
}