forked from crewjam/saml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice_provider.go
471 lines (410 loc) · 14.6 KB
/
service_provider.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
464
465
466
467
468
469
470
471
package saml
import (
"bytes"
"compress/flate"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"fmt"
"html/template"
"net/http"
"net/url"
"regexp"
"time"
"github.com/edaniels/go-saml/xmlsec"
)
// ServiceProvider implements SAML Service provider.
//
// In SAML, service providers delegate responsibility for identifying
// clients to an identity provider. If you are writing an application
// that uses passwords (or whatever) stored somewhere else, then you
// are service provider.
//
// See the example directory for an example of a web application using
// the service provider interface.
type ServiceProvider struct {
// Key is the RSA private key we use to sign requests.
Key string
// Certificate is the RSA public part of Key.
Certificate string
// MetadataURL is the full URL to the metadata endpoint on this host,
// i.e. https://example.com/saml/metadata
MetadataURL string
// AcsURL is the full URL to the SAML Assertion Customer Service endpoint
// on this host, i.e. https://example.com/saml/acs
AcsURL string
// IDPMetadata is the metadata from the identity provider.
IDPMetadata *Metadata
// State that Authn Requests will be signed
AuthnRequestsSigned bool
// Request that IdP assertions be signed
WantAssertionsSigned bool
}
// MaxIssueDelay is the longest allowed time between when a SAML assertion is
// issued by the IDP and the time it is received by ParseResponse. (In practice
// this is the maximum allowed clock drift between the SP and the IDP).
const MaxIssueDelay = time.Second * 90
// DefaultValidDuration is how long we assert that the SP metadata is valid.
const DefaultValidDuration = time.Hour * 24 * 2
// DefaultCacheDuration is how long we ask the IDP to cache the SP metadata.
const DefaultCacheDuration = time.Hour * 24 * 1
// Metadata returns the service provider metadata
func (sp *ServiceProvider) Metadata() *Metadata {
if cert, _ := pem.Decode([]byte(sp.Certificate)); cert != nil {
sp.Certificate = base64.StdEncoding.EncodeToString(cert.Bytes)
}
return &Metadata{
EntityID: sp.MetadataURL,
ValidUntil: TimeNow().Add(DefaultValidDuration),
SPSSODescriptor: &SPSSODescriptor{
AuthnRequestsSigned: sp.AuthnRequestsSigned,
WantAssertionsSigned: sp.WantAssertionsSigned,
ProtocolSupportEnumeration: "urn:oasis:names:tc:SAML:2.0:protocol",
KeyDescriptor: []KeyDescriptor{
{
Use: "signing",
KeyInfo: KeyInfo{
Certificate: sp.Certificate,
},
},
{
Use: "encryption",
KeyInfo: KeyInfo{
Certificate: sp.Certificate,
},
EncryptionMethods: []EncryptionMethod{
{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes128-cbc"},
{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes192-cbc"},
{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes256-cbc"},
{Algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"},
},
},
},
AssertionConsumerService: []IndexedEndpoint{{
Binding: HTTPPostBinding,
Location: sp.AcsURL,
Index: 1,
}},
},
}
}
// MakeRedirectAuthenticationRequest creates a SAML authentication request using
// the HTTP-Redirect binding. It returns a URL that we will redirect the user to
// in order to start the auth process.
func (sp *ServiceProvider) MakeRedirectAuthenticationRequest(relayState string) (*url.URL, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPRedirectBinding))
if err != nil {
return nil, err
}
redirect, err := req.Redirect(relayState)
if err != nil {
return nil, err
}
return redirect, nil
}
// Redirect returns a URL suitable for using the redirect binding with the request
func (req *AuthnRequest) Redirect(relayState string) (*url.URL, error) {
w := &bytes.Buffer{}
w1 := base64.NewEncoder(base64.StdEncoding, w)
w2, _ := flate.NewWriter(w1, 9)
if err := xml.NewEncoder(w2).Encode(req); err != nil {
return nil, err
}
w2.Close()
w1.Close()
rv, _ := url.Parse(req.Destination)
query := rv.Query()
query.Set("SAMLRequest", string(w.Bytes()))
if relayState != "" {
query.Set("RelayState", relayState)
}
rv.RawQuery = query.Encode()
return rv, nil
}
// GetSSOBindingLocation returns URL for the IDP's Single Sign On Service binding
// of the specified type (HTTPRedirectBinding or HTTPPostBinding)
func (sp *ServiceProvider) GetSSOBindingLocation(binding string) string {
for _, singleSignOnService := range sp.IDPMetadata.IDPSSODescriptor.SingleSignOnService {
if singleSignOnService.Binding == binding {
return singleSignOnService.Location
}
}
return ""
}
// getIDPSigningCert returns the certificate which we can use to verify things
// signed by the IDP in PEM format, or nil if no such certificate is found.
func (sp *ServiceProvider) getIDPSigningCert() []byte {
cert := ""
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "signing" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
// If there are no explicitly signing certs, just return the first
// non-empty cert we find.
if cert == "" {
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
}
if cert == "" {
return nil
}
// cleanup whitespace and re-encode a PEM
cert = regexp.MustCompile("\\s+").ReplaceAllString(cert, "")
certBytes, _ := base64.StdEncoding.DecodeString(cert)
certBytes = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes})
return certBytes
}
// MakeAuthenticationRequest produces a new AuthnRequest object for idpURL.
func (sp *ServiceProvider) MakeAuthenticationRequest(idpURL string) (*AuthnRequest, error) {
rnd, err := randomBytes(20)
if err != nil {
return nil, err
}
req := AuthnRequest{
AssertionConsumerServiceURL: sp.AcsURL,
Destination: idpURL,
ID: fmt.Sprintf("id-%x", rnd),
IssueInstant: TimeNow(),
Version: "2.0",
Issuer: Issuer{
Format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity",
Value: sp.MetadataURL,
},
NameIDPolicy: NameIDPolicy{
AllowCreate: true,
// TODO(ross): figure out exactly policy we need
// urn:mace:shibboleth:1.0:nameIdentifier
// urn:oasis:names:tc:SAML:2.0:nameid-format:transient
Format: "urn:oasis:names:tc:SAML:2.0:nameid-format:transient",
},
}
if !sp.AuthnRequestsSigned {
return &req, nil
}
signatureTemplate := xmlsec.DefaultSignature(sp.Certificate)
req.Signature = &signatureTemplate
req.Signature.SignedInfo.Reference.URI = "#" + req.ID
reqXml, err := xml.Marshal(&req)
if err != nil {
return nil, err
}
signedXml, err := xmlsec.SignRequest(string(reqXml), sp.Key)
if err != nil {
return nil, err
}
signedReq := &AuthnRequest{}
if err := xml.Unmarshal([]byte(signedXml), signedReq); err != nil {
return nil, err
}
return signedReq, nil
}
// MakePostAuthenticationRequest creates a SAML authentication request using
// the HTTP-POST binding. It returns HTML text representing an HTML form that
// can be sent presented to a browser to initiate the login process.
func (sp *ServiceProvider) MakePostAuthenticationRequest(relayState string) ([]byte, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPPostBinding))
if err != nil {
return nil, err
}
post, err := req.Post(relayState)
if err != nil {
return nil, err
}
return post, nil
}
// Post returns an HTML form suitable for using the HTTP-POST binding with the request
func (req *AuthnRequest) Post(relayState string) ([]byte, error) {
reqBuf, err := xml.Marshal(req)
if err != nil {
return nil, err
}
encodedReqBuf := base64.StdEncoding.EncodeToString(reqBuf)
tmpl := template.Must(template.New("saml-post-form").Parse(`` +
`<form method="post" action="{{.URL}}" id="SAMLRequestForm">` +
`<input type="hidden" name="SAMLRequest" value="{{.SAMLRequest}}" />` +
`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
`<input type="submit" value="Submit" />` +
`</form>` +
`<script>document.getElementById('SAMLRequestForm').submit();</script>`))
data := struct {
URL string
SAMLRequest string
RelayState string
}{
URL: req.Destination,
SAMLRequest: encodedReqBuf,
RelayState: relayState,
}
rv := bytes.Buffer{}
if err := tmpl.Execute(&rv, data); err != nil {
return nil, err
}
return rv.Bytes(), nil
}
// AssertionAttributes is a list of AssertionAttribute
type AssertionAttributes []AssertionAttribute
// Get returns the assertion attribute whose Name or FriendlyName
// matches name, or nil if no matching attribute is found.
func (aa AssertionAttributes) Get(name string) *AssertionAttribute {
for _, attr := range aa {
if attr.Name == name {
return &attr
}
if attr.FriendlyName == name {
return &attr
}
}
return nil
}
// AssertionAttribute represents an attribute of the user extracted from
// a SAML Assertion.
type AssertionAttribute struct {
FriendlyName string
Name string
Value string
}
// InvalidResponseError is the error produced by ParseResponse when it fails.
// The underlying error is in PrivateErr. Response is the response as it was
// known at the time validation failed. Now is the time that was used to validate
// time-dependent parts of the assertion.
type InvalidResponseError struct {
PrivateErr error
Response string
Now time.Time
}
func (ivr *InvalidResponseError) Error() string {
return fmt.Sprintf("Authentication failed")
}
// ParseResponse extracts the SAML IDP response received in req, validates
// it, and returns the verified attributes of the request.
//
// This function handles decrypting the message, verifying the digital
// signature on the assertion, and verifying that the specified conditions
// and properties are met.
//
// If the function fails it will return an InvalidResponseError whose
// properties are useful in describing which part of the parsing process
// failed. However, to discourage inadvertent disclosure the diagnostic
// information, the Error() method returns a static string.
func (sp *ServiceProvider) ParseResponse(req *http.Request, possibleRequestIDs []string) (*Assertion, error) {
now := TimeNow()
if err := req.ParseForm(); err != nil {
return nil, err
}
retErr := &InvalidResponseError{
Now: now,
Response: req.PostForm.Get("SAMLResponse"),
}
rawResponseBuf, err := base64.StdEncoding.DecodeString(req.PostForm.Get("SAMLResponse"))
if err != nil {
retErr.PrivateErr = fmt.Errorf("cannot parse base64: %s", err)
return nil, retErr
}
retErr.Response = string(rawResponseBuf)
// do some validation first before we decrypt
resp := Response{}
if err := xml.Unmarshal(rawResponseBuf, &resp); err != nil {
retErr.PrivateErr = fmt.Errorf("cannot unmarshal response: %s", err)
return nil, retErr
}
if resp.Destination != sp.AcsURL {
retErr.PrivateErr = fmt.Errorf("`Destination` does not match AcsURL (expected %q)", sp.AcsURL)
return nil, retErr
}
requestIDvalid := false
for _, possibleRequestID := range possibleRequestIDs {
if resp.InResponseTo == possibleRequestID {
requestIDvalid = true
}
}
if !requestIDvalid {
retErr.PrivateErr = fmt.Errorf("`InResponseTo` does not match any of the possible request IDs (expected %v)", possibleRequestIDs)
return nil, retErr
}
if resp.IssueInstant.Add(MaxIssueDelay).Before(now) {
retErr.PrivateErr = fmt.Errorf("IssueInstant expired at %s", resp.IssueInstant.Add(MaxIssueDelay))
return nil, retErr
}
if resp.Issuer.Value != sp.IDPMetadata.EntityID {
retErr.PrivateErr = fmt.Errorf("Issuer does not match the IDP metadata (expected %q)", sp.IDPMetadata.EntityID)
return nil, retErr
}
if resp.Status.StatusCode.Value != StatusSuccess {
retErr.PrivateErr = fmt.Errorf("Status code was not %s", StatusSuccess)
return nil, retErr
}
var assertion *Assertion
if resp.EncryptedAssertion == nil {
if err := xmlsec.VerifyResponseSignature(string(rawResponseBuf), string(sp.getIDPSigningCert())); err != nil {
retErr.PrivateErr = fmt.Errorf("failed to verify signature on response: %s", err)
return nil, retErr
}
assertion = resp.Assertion
}
// decrypt the response
if resp.EncryptedAssertion != nil {
plaintextAssertion, err := xmlsec.Decrypt(string(resp.EncryptedAssertion.EncryptedData), sp.Key)
if err != nil {
retErr.PrivateErr = fmt.Errorf("failed to decrypt response: %s", err)
return nil, retErr
}
retErr.Response = string(plaintextAssertion)
if err := xmlsec.VerifyAssertionSignature(plaintextAssertion, string(sp.getIDPSigningCert())); err != nil {
retErr.PrivateErr = fmt.Errorf("failed to verify signature on response: %s", err)
return nil, retErr
}
assertion = &Assertion{}
xml.Unmarshal([]byte(plaintextAssertion), assertion)
}
if err := sp.validateAssertion(assertion, possibleRequestIDs, now); err != nil {
retErr.PrivateErr = fmt.Errorf("assertion invalid: %s", err)
return nil, retErr
}
return assertion, nil
}
// validateAssertion checks that the conditions specified in assertion match
// the requirements to accept. If validation fails, it returns an error describing
// the failure. (The digital signature on the assertion is not checked -- this
// should be done before calling this function).
func (sp *ServiceProvider) validateAssertion(assertion *Assertion, possibleRequestIDs []string, now time.Time) error {
if assertion.IssueInstant.Add(MaxIssueDelay).Before(now) {
return fmt.Errorf("expired on %s", assertion.IssueInstant.Add(MaxIssueDelay))
}
if assertion.Issuer.Value != sp.IDPMetadata.EntityID {
return fmt.Errorf("issuer is not %q", sp.IDPMetadata.EntityID)
}
requestIDvalid := false
for _, possibleRequestID := range possibleRequestIDs {
if assertion.Subject.SubjectConfirmation.SubjectConfirmationData.InResponseTo == possibleRequestID {
requestIDvalid = true
break
}
}
if !requestIDvalid {
return fmt.Errorf("SubjectConfirmation one of the possible request IDs (%v)", possibleRequestIDs)
}
if assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient != sp.AcsURL {
return fmt.Errorf("SubjectConfirmation Recipient is not %s", sp.AcsURL)
}
if assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotOnOrAfter.Before(now) {
return fmt.Errorf("SubjectConfirmationData is expired")
}
if assertion.Conditions.NotBefore.After(now) {
return fmt.Errorf("Conditions is not yet valid")
}
if assertion.Conditions.NotOnOrAfter.Before(now) {
return fmt.Errorf("Conditions is expired")
}
if assertion.Conditions.AudienceRestriction.Audience.Value != sp.MetadataURL {
return fmt.Errorf("Conditions AudienceRestriction is not %q", sp.MetadataURL)
}
return nil
}