forked from anoop2811/saml2aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pingfed.go
218 lines (180 loc) · 6.43 KB
/
pingfed.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
package pingfed
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"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/page"
"github.com/versent/saml2aws/pkg/prompter"
"github.com/versent/saml2aws/pkg/provider"
)
var logger = logrus.WithField("provider", "pingfed")
// Client wrapper around PingFed + PingId enabling authentication and retrieval of assertions
type Client struct {
client *provider.HTTPClient
idpAccount *cfg.IDPAccount
}
// New create a new PingFed 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")
}
// assign a response validator to ensure all responses are either success or a redirect
// this is to avoid have explicit checks for every single response
client.CheckResponseStatus = provider.SuccessOrRedirectResponseValidator
return &Client{
client: client,
idpAccount: idpAccount,
}, nil
}
type ctxKey string
// Authenticate Authenticate to PingFed and return the data from the body of the SAML assertion.
func (ac *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) {
url := fmt.Sprintf("%s/idp/startSSO.ping?PartnerSpId=%s", loginDetails.URL, ac.idpAccount.AmazonWebservicesURN)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", errors.Wrap(err, "error building request")
}
ctx := context.WithValue(context.Background(), ctxKey("login"), loginDetails)
return ac.follow(ctx, req)
}
func (ac *Client) follow(ctx context.Context, req *http.Request) (string, error) {
res, err := ac.client.Do(req)
if err != nil {
return "", errors.Wrap(err, "error following")
}
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return "", errors.Wrap(err, "failed to build document from response")
}
var handler func(context.Context, *goquery.Document) (context.Context, *http.Request, error)
if samlResponse, ok := extractSAMLResponse(doc); ok {
return samlResponse, nil
} else if docIsLogin(doc) {
logger.WithField("type", "login").Debug("doc detect")
handler = ac.handleLogin
} else if docIsOTP(doc) {
logger.WithField("type", "otp").Debug("doc detect")
handler = ac.handleOTP
} else if docIsSwipe(doc) {
logger.WithField("type", "swipe").Debug("doc detect")
handler = ac.handleSwipe
} else if docIsFormRedirect(doc) {
logger.WithField("type", "form-redirect").Debug("doc detect")
handler = ac.handleFormRedirect
}
if handler == nil {
html, _ := doc.Selection.Html()
logger.WithField("doc", html).Debug("Unknown document type")
return "", fmt.Errorf("Unknown document type")
}
ctx, req, err = handler(ctx, doc)
if err != nil {
return "", err
}
return ac.follow(ctx, req)
}
func (ac *Client) handleLogin(ctx context.Context, doc *goquery.Document) (context.Context, *http.Request, error) {
loginDetails, ok := ctx.Value(ctxKey("login")).(*creds.LoginDetails)
if !ok {
return ctx, nil, fmt.Errorf("no context value for 'login'")
}
form, err := page.NewFormFromDocument(doc, "form")
if err != nil {
return ctx, nil, errors.Wrap(err, "error extracting login form")
}
form.Values.Set("pf.username", loginDetails.Username)
form.Values.Set("pf.pass", loginDetails.Password)
form.URL = makeAbsoluteURL(form.URL, loginDetails.URL)
req, err := form.BuildRequest()
return ctx, req, err
}
func (ac *Client) handleOTP(ctx context.Context, doc *goquery.Document) (context.Context, *http.Request, error) {
form, err := page.NewFormFromDocument(doc, "#otp-form")
if err != nil {
return ctx, nil, errors.Wrap(err, "error extracting OTP form")
}
token := prompter.StringRequired("Enter passcode")
form.Values.Set("otp", token)
req, err := form.BuildRequest()
return ctx, req, err
}
func (ac *Client) handleSwipe(ctx context.Context, doc *goquery.Document) (context.Context, *http.Request, error) {
form, err := page.NewFormFromDocument(doc, "#form1")
if err != nil {
return ctx, nil, errors.Wrap(err, "error extracting swipe status form")
}
// poll status. request must specifically be a GET
form.Method = "GET"
req, err := form.BuildRequest()
if err != nil {
return ctx, nil, err
}
for {
time.Sleep(3 * time.Second)
res, err := ac.client.Do(req)
if err != nil {
return ctx, nil, errors.Wrap(err, "error polling swipe status")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return ctx, nil, errors.Wrap(err, "error parsing body from swipe status response")
}
resp := string(body)
pingfedMFAStatusResponse := gjson.Get(resp, "status").String()
//ASYNC_AUTH_WAIT indicates we keep going
//OK indicates someone swiped
//DEVICE_CLAIM_TIMEOUT indicates nobody swiped
//otherwise loop forever?
if pingfedMFAStatusResponse == "OK" || pingfedMFAStatusResponse == "DEVICE_CLAIM_TIMEOUT" || pingfedMFAStatusResponse == "TIMEOUT" {
break
}
}
// now build a request for getting response of MFA
form, err = page.NewFormFromDocument(doc, "#reponseView")
if err != nil {
return ctx, nil, errors.Wrap(err, "error extracting swipe response form")
}
req, err = form.BuildRequest()
return ctx, req, err
}
func (ac *Client) handleFormRedirect(ctx context.Context, doc *goquery.Document) (context.Context, *http.Request, error) {
form, err := page.NewFormFromDocument(doc, "")
if err != nil {
return ctx, nil, errors.Wrap(err, "error extracting redirect form")
}
req, err := form.BuildRequest()
return ctx, req, err
}
func docIsLogin(doc *goquery.Document) bool {
return doc.Has("input[name=\"pf.pass\"]").Size() == 1
}
func docIsOTP(doc *goquery.Document) bool {
return doc.Has("form#otp-form").Size() == 1
}
func docIsSwipe(doc *goquery.Document) bool {
return doc.Has("form#form1").Size() == 1 && doc.Has("form#reponseView").Size() == 1
}
func docIsFormRedirect(doc *goquery.Document) bool {
return doc.Has("input[name=\"ppm_request\"]").Size() == 1
}
func extractSAMLResponse(doc *goquery.Document) (v string, ok bool) {
return doc.Find("input[name=\"SAMLResponse\"]").Attr("value")
}
// ensures given url is an absolute URL. if not, it will be combined with the base URL
func makeAbsoluteURL(v string, base string) string {
if u, err := url.ParseRequestURI(v); err == nil && !u.IsAbs() {
return fmt.Sprintf("%s%s", base, v)
}
return v
}