forked from anoop2811/saml2aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pingone.go
463 lines (374 loc) · 12.6 KB
/
pingone.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
460
461
462
463
package pingone
import (
"fmt"
"net/http"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"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", "pingone")
// Client wrapper around PingOne + PingID enabling authentication and retrieval of assertions
type Client struct {
client *provider.HTTPClient
idpAccount *cfg.IDPAccount
lastAccessUrl *url.URL
}
// New create a new PingOne client
func New(idpAccount *cfg.IDPAccount) (*Client, error) {
tr := provider.NewDefaultTransport(idpAccount.SkipVerify)
client, err := provider.NewHTTPClient(tr)
if err != nil {
return nil, errors.Wrap(err, "error building http client")
}
//disable default behaviour to follow redirects as we use this to detect mfa
client.DisableFollowRedirect()
return &Client{
client: client,
idpAccount: idpAccount,
//mfaRequired: false,
}, nil
}
func (ac *Client) EnableFollowRedirect() {
ac.client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
ac.lastAccessUrl = req.URL
return nil
}
}
// Authenticate Authenticate to PingOne and return the data from the body of the SAML assertion.
func (ac *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) {
// Access to PingOne
authSubmitURL, authForm, err := ac.getLoginForm(loginDetails)
if err != nil {
return "", errors.Wrap(err, "error retrieving login form")
}
// Access to PingFederate
req, err := http.NewRequest("POST", authSubmitURL, strings.NewReader(authForm.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := ac.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving login form")
}
// parse form for action(url), SAMLREquest, RelayState
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return "", errors.Wrap(err, "error parsing document")
}
postUrl, formData, err := parseSAMLResponseForm(doc)
if err != nil {
return "", errors.Wrap(err, "error parse SAMLResponse form")
}
// Redirect from PingFederate to PingOne
ac.client.DisableFollowRedirect()
req, err = http.NewRequest("POST", postUrl, strings.NewReader(formData.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request to PingOne")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = ac.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving login form")
}
// parse form for action(url), ppm_request, etc
doc, err = goquery.NewDocumentFromResponse(res)
if err != nil {
return "", errors.Wrap(err, "error parsing document")
}
postUrl, formData, err = parsePpmRequestForm(doc)
if err != nil {
return "", errors.Wrap(err, "error parse ppm_request form")
}
// post to /pingid/ppm/auth
res, err = ac.client.PostForm(postUrl, formData)
if err != nil {
return "", errors.Wrap(err, "error retrieving login form")
}
//extract form action and jwt token
form, actionURL, err := extractFormData(res)
if err != nil {
return "", errors.Wrap(err, "error extracting mfa form data")
}
//request mfa auth via PingId (device swipe) /pingid/ppm/auth/poll
req, err = http.NewRequest("POST", actionURL, strings.NewReader(form.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building mfa authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = ac.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error retrieving mfa response")
}
doc, err = goquery.NewDocumentFromResponse(res)
if err != nil {
return "", errors.Wrap(err, "failed to build document from response")
}
//extract form action and csrf token
form, actionURL, err = extractMfaFormData(doc)
if err != nil {
return "", errors.Wrap(err, "error extracting authentication form")
}
logger.WithField("actionURL", actionURL).WithField("form", form).Debug("extract mfa form")
//contine mfa auth with csrf token
req, err = http.NewRequest("POST", actionURL, strings.NewReader(form.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// accept mfa
res, err = ac.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error polling mfa device")
}
//user has disabled swipe
if strings.Contains(actionURL, "/pingid/ppm/auth/otp") {
token := prompter.StringRequired("Enter passcode")
//build request
otpReq := url.Values{}
otpReq.Add("otp", token)
otpReq.Add("message", "")
//submit otp
req, err = http.NewRequest("POST", actionURL, strings.NewReader(otpReq.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = ac.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error polling mfa device")
}
//extract form action and jwt token
form, actionURL, err = extractFormData(res)
if err != nil {
return "", errors.Wrap(err, "error extracting mfa form data")
}
//pass PingId auth back to pingfed
req, err = http.NewRequest("POST", actionURL, strings.NewReader(form.Encode()))
if err != nil {
return "", errors.Wrap(err, "error building authentication request")
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = ac.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error authenticating mfa")
}
}
//try to extract SAMLResponse
doc, err = goquery.NewDocumentFromResponse(res)
if err != nil {
return "", errors.Wrap(err, "error parsing document")
}
var ok bool
samlAssertion, ok := doc.Find("input[name=\"SAMLResponse\"]").Attr("value")
if !ok {
return "", errors.Wrap(err, "unable to locate saml response")
}
logger.WithField("samlAssertion", samlAssertion).Debug("SAMLResponse")
return samlAssertion, nil
}
func (ac *Client) getLoginForm(loginDetails *creds.LoginDetails) (string, url.Values, error) {
// request to PingOne
res, err := ac.client.Get(loginDetails.URL)
if err != nil {
return "", nil, errors.Wrap(err, "error retrieving AuthnRequest form")
}
// parse form for action(url), SAMLRequest, RelayState
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
return "", nil, errors.Wrap(err, "error parsing document")
}
postUrl, formData, err := parseSAMLRequestForm(doc)
if err != nil {
return "", nil, errors.Wrap(err, "error parse SAMLRequest form")
}
// AuthnRequest to PingFederate
ac.EnableFollowRedirect()
res, err = ac.client.PostForm(postUrl, formData)
if err != nil {
return "", nil, errors.Wrap(err, "error retrieving login form")
}
// 401 Unauthorized -> refresh same page with cookie
res, err = ac.client.Get(ac.lastAccessUrl.String())
if err != nil {
return "", nil, errors.Wrap(err, "error refresh same page")
}
// Get login form
doc, err = goquery.NewDocumentFromResponse(res)
if err != nil {
return "", nil, errors.Wrap(err, "failed to build document from response")
}
doc.Find("input").Each(func(i int, s *goquery.Selection) {
updateLoginFormData(formData, s, loginDetails)
})
formAction := ""
doc.Find("form").Each(func(i int, s *goquery.Selection) {
action, ok := s.Attr("action")
if !ok {
return
}
formAction = action
})
if formAction == "" {
return "", nil, fmt.Errorf("unable to locate IDP authentication form submit URL")
}
authSubmitURL, err := url.Parse(formAction)
if err != nil {
return "", nil, fmt.Errorf("unable parse form action")
}
if !authSubmitURL.IsAbs() {
authSubmitURL.Scheme = ac.lastAccessUrl.Scheme
authSubmitURL.Host = ac.lastAccessUrl.Host
}
return authSubmitURL.String(), formData, nil
}
func parseSAMLRequestForm(doc *goquery.Document) (string, url.Values, error) {
formSelection := doc.Find("form")
postUrl, exists := formSelection.Attr("action")
if !exists {
return "", nil, fmt.Errorf("error parsing form")
}
formData := url.Values{}
samlRequest, exists := formSelection.Find("input[name=\"SAMLRequest\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error SAMLRequest not found")
}
formData.Add("SAMLRequest", samlRequest)
relayState, exists := formSelection.Find("input[name=\"RelayState\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error RelayState not found")
}
formData.Add("RelayState", relayState)
logger.WithField("url", postUrl).WithField("SAMLRequest", samlRequest).WithField("RelayState", relayState).Debug("SAMLRequest")
return postUrl, formData, nil
}
func parseSAMLResponseForm(doc *goquery.Document) (string, url.Values, error) {
formSelection := doc.Find("form")
postUrl, exists := formSelection.Attr("action")
if !exists {
return "", nil, fmt.Errorf("error parsing form")
}
formData := url.Values{}
samlRequest, exists := formSelection.Find("input[name=\"SAMLResponse\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error SAMLResponse not found")
}
formData.Add("SAMLResponse", samlRequest)
relayState, exists := formSelection.Find("input[name=\"RelayState\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error RelayState not found")
}
formData.Add("RelayState", relayState)
logger.WithField("url", postUrl).WithField("SAMLResponse", samlRequest).WithField("RelayState", relayState).Debug("SAMLResponse")
return postUrl, formData, nil
}
func parsePpmRequestForm(doc *goquery.Document) (string, url.Values, error) {
formSelection := doc.Find("form")
postUrl, exists := formSelection.Attr("action")
if !exists {
return "", nil, fmt.Errorf("error parsing form")
}
formData := url.Values{}
ppmRequest, exists := formSelection.Find("input[name=\"ppm_request\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error ppm_request not found")
}
formData.Add("ppm_request", ppmRequest)
iss, exists := formSelection.Find("input[name=\"iss\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error iss not found")
}
formData.Add("iss", iss)
idpAccountId, exists := formSelection.Find("input[name=\"idp_account_id\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error idp_account_id not found")
}
formData.Add("idp_account_id", idpAccountId)
userAgentId, exists := formSelection.Find("input[name=\"userAgentId\"]").Attr("value")
if !exists {
return "", nil, fmt.Errorf("error userAgentId not found")
}
formData.Add("userAgentId", userAgentId)
logger.WithField("postUrl", postUrl).WithField("ppm_request", ppmRequest).WithField("iss", iss).WithField("idp_account_id", idpAccountId).WithField("userAgentId", userAgentId).Debug("ppm_request")
return postUrl, formData, nil
}
func updateLoginFormData(authForm url.Values, s *goquery.Selection, user *creds.LoginDetails) {
name, ok := s.Attr("name")
// log.Printf("name = %s ok = %v", name, ok)
if !ok {
return
}
lname := strings.ToLower(name)
if strings.Contains(lname, "pf.username") {
authForm.Add(name, user.Username)
} else if strings.Contains(lname, "pf.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 extractFormData(res *http.Response) (url.Values, string, error) {
formData := url.Values{}
var actionURL string
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return formData, actionURL, errors.Wrap(err, "failed to build document from response")
}
//get action url
doc.Find("form[method=\"POST\"]").Each(func(i int, s *goquery.Selection) {
action, ok := s.Attr("action")
if !ok {
return
}
actionURL = action
})
// extract form data to passthrough
doc.Find("form[method=\"POST\"] > input").Each(func(i int, s *goquery.Selection) {
name, ok := s.Attr("name")
if !ok {
return
}
val, ok := s.Attr("value")
if !ok {
return
}
formData.Add(name, val)
})
return formData, actionURL, nil
}
func extractMfaFormData(doc *goquery.Document) (url.Values, string, error) {
formData := url.Values{}
var actionURL string
//get action url
doc.Find("#form1").Each(func(i int, s *goquery.Selection) {
action, ok := s.Attr("action")
if !ok {
return
}
actionURL = action
})
// extract form data to passthrough
doc.Find("#form1 > input").Each(func(i int, s *goquery.Selection) {
name, ok := s.Attr("name")
if !ok {
return
}
val, ok := s.Attr("value")
if !ok {
return
}
formData.Add(name, val)
})
return formData, actionURL, nil
}