forked from LoginRadius/go-saml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidp.go
463 lines (421 loc) · 14 KB
/
idp.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 saml
import (
"bytes"
"compress/flate"
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net/url"
"time"
lib "github.com/LoginRadius/go-saml/internal"
"github.com/LoginRadius/go-saml/templates"
"github.com/LoginRadius/go-saml/util"
)
var samlPostFormTemplate = templates.SAMLResponsePostForm()
func (idp *IdentityProvider) NewSignedLoginResponse() (string, *Reject) {
errReject := idp.validate()
if errReject != nil {
return "", errReject
}
response := lib.NewResponse()
response.SetIdpCertificate(idp.x509IdpCertificate)
response.SetSignatureAlgorithm(idp.signatureAlgorithm())
response.SetDigestAlgorithm(idp.digestAlgorithm())
response.SetIssuer(idp.Issuer)
response.SetDestination(idp.ACSLocation)
response.SetNameId(idp.NameIdentifierFormat, idp.NameIdentifier)
response.SetSessionIndex(idp.SessionIndex)
response.AddAudience(idp.Audiences)
response.AddAttributes(idp.Attributes)
if idp.samlRequestParam != nil {
response.SetInResponseTo(idp.samlRequestParam.AuthnRequest.ID)
}
signedXml, err := response.SignedXml(idp.idpPrivateKey)
if err != nil {
return "", &Reject{err, "SIGNED_XML_ERROR"}
}
return signedXml, nil
}
func (idp *IdentityProvider) NewSignedLogoutResponse() (string, *Reject) {
//err := idp.validate()
response := lib.NewLogoutResponse()
response.Issuer.Url = idp.Issuer
response.Destination = idp.LogoutUrl
errReject := idp.parseIdpX509Certificate()
if errReject != nil {
return "", errReject
}
errReject = idp.parsePrivateKey()
if errReject != nil {
return "", errReject
}
response.Signature.KeyInfo.X509Data.X509Certificate.Cert = idp.x509IdpCertificate
if idp.samlRequestParam != nil {
response.InResponseTo = idp.samlRequestParam.LogoutRequest.ID
}
response.SetSignatureAlgorithm(idp.signatureAlgorithm())
response.SetDigestAlgorithm(idp.digestAlgorithm())
signedXml, err := response.SignedXml(idp.idpPrivateKey)
if err != nil {
return "", &Reject{err, "SIGNED_XML_ERROR"}
}
return signedXml, nil
}
func (idp *IdentityProvider) MetaDataResponse() (string, *Reject) {
var idpCert string
if idp.IDPCertFilePath != "" {
// IDP Cert is provided by file path.
buf, err := ioutil.ReadFile(idp.IDPCertFilePath)
if err != nil {
return "", &Reject{err, "SAML Configuration: IDP Certificate file could not be read"}
}
idpCert = util.GetRawCertificate(string(buf))
} else {
idpCert = util.GetRawCertificate(idp.IDPCert)
}
metadata := lib.GetIdpEntityDescriptor()
metadata.EntityId = idp.Issuer
metadata.IDPSSODescriptor.SigningKeyDescriptor.KeyInfo.X509Data.X509Certificate.Cert = idpCert
if len(idp.SingleSignOnService) > 0 {
for i := 0; i < len(idp.SingleSignOnService); i++ {
metadata.IDPSSODescriptor.SingleSignOnService = append(metadata.IDPSSODescriptor.SingleSignOnService, lib.SingleSignOnService{
XMLName: xml.Name{
Local: "SingleSignOnService",
},
Index: fmt.Sprintf(`%d`, i),
Binding: idp.SingleSignOnService[i].Binding,
Location: idp.SingleSignOnService[i].Location,
})
}
}
if len(idp.SingleSignOutService) > 0 {
for i := 0; i < len(idp.SingleSignOutService); i++ {
metadata.IDPSSODescriptor.SingleLogoutService = append(metadata.IDPSSODescriptor.SingleLogoutService, lib.SingleLogoutService{
XMLName: xml.Name{
Local: "SingleLogoutService",
},
Index: fmt.Sprintf(`%d`, i),
Binding: idp.SingleSignOutService[i].Binding,
Location: idp.SingleSignOutService[i].Location,
})
}
}
b, err := xml.MarshalIndent(metadata, "", " ")
if err != nil {
return "", &Reject{err, "XML_ENCODE_ERROR"}
}
newMetadata := fmt.Sprintf("<?xml version='1.0' encoding='UTF-8'?>\n%s", b)
return string(newMetadata), nil
}
func (idp *IdentityProvider) ValidateAuthnRequest(method string, query url.Values, payload url.Values) *Reject {
samlRequestParam, err := prepareSamlRequestParam(method, query, payload, "AuthnRequest")
if err != nil {
return &Reject{err, "SAML_REQUEST_NOT_VALID"}
}
if err = samlRequestParam.CheckSignature(idp); err != nil {
return &Reject{err, "SAML_SINGING_CERTIFICATE_MISMATCH"}
}
if err = samlRequestParam.AuthnRequest.Validate(); err != nil {
return &Reject{err, "SAML_REQUEST_NOT_VALID"}
}
idp.RelayState = samlRequestParam.RelayState
idp.samlRequestParam = samlRequestParam
return nil
}
func (idp *IdentityProvider) ValidateLogoutRequest(method string, query url.Values, payload url.Values) *Reject {
samlRequestParam, err := prepareSamlRequestParam(method, query, payload, "LogoutRequest")
if err != nil {
return &Reject{err, "SAML_REQUEST_NOT_VALID"}
}
if err = samlRequestParam.CheckSignature(idp); err != nil {
return &Reject{err, "SAML_SINGING_CERTIFICATE_MISMATCH"}
}
if err = samlRequestParam.LogoutRequest.Validate(); err != nil {
return &Reject{err, "SAML_REQUEST_NOT_VALID"}
}
idp.RelayState = samlRequestParam.RelayState
idp.samlRequestParam = samlRequestParam
return nil
}
func (idp *IdentityProvider) AddAttribute(name string, value string, format string) {
idp.Attributes = append(idp.Attributes, map[string]string{
"Name": name,
"Value": value,
"Format": format,
})
}
func (idp *IdentityProvider) AddSingleSignOnService(service MetadataBinding) {
idp.SingleSignOnService = append(idp.SingleSignOnService, service)
}
func (idp *IdentityProvider) AddSingleSignOutService(service MetadataBinding) {
idp.SingleSignOutService = append(idp.SingleSignOutService, service)
}
func (idp *IdentityProvider) AuthnRequestTTL(duration time.Duration) {
lib.MaxIssueDelay = duration
}
func (idp *IdentityProvider) ResponseHtml(signedXML string, requestType string) (string, *Reject) {
var b bytes.Buffer
location := idp.ACSLocation
if requestType == "LogoutResponse" {
location = idp.LogoutUrl
}
data := struct {
URL string
SAMLResponse string
RelayState string
}{
URL: location,
SAMLResponse: base64.StdEncoding.EncodeToString([]byte(signedXML)),
RelayState: idp.RelayState,
}
if err := samlPostFormTemplate.Execute(&b, data); err != nil {
return "", &Reject{err, "XML_ENCODE_ERROR"}
}
return b.String(), nil
}
func (idp *IdentityProvider) validateIDPX509Certificate() *Reject {
if idp.IDPCert == "" && idp.IDPCertFilePath == "" {
return &Reject{errors.New("SAML Configuration: IDP Certificate is empty"), "EMPTY_IDP_CERTIFICATE"}
}
if idp.IDPCertFilePath != "" {
// IDP Cert is provided by file path.
buf, err := ioutil.ReadFile(idp.IDPCertFilePath)
if err != nil {
return &Reject{errors.New("SAML Configuration: IDP Certificate is empty"), "EMPTY_IDP_CERTIFICATE"}
}
if err := util.ValidateCertificatePem(string(buf)); err != nil {
return &Reject{err, "INVALID_CERTIFICATE_PEM"}
}
} else {
// IDP Cert is provided by string.
if err := util.ValidateCertificatePem(idp.IDPCert); err != nil {
return &Reject{err, "INVALID_CERTIFICATE_PEM"}
}
}
return nil
}
func (idp *IdentityProvider) validateSPX509Certificate() *Reject {
if idp.SPCert == "" && idp.SPCertFilePath == "" {
return &Reject{errors.New("SAML Configuration: SP Certificate is empty"), "EMPTY_IDP_CERTIFICATE"}
}
if idp.SPCertFilePath != "" {
// SP Cert is provided by file path.
buf, err := ioutil.ReadFile(idp.SPCertFilePath)
if err != nil {
return &Reject{err, "INVALID_CERTIFICATE_PEM_FILE_PATH"}
}
if err := util.ValidateCertificatePem(string(buf)); err != nil {
return &Reject{err, "INVALID_CERTIFICATE_PEM"}
}
} else {
// SP Cert is provided by string.
if err := util.ValidateCertificatePem(idp.SPCert); err != nil {
return &Reject{err, "INVALID_CERTIFICATE_PEM"}
}
}
return nil
}
func (idp *IdentityProvider) rawIdpX509Certificate() *Reject {
err := idp.validateIDPX509Certificate()
if err != nil {
return err
}
if idp.IDPCertFilePath != "" {
// IDP Cert is provided by file path.
buf, err := ioutil.ReadFile(idp.IDPCertFilePath)
if err != nil {
return &Reject{err, "INVALID_CERTIFICATE_PEM_FILE_PATH"}
}
idp.x509IdpCertificate = util.GetRawCertificate(string(buf))
} else {
idp.x509IdpCertificate = util.GetRawCertificate(idp.IDPCert)
}
return nil
}
func (idp *IdentityProvider) rawSPX509Certificate() *Reject {
err := idp.validateSPX509Certificate()
if err != nil {
return err
}
if idp.SPCertFilePath != "" {
// SP Cert is provided by file path.
buf, err := ioutil.ReadFile(idp.SPCertFilePath)
if err != nil {
return &Reject{err, "INVALID_CERTIFICATE_PEM_FILE_PATH"}
}
idp.x509SpCertificate = util.GetRawCertificate(string(buf))
} else {
idp.x509SpCertificate = util.GetRawCertificate(idp.SPCert)
}
return nil
}
func (idp *IdentityProvider) parseIdpX509Certificate() *Reject {
err := idp.validateIDPX509Certificate()
if err != nil {
return err
}
idp.x509IdpCertificate = util.GetRawCertificate(idp.IDPCert)
return nil
}
func (idp *IdentityProvider) parseSpX509Certificate() *Reject {
err := idp.validateSPX509Certificate()
if err != nil {
return err
}
idp.x509SpCertificate = util.GetRawCertificate(idp.SPCert)
return nil
}
func (idp *IdentityProvider) parsePrivateKey() *Reject {
if idp.IDPKey == "" && idp.IDPKeyFilePath == "" {
return &Reject{errors.New("SAML Configuration: IDP Private Key is empty"), "EMPTY_IDP_PRIVATE_KEY"}
}
privateKey, err := util.ParseRsaPrivateKeyPem(idp.IDPKey)
if err != nil {
return &Reject{err, "PARSE_PRIVATE_KEY_ERROR"}
}
idp.idpPrivateKey = privateKey
if idp.IDPKeyFilePath != "" {
// IDP Private Key is provided by file path.
buf, err := ioutil.ReadFile(idp.IDPKeyFilePath)
if err != nil {
return &Reject{err, "INVALID_PRIVATE_KEY_FILE_PATH"}
}
privateKey, err := util.ParseRsaPrivateKeyPem(string(buf))
if err != nil {
return &Reject{err, "PARSE_PRIVATE_KEY_ERROR"}
}
idp.idpPrivateKey = privateKey
} else {
// IDP Private Key is provided by string.
privateKey, err := util.ParseRsaPrivateKeyPem(idp.IDPKey)
if err != nil {
return &Reject{err, "PARSE_PRIVATE_KEY_ERROR"}
}
idp.idpPrivateKey = privateKey
}
return nil
}
func (idp *IdentityProvider) validate() *Reject {
err := idp.parseIdpX509Certificate()
if err != nil {
return err
}
err = idp.parsePrivateKey()
if err != nil {
return err
}
if !idp.IsIdpInitiated {
err := idp.parseSpX509Certificate()
if err != nil {
return err
}
}
if idp.Issuer == "" {
return &Reject{errors.New("SAML Configuration: Issuer is empty"), "SAML_CONFIG_ISSUER_EMPTY"}
}
if idp.ACSLocation == "" {
return &Reject{errors.New("SAML Configuration: ACSLocation is empty"), "SAML_CONFIG_ASCLOCATION_EMPTY"}
}
if idp.ACSBinging == "" {
return &Reject{errors.New("SAML Configuration: ACSBinging is empty"), "SAML_CONFIG_ACSBINGING_EMPTY"}
}
if idp.ACSBinging != "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" {
return &Reject{errors.New("SAML Configuration: ACSBinging is invalid"), "SAML_CONFIG_ACSBINGING_EMPTY"}
}
if idp.NameIdentifierFormat == "" {
return &Reject{errors.New("SAML Configuration: NameID Format is empty"), "SAML_CONFIG_NAMEID_FORMAT_EMPTY"}
}
if idp.NameIdentifier == "" {
return &Reject{errors.New("SAML Configuration: NameID value is empty"), "SAML_CONFIG_NAMEID_VALUE_EMPTY"}
}
if idp.SessionIndex == "" {
return &Reject{errors.New("SAML Configuration: SessionIndex is empty"), "SAML_CONFIG_SESSIONINDEX_EMPTY"}
}
if len(idp.Audiences) == 0 {
return &Reject{errors.New("SAML Configuration: Audience is empty"), "SAML_CONFIG_AUDIENCE_EMPTY"}
}
if len(idp.Attributes) > 0 {
for _, attr := range idp.Attributes {
attrName, attrNameOk := attr["Name"]
attrFormat, attrFormatOk := attr["Format"]
_, attrValueOk := attr["Value"]
if !(attrNameOk && attrName != "") {
return &Reject{errors.New("SAML Configuration: Attributes Name is not defined or empty"), "SAML_CONFIG_NAME_UNDEFINED"}
}
if !(attrFormatOk && attrFormat != "") {
return &Reject{errors.New("SAML Configuration: Attributes Format is not defined or empty"), "SAML_CONFIG_FORMAT_UNDEFINED"}
}
if !(attrValueOk) {
return &Reject{errors.New("SAML Configuration: Attributes Value is not defined"), "SAML_CONFIG_VALUE_UNDEFINED"}
}
}
}
return nil
}
func (idp *IdentityProvider) signatureAlgorithm() string {
if idp.SignatureAlgorithm == "" {
return SignatureAlgorithmRSASHA256
}
return idp.SignatureAlgorithm
}
func (idp *IdentityProvider) digestAlgorithm() string {
if idp.DigestAlgorithm == "" {
return DigestAlgorithmSHA256
}
return idp.DigestAlgorithm
}
func prepareSamlRequestParam(method string, query url.Values, payload url.Values, requestType string) (*SamlRequestParam, error) {
samlRequestParam := &SamlRequestParam{Method: method}
switch method {
case "GET":
samlRequest := query.Get("SAMLRequest")
sigAlg := query.Get("SigAlg")
signature := query.Get("Signature")
if samlRequest == "" {
return nil, errors.New("AuthnRequest: SamlRequest is not found")
}
/*if sigAlg==""{
return nil, errors.New("AuthnRequest: Signature Algo is not found")
}*/
/*if signature==""{
return nil, errors.New("AuthnRequest: signature is not found")
}*/
samlRequestParam.Signature = signature
samlRequestParam.RelayState = query.Get("RelayState")
samlRequestParam.SAMLRequest = samlRequest
samlRequestParam.SigAlg = sigAlg
compressedRequest, err := base64.StdEncoding.DecodeString(query.Get("SAMLRequest"))
if err != nil {
return nil, fmt.Errorf("cannot decode request: %s", err)
}
samlRequestParam.RequestBuffer, err = ioutil.ReadAll(flate.NewReader(bytes.NewReader(compressedRequest)))
if err != nil {
return nil, fmt.Errorf("cannot decompress request: %s", err)
}
case "POST":
var err error
samlRequest := payload.Get("SAMLRequest")
samlRequestParam.RelayState = payload.Get("RelayState")
if samlRequest == "" {
return nil, errors.New("AuthnRequest: SamlRequest is not found")
}
samlRequestParam.RequestBuffer, err = base64.StdEncoding.DecodeString(payload.Get("SAMLRequest"))
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("method not allowed")
}
if requestType == "AuthnRequest" {
if err := samlRequestParam.ParseAuthnRequest(); err != nil {
return nil, err
}
} else {
if err := samlRequestParam.ParseLogoutRequest(); err != nil {
return nil, err
}
}
return samlRequestParam, nil
}