/
gosaml.go
executable file
·2305 lines (2074 loc) · 82.4 KB
/
gosaml.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Gosaml is a library for doing SAML stuff in Go.
package gosaml
import (
"bytes"
"compress/flate"
"compress/gzip"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/ed25519"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/json"
"encoding/pem"
"encoding/xml"
"errors"
"fmt"
"hash"
"html/template"
"io"
"io/fs"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/wayf-dk/go-libxml2/types"
"github.com/wayf-dk/goxml"
"golang.org/x/crypto/curve25519"
"x.config"
)
var (
_ = log.Printf // For debugging; delete when done.
)
const (
// IDPRole used to set the role as an IDP
IDPRole = iota
// SPRole used to set the role as an SP
SPRole
)
const (
// SAMLSign for SAML signing
SAMLSign = iota
// WSFedSign for WS-Fed signing
WSFedSign
)
const (
// XsDateTime Setting the Date Time
XsDateTime = "2006-01-02T15:04:05Z"
// SigningCertQuery refers to get the key from the metadata
SigningCertQuery = `/md:KeyDescriptor[@use="signing" or not(@use)]/ds:KeyInfo/ds:X509Data/ds:X509Certificate`
// EncryptionCertQuery refers to encryption key
EncryptionCertQuery = `/md:KeyDescriptor[@use="encryption" or not(@use)]/ds:KeyInfo/ds:X509Data/ds:X509Certificate`
SPEnc = "md:SPSSODescriptor" + EncryptionCertQuery
IdPEnc = "md:IDPSODescriptor" + EncryptionCertQuery
// Transient refers to nameid format
Transient = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"
// Persistent refers to nameid format
Persistent = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
// X509 refers to nameid format
X509 = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName"
// Email refers to nameid format
Email = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
// Unspecified refers to unspecified nameid format
Unspecified = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
// REDIRECT refers to HTTP-Redirect
REDIRECT = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
// POST refers to HTTP-POST
POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
// Allowed slack for timingchecks
timeskew = 90
)
type (
// SamlRequest - compact representation of a request across the hub
SamlRequest struct {
Nonce, RequestID, SP, IDP, VirtualIDP, WAYFSP, AssertionConsumerIndex, Protocol, IDPProtocol string
NameIDFormat, SPIndex, HubBirkIndex uint8
}
// Md Interface for metadata provider
Md interface {
MDQ(key string) (xp *goxml.Xp, err error)
}
// MdSets slice of Md sets - for searching one MD at at time and remembering the index
MdSets []Md
// SLOInfo refers to Single Logout information
SLOInfo struct {
IDP, SP, NameID, SPNameQualifier, SessionIndex, ID, Protocol string
NameIDFormat, HubRole, SLOStatus uint8
SLOSupport, Async bool
}
SLOInfoList []SLOInfo
// Formdata for passing parameters to display template
Formdata struct {
AcsURL template.URL
Acs, Samlresponse, Samlrequest, Id_token string
RelayState, SigAlg, Signature string
Protocol string
SLOStatus string
Ard template.JS
Initial bool
}
// Hm - HMac struct
Hm struct {
TTL int64
Hash func() hash.Hash
Key []byte
}
nemLog struct {
lock sync.Mutex
file *os.File
crypt *cipher.StreamWriter
writer *gzip.Writer
hash hash.Hash
name string
counter int
slot int64
peerPublic []byte
}
)
var (
// TestTime refers to global testing time
TestTime, ZeroTime time.Time
// TestID for testing
TestID string
// TestAssertionID for testing
TestAssertionID string
// Roles refers to defining roles for SPs and IDPs
Roles = []string{"md:IDPSSODescriptor", "md:SPSSODescriptor"}
// ErrorACS refers error information
ErrorACS = errors.New("AsssertionConsumerService, AsssertionConsumerServiceIndex, ProtocolBinding combination not found in metadata")
// NameIDList list of supported nameid formats
NameIDList = []string{"", Transient, Persistent, X509, Email, Unspecified}
// NameIDMap refers to mapping the nameid formats
NameIDMap = map[string]uint8{"": 1, Transient: 1, Persistent: 2, X509: 3, Email: 4, Unspecified: 5} // Unspecified accepted but not sent upstream
whitespace = regexp.MustCompile("\\s")
// PostForm -
PostForm *template.Template
// AuthnRequestCookie - shortlived hmaced timelimited data
AuthnRequestCookie *Hm
// B2I map for marshalling bool to uint
B2I = map[bool]byte{false: 0, true: 1}
privatekeyLock sync.RWMutex
privatekeyCache = map[string]crypto.PrivateKey{}
NemLog = &nemLog{}
)
// DebugSetting for debugging cookies
func DebugSetting(r *http.Request, name string) string {
cookie, err := r.Cookie("debug")
if err == nil {
vals, _ := url.ParseQuery(cookie.Value)
return vals.Get(name)
}
return ""
}
func DebugSettingWithDefault(r *http.Request, name, def string) (res string) {
res = DebugSetting(r, name)
if res == "" {
res = def
}
return
}
// DumpFile is for logging requests and responses
func DumpFile(r *http.Request, xp *goxml.Xp) (logtag string) {
msgType := xp.QueryString(nil, "local-name(/*)")
logtag = dump(msgType, []byte(fmt.Sprintf("%s\n###\n%s", xp.PP(), goxml.NewWerror("").Stack(1))))
return
}
// DumpFileIfTracing - check trace flag and and dump if set
func DumpFileIfTracing(r *http.Request, xp *goxml.Xp) (logtag string) {
if DebugSetting(r, "trace") == "1" {
logtag = DumpFile(r, xp)
}
return
}
func dump(msgType string, blob []byte) (logtag string) {
now := TestTime
if now.IsZero() {
now = time.Now()
}
logtag = now.Format("2006-01-02T15:04:05.0000000") // local time with microseconds
if err := ioutil.WriteFile(fmt.Sprintf("log/%s-%s", logtag, msgType), blob, 0644); err != nil {
//log.Panic(err)
}
return
}
func (l *nemLog) Write(p []byte) (n int, err error) {
l.counter += len(p)
l.hash.Write(p)
return l.file.Write(p)
}
func (l *nemLog) Init(slot int64) {
var err error
hostname, _ := os.Hostname()
l.slot = slot
l.name = fmt.Sprintf(config.NemLogNameFormat, hostname, time.Now().Format("2006-01-02T15:04:05.0000000"))
l.peerPublic, err = base64.StdEncoding.DecodeString(config.NemlogPublic)
if err != nil {
config.Logger.Fatalln(err)
}
ephemeralPriv := make([]byte, 32)
_, err = io.ReadFull(rand.Reader, ephemeralPriv[:])
if err != nil {
config.Logger.Fatalln(err)
}
if l.file, err = os.Create(l.name + ".gzip"); err != nil {
config.Logger.Fatalln(err)
}
l.hash = sha512.New()
var cb cipher.Block
var iv [aes.BlockSize]byte // blank is ok if key is new every time
ephemeralPub, err := curve25519.X25519(ephemeralPriv, curve25519.Basepoint)
if err != nil {
config.Logger.Fatalln(err)
}
sessionkey, err := curve25519.X25519(ephemeralPriv, l.peerPublic)
if err != nil {
config.Logger.Fatalln(err)
}
if _, err = l.Write([]byte(base64.StdEncoding.EncodeToString(ephemeralPub[:]) + "\n")); err != nil {
config.Logger.Fatalln(err)
}
if cb, err = aes.NewCipher(sessionkey[:]); err != nil {
config.Logger.Fatalln(err)
}
l.crypt = &cipher.StreamWriter{
S: cipher.NewOFB(cb, iv[:]),
W: l,
}
if l.writer, err = gzip.NewWriterLevel(l.crypt, gzip.BestCompression); err != nil {
config.Logger.Fatalln(err)
}
}
func (l *nemLog) Finalize() {
if l.writer != nil {
l.writer.Close()
l.crypt.Close()
l.file.Close()
l.writer = nil
l.counter = 0
if err := ioutil.WriteFile(l.name+".digest", []byte(fmt.Sprintf("%x %s.gzip\n", l.hash.Sum(nil), l.name)), 0644); err != nil {
config.Logger.Panic(err)
}
}
}
func (l *nemLog) Log(msg, idpMd *goxml.Xp, id string) {
entityID := idpMd.Query1(nil, `/md:EntityDescriptor/@entityID`)
if !config.NemLoginRelated[entityID] {
return
}
l.lock.Lock()
defer l.lock.Unlock()
slot := time.Now().Unix() / config.NemLogSlotGranularity
if l.counter >= config.NemLogMaxSize || (l.slot != slot && l.slot != 0) {
l.Finalize()
}
if l.writer == nil {
l.Init(slot)
}
if _, err := l.writer.Write([]byte("\n" + id + "\n")); err != nil {
config.Logger.Fatalln(err)
}
if _, err := l.writer.Write([]byte(msg.PP())); err != nil {
config.Logger.Fatalln(err)
}
return
}
// PublicKeyInfo extracts the keyname, publickey and cert (base64 DER - no PEM) from the given certificate.
// The keyname is computed from the public key corresponding to running this command: openssl x509 -modulus -noout -in <cert> | openssl sha1.
func PublicKeyInfo(cert string) (keyname string, publickey crypto.PublicKey, err error) {
// no pem so no pem.Decode
key, err := base64.StdEncoding.DecodeString(whitespace.ReplaceAllString(cert, ""))
crt, err := x509.ParseCertificate(key)
if err == nil {
publickey = crt.PublicKey
} else {
publickey, err = x509.ParsePKIXPublicKey(key)
if err != nil {
err = goxml.Wrap(err)
return
}
}
switch pk := publickey.(type) {
case *rsa.PublicKey:
keyname = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("Modulus=%X\n", pk.N))))
case ed25519.PublicKey:
keyname = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%X", pk))))
default:
panic("unknown type of public key")
}
return
}
func PublicKeyInfoByMethod(certs []string, keyType x509.PublicKeyAlgorithm) (keynames, crts []string, publickeys []crypto.PublicKey, err error) {
for _, cert := range certs {
var ok bool
name, publickey, _ := PublicKeyInfo(cert)
switch publickey.(type) {
case *rsa.PublicKey:
ok = keyType == x509.RSA
case ed25519.PublicKey:
ok = keyType == x509.Ed25519
}
if ok {
keynames = append(keynames, name)
publickeys = append(publickeys, publickey)
crts = append(crts, cert)
}
}
return
}
// GetPrivateKey extract the key from Metadata and builds a name and reads the key
func GetPrivateKey(md *goxml.Xp, path string) (privatekey crypto.PrivateKey, cert string, err error) {
cert = md.Query1(nil, path)
keyname, _, err := PublicKeyInfo(cert)
if err != nil {
return
}
privatekey, err = getPrivateKeyByName(keyname, "")
return
}
func GetPrivateKeyByMethodWithPW(md *goxml.Xp, path string, keyType x509.PublicKeyAlgorithm, pw string) (privatekey crypto.PrivateKey, cert string, err error) {
certs := md.QueryMulti(nil, path)
names, crts, _, _ := PublicKeyInfoByMethod(certs, keyType)
if len(names) == 0 {
err = fmt.Errorf("No keys found: %d", keyType)
return
}
privatekey, err = getPrivateKeyByName(names[0], pw)
cert = crts[0]
return
}
func GetPrivateKeyByMethod(md *goxml.Xp, path string, keyType x509.PublicKeyAlgorithm) (privatekey crypto.PrivateKey, cert string, err error) {
return GetPrivateKeyByMethodWithPW(md, path, keyType, "")
}
func getPrivateKeyByName(keyname, pw string) (privatekey crypto.PrivateKey, err error) {
privatekeyLock.RLock()
privatekey, ok := privatekeyCache[keyname]
privatekeyLock.RUnlock()
if ok {
return
}
pkpem, err := fs.ReadFile(config.PrivateKeys, keyname+".key")
if err != nil {
err = goxml.Wrap(err)
return
}
if bytes.HasPrefix(pkpem, []byte("hsm:")) {
privatekey = goxml.HSMKey(pkpem)
} else {
privatekey, err = Pem2PrivateKey(pkpem, pw)
if err != nil {
return nil, goxml.Wrap(err)
}
}
privatekeyLock.Lock()
privatekeyCache[keyname] = privatekey
privatekeyLock.Unlock()
return
}
// Pem2PrivateKey converts a PEM encoded private key with an optional password to a *rsa.PrivateKey
func Pem2PrivateKey(privatekeypem []byte, pw string) (pk crypto.PrivateKey, err error) {
block, _ := pem.Decode(privatekeypem) // not used rest
derbytes := block.Bytes
if pw != "" {
if derbytes, err = x509.DecryptPEMBlock(block, []byte(pw)); err != nil {
return nil, goxml.Wrap(err)
}
}
if pk, err = x509.ParsePKCS1PrivateKey(derbytes); err != nil {
if pk, err = x509.ParsePKCS8PrivateKey(derbytes); err != nil {
return nil, goxml.Wrap(err)
}
}
return
}
// ID makes a random id
func ID() (id string) {
b := make([]byte, 21) // 168 bits - just over the 160 bit recomendation without base64 padding
rand.Read(b)
return "_" + base64.RawURLEncoding.EncodeToString(b)
}
// IDHash to create hash of the id
func IDHash(data string) string {
return fmt.Sprintf("%.5x", sha1.Sum([]byte(data)))
}
// Deflate utility that compresses a string using the flate algo
func Deflate(inflated []byte) []byte {
var b bytes.Buffer
w, _ := flate.NewWriter(&b, -1)
w.Write(inflated)
w.Close()
return b.Bytes()
}
// Inflate utility that decompresses a string using the flate algo
func Inflate(deflated []byte) []byte {
var b bytes.Buffer
r := flate.NewReader(bytes.NewReader(deflated))
b.ReadFrom(r)
r.Close()
return b.Bytes()
}
// HTML2SAMLResponse extracts the SAMLResponse from a HTML document
func HTML2SAMLResponse(html []byte) (samlresponse *goxml.Xp, relayState string, action *url.URL) {
response := goxml.NewHTMLXp(html)
action, _ = url.Parse(response.Query1(nil, `//form/@action`))
samlbase64 := response.Query1(nil, `//input[@name="SAMLResponse"]/@value`)
if samlbase64 != "" {
relayState = response.Query1(nil, `//input[@name="RelayState"]/@value`)
samlxml, _ := base64.StdEncoding.DecodeString(samlbase64)
samlresponse = goxml.NewXp(samlxml)
return
}
samlxml := response.Query1(nil, `//input[@name="wresult"]/@value`)
if samlxml != "" {
samlresponse = goxml.NewXp([]byte(samlxml))
relayState = response.Query1(nil, `//input[@name="wctx"]/@value`)
return
}
return
}
// URL2SAMLRequest extracts the SAMLRequest from an URL
func URL2SAMLRequest(url *url.URL, err error) (samlrequest *goxml.Xp, relayState string) {
query := url.Query()
req, _ := base64.StdEncoding.DecodeString(query.Get("SAMLRequest"))
relayState = query.Get("RelayState")
samlrequest = goxml.NewXp(Inflate(req))
return
}
// SAMLRequest2URL creates a redirect URL from a saml request
func SAMLRequest2URL(samlrequest *goxml.Xp, relayState string, privatekey crypto.PrivateKey, algo string) (destination *url.URL, err error) {
var paramName string
switch samlrequest.QueryString(nil, "local-name(/*)") {
case "LogoutResponse":
paramName = "SAMLResponse="
default:
paramName = "SAMLRequest="
}
req := base64.StdEncoding.EncodeToString(Deflate(samlrequest.Dump()))
destination, _ = url.Parse(samlrequest.Query1(nil, "@Destination"))
q := paramName + url.QueryEscape(req)
if relayState != "" {
q += "&RelayState=" + url.QueryEscape(relayState)
}
if privatekey != nil {
q += "&SigAlg=" + url.QueryEscape(config.CryptoMethods[algo].SigningMethod)
digest := goxml.Hash(config.CryptoMethods[algo].Hash, q)
var signaturevalue []byte
signaturevalue, err = goxml.Sign(digest, privatekey, algo)
if err != nil {
return
}
signatureval := base64.StdEncoding.EncodeToString(signaturevalue)
q += "&Signature=" + url.QueryEscape(signatureval)
}
destination.RawQuery = q
return
}
func SAMLRequest2OIDCRequest(samlrequest *goxml.Xp, relayState, flow string, idpMD *goxml.Xp) (destination *url.URL, err error) {
destination, err = url.Parse(samlrequest.Query1(nil, "@Destination"))
if err != nil {
return
}
client_id := samlrequest.Query1(nil, "./saml:Issuer")
params := url.Values{}
params.Set("scope", "openid")
params.Set("response_type", flow) // code id_token
params.Set("client_id", client_id)
params.Set("redirect_uri", samlrequest.Query1(nil, "@AssertionConsumerServiceURL"))
params.Set("response_mode", "form_post")
params.Set("audience", client_id)
params.Set("nonce", samlrequest.Query1(nil, "@ID"))
params.Set("state", relayState)
if samlrequest.QueryXMLBool(nil, "@ForceAuthn") {
params.Set("prompt", "login")
}
if requesterIDs := samlrequest.QueryMulti(nil, "samlp:Scoping/samlp:RequesterID"); len(requesterIDs) > 0 {
params.Set("requester_id", strings.Join(requesterIDs, ","))
}
// params.Set("acr_values", "")
destination.RawQuery = params.Encode()
return
}
// AttributeCanonicalDump for canonical dump
func AttributeCanonicalDump(w io.Writer, xp *goxml.Xp) {
attrsmap := map[string][]string{}
keys := []string{}
attrs := xp.Query(nil, "./saml:Assertion/saml:AttributeStatement/saml:Attribute | ./t:RequestedSecurityToken/saml1:Assertion/saml1:AttributeStatement/saml1:Attribute")
for _, attr := range attrs {
values := []string{}
for _, value := range xp.QueryMulti(attr, "saml:AttributeValue | saml1:AttributeValue") {
values = append(values, value)
}
name := xp.Query1(attr, "@Name | @AttributeName") + " "
friendlyName := xp.Query1(attr, "@FriendlyName") + " "
nameFormat := xp.Query1(attr, "@NameFormat | @AttributeNamespace")
if name == friendlyName {
friendlyName = ""
}
key := strings.TrimSpace(friendlyName + name + nameFormat)
keys = append(keys, key)
attrsmap[key] = values
}
sort.Strings(keys)
for _, key := range keys {
fmt.Fprintln(w, key)
values := attrsmap[key]
sort.Strings(values)
for _, value := range values {
if value != "" {
fmt.Fprint(w, " ")
xml.EscapeText(w, bytes.TrimSpace([]byte(value)))
}
fmt.Fprintln(w)
}
}
}
// ReceiveAuthnRequest receives the authentication request
// Checks for Subject and NameidPolicy(Persistent or Transient)
// Receives the metadatasets for resp. the sender and the receiver
// Returns metadata for the sender and the receiver
func ReceiveAuthnRequest(r *http.Request, issuerMdSets, destinationMdSets MdSets, location string) (xp, issuerMd, destinationMd *goxml.Xp, relayState string, issuerIndex, destinationIndex uint8, err error) {
xp, issuerMd, destinationMd, relayState, issuerIndex, destinationIndex, err = DecodeSAMLMsg(r, issuerMdSets, destinationMdSets, IDPRole, []string{"AuthnRequest"}, location, nil)
if err != nil {
return
}
nameIDFormat := xp.Query1(nil, "./samlp:NameIDPolicy/@Format")
if NameIDMap[nameIDFormat] == 0 {
err = fmt.Errorf("nameidpolicy format: '%s' is not supported", nameIDFormat)
return
}
if nameIDFormat == Unspecified || nameIDFormat == "" {
nameIDFormat = issuerMd.Query1(nil, "./md:SPSSODescriptor/md:NameIDFormat") // none ends up being Transient
} else if inArray(nameIDFormat, issuerMd.QueryMulti(nil, "./md:SPSSODescriptor/md:NameIDFormat")) {
} else {
nameIDFormat = Transient
}
xp.QueryDashP(nil, "./samlp:NameIDPolicy/@Format", nameIDFormat, nil)
/*
allowcreate := xp.Query1(nil, "./samlp:NameIDPolicy/@AllowCreate")
if allowcreate != "true" && allowcreate != "1" {
err = fmt.Errorf("only supported value for NameIDPolicy @AllowCreate is true/1, got: %s", allowcreate)
return
}
*/
return
}
func inArray(item string, array []string) bool {
for _, i := range array {
if i == item {
return true
}
}
return false
}
// FindInMetadataSets - find an entity in a list of MD sets and return it and the index
func FindInMetadataSets(metadataSets MdSets, key string) (md *goxml.Xp, index uint8, err error) {
for i := range metadataSets {
index = uint8(i)
md, err = metadataSets[index].MDQ(key)
if err == nil { // if we don't get md not found the last error is as good as the first
return
}
}
return
}
// ReceiveSAMLResponse handles the SAML minutiae when receiving a SAMLResponse
// Currently the only supported binding is POST
// Receives the metadatasets for resp. the sender and the receiver
// Returns metadata for the sender and the receiver
func ReceiveSAMLResponse(r *http.Request, issuerMdSets, destinationMdSets MdSets, location string, xtraCerts []string) (xp, issuerMd, destinationMd *goxml.Xp, relayState string, issuerIndex, destinationIndex uint8, err error) {
return DecodeSAMLMsg(r, issuerMdSets, destinationMdSets, SPRole, []string{"Response"}, location, xtraCerts)
}
// ReceiveLogoutMessage receives the Logout Message
// Receives the metadatasets for resp. the sender and the receiver
// Returns metadata for the sender and the receiver
func ReceiveLogoutMessage(r *http.Request, issuerMdSets, destinationMdSets MdSets, role int) (xp, issuerMd, destinationMd *goxml.Xp, relayState string, issuerIndex, destinationIndex uint8, err error) {
return DecodeSAMLMsg(r, issuerMdSets, destinationMdSets, role, []string{"LogoutRequest", "LogoutResponse"}, "https://"+r.Host+r.URL.Path, nil)
}
// DecodeSAMLMsg decodes the Request. Extracts Issuer, Destination
// Check for Protocol for example (AuthnRequest)
// Validates the schema
// Receives the metadatasets for resp. the sender and the receiver
// Returns metadata for the sender and the receiver
func DecodeSAMLMsg(r *http.Request, issuerMdSets, destinationMdSets MdSets, role int, protocols []string, location string, xtraCerts []string) (xp, issuerMd, destinationMd *goxml.Xp, relayState string, issuerIndex, destinationIndex uint8, err error) {
defer r.Body.Close()
r.ParseForm()
destinationMd, destinationIndex, err = FindInMetadataSets(destinationMdSets, location)
if err != nil {
return
}
var signed bool
switch {
case r.Form.Get("id_token") != "":
xp, relayState, issuerMd, issuerIndex, signed, err = handleOIDCResponse(r, issuerMdSets, destinationMd, location)
if err != nil {
return
}
xp.QueryDashP(nil, "@Flow", "id_token", nil)
default:
method := r.Method
if ok := method == "GET" || method == "POST"; !ok {
err = fmt.Errorf("unsupported http method used '%s'", method)
return
}
relayState = r.Form.Get("RelayState")
var bmsg []byte
msg := r.Form.Get("SAMLRequest") + r.Form.Get("SAMLResponse") // never both at the same time
if msg != "" {
bmsg, err = base64.StdEncoding.DecodeString(msg)
if err != nil {
return
}
if method == "GET" {
bmsg = Inflate(bmsg)
}
xp = goxml.NewXp(bmsg)
} else {
xp, relayState, err = request2samlRequest(r, issuerMdSets, destinationMdSets, location)
if err != nil {
return
}
}
DumpFileIfTracing(r, xp)
//log.Println("stack", goxml.New().Stack(1))
err = xp.SchemaValidate()
if err != nil {
dump("raw", bmsg)
err = goxml.Wrap(err)
return
}
protocol := xp.QueryString(nil, "local-name(/*)")
var protocolOK bool
for _, expectedProtocol := range protocols {
protocolOK = protocolOK || protocol == expectedProtocol
}
if !protocolOK {
err = fmt.Errorf("expected protocol(s) %v not found, got %s", protocols, protocol)
return
}
issuer := xp.Query1(nil, "./saml:Issuer")
if issuer == "" {
err = fmt.Errorf("no issuer found in SAMLRequest/SAMLResponse")
return
}
issuerMd, issuerIndex, err = FindInMetadataSets(issuerMdSets, issuer)
if err != nil {
return
}
xp, signed, err = CheckSAMLMessage(r, xp, issuerMd, destinationMd, role, location, xtraCerts)
if err != nil {
err = goxml.Wrap(err)
return
}
}
if signed { // Bindings 3.4.5.2 Security Considerations and 3.5.5.2 Security Considerations
destination := xp.Query1(nil, "./@Destination")
if destination == "" {
err = fmt.Errorf("no destination found in SAMLRequest/SAMLResponse")
return
}
if destination != location && !strings.HasPrefix(destination, location+"?") { // ignore params ...
err = fmt.Errorf("destination: %s is not here, here is %s", destination, location)
return
}
}
xp, err = checkDestinationAndACS(xp, issuerMd, destinationMd, role, location)
if err != nil {
return
}
xp, err = VerifyTiming(xp, signed)
if err != nil {
return
}
return
}
// CheckSAMLMessage checks for Authentication Requests, Reponses and Logout Requests
// Checks for invalid Bindings. Check for Certificates. Verify Signatures
func CheckSAMLMessage(r *http.Request, xp, issuerMd, destinationMd *goxml.Xp, role int, location string, xtraCerts []string) (validatedMessage *goxml.Xp, signed bool, err error) {
type protoCheckInfoStruct struct {
minSignatures int
service string
signatureElements []string
checks []string
}
protocol := xp.QueryString(nil, "local-name(/*)")
authnRequestChecks := 0
if protocol == "AuthnRequest" && destinationMd.QueryXMLBool(nil, "./md:IDPSSODescriptor/@WantAuthnRequestsSigned") {
authnRequestChecks = 1
}
// add checks for xtra element on top level in tests - does schema checks handle that or should we do it here???
protoChecks := map[string]protoCheckInfoStruct{
"AuthnRequest": {
minSignatures: authnRequestChecks,
service: "md:SingleSignOnService",
signatureElements: []string{"/samlp:AuthnRequest[1]/ds:Signature[1]/..]", ""}},
"Response": {
minSignatures: 1,
service: "md:AssertionConsumerService",
signatureElements: []string{"/samlp:Response[1]/ds:Signature[1]/..", "/samlp:Response[1]/saml:Assertion[1]/ds:Signature[1]/.."},
checks: []string{"count(/samlp:Response/saml:Assertion) = 1", "/samlp:Response/saml:Issuer = /samlp:Response/saml:Assertion/saml:Issuer"}},
"LogoutRequest": {
minSignatures: 0,
service: "md:SingleLogoutService",
signatureElements: []string{"/samlp:LogoutRequest[1]/ds:Signature[1]/..", ""}},
"LogoutResponse": {
minSignatures: 0,
service: "md:SingleLogoutService",
signatureElements: []string{"/samlp:LogoutResponse[1]/ds:Signature[1]/..", ""}},
}
bindings := map[string][]string{
"GET": {REDIRECT},
"POST": {POST},
}
var usedBinding string
validBinding := false
findbinding:
for _, usedBinding = range bindings[r.Method] {
for _, v := range destinationMd.QueryMulti(nil, `./`+Roles[role]+`/`+protoChecks[protocol].service+`[@Location=`+strconv.Quote(location)+`]/@Binding`) {
validBinding = v == usedBinding
if validBinding {
break findbinding
}
}
}
if !validBinding || usedBinding == "" {
err = errors.New("No valid binding found in metadata")
return
}
// the check for SigAlg is mostly for testing. If checking is not enforced by metadata the Signature and SigAlg can just be removed
if protoChecks[protocol].minSignatures <= 0 {
return xp, false, nil
}
certificates := issuerMd.QueryMulti(nil, `./`+Roles[(role+1)%2]+SigningCertQuery) // the issuer's role
certificates = append(certificates, xtraCerts...)
if len(certificates) == 0 {
err = errors.New("no certificates found in metadata")
return
}
switch usedBinding {
case REDIRECT:
{
if err = checkRedirect(parseQueryRaw(r.URL.RawQuery), certificates); err == nil {
validatedMessage = xp
} else if query := protoChecks[protocol].signatureElements[0]; query != "" {
signatures := xp.Query(nil, query)
if len(signatures) == 1 {
if err = VerifySign(xp, certificates, signatures[0]); err != nil {
return
}
validatedMessage = xp
}
}
}
case POST:
{
if query := protoChecks[protocol].signatureElements[0]; query != "" {
signatures := xp.Query(nil, query)
if len(signatures) == 1 {
if err = VerifySign(xp, certificates, signatures[0]); err != nil {
return
}
validatedMessage = xp
}
}
if protocol == "Response" {
encryptedAssertions := xp.Query(nil, "/samlp:Response/saml:EncryptedAssertion")
if len(encryptedAssertions) == 1 {
privatekey, _, err := GetPrivateKeyByMethod(destinationMd, "md:SPSSODescriptor"+EncryptionCertQuery, x509.RSA)
if err != nil {
return nil, false, goxml.Wrap(err)
}
encryptedAssertion := encryptedAssertions[0]
err = xp.Decrypt(encryptedAssertion.(types.Element), privatekey)
if err != nil {
err = goxml.Wrap(err)
err = goxml.PublicError(err.(goxml.Werror), "cause:encryption error") // hide the real problem from attacker
return nil, false, err
}
// repeat schemacheck
err = xp.SchemaValidate()
if err != nil {
err = goxml.Wrap(err)
err = goxml.PublicError(err.(goxml.Werror), "cause:encryption error") // hide the real problem from attacker
return nil, false, err
}
} else if len(encryptedAssertions) != 0 {
err = fmt.Errorf("only 1 EncryptedAssertion allowed, %d found", len(encryptedAssertions))
}
}
// Only Responses with an Assertion will have a second signatureElements query
if query := protoChecks[protocol].signatureElements[1]; query != "" {
signatures := xp.Query(nil, query)
if len(signatures) == 1 {
if err = VerifySign(xp, certificates, signatures[0]); err != nil {
return nil, false, goxml.Wrap(err, "err:unable to validate signature")
}
validatedMessage = xp
}
}
}
}
// if we don't have a validatedResponse by now we are toast
if validatedMessage == nil {
err = goxml.NewWerror("err:no signatures found")
err = goxml.PublicError(err.(goxml.Werror), "cause:encryption error") // hide the real problem from attacker
return nil, false, err
}
for _, check := range protoChecks[protocol].checks {
if !validatedMessage.QueryBool(nil, check) {
return nil, false, goxml.NewWerror("cause: check failed", "check: "+check)
}
}
signed = validatedMessage != nil
return
}
func checkRedirect(params url.Values, certificates []string) (err error) {
signed, delim := "", ""
for _, key := range []string{"SAMLRequest", "RelayState", "SigAlg"} {
if rw, ok := params[key]; ok {
val := rw[0]
signed += delim + key + "=" + val
delim = "&"
}
}
sig, _ := url.QueryUnescape(params.Get("Signature"))
signature, _ := base64.StdEncoding.DecodeString(sig)
sigAlg, _ := url.QueryUnescape(params.Get("SigAlg")) // need to unescape here because the signature uses the escaped value
if _, ok := goxml.SigningMethods[sigAlg]; !ok {
return goxml.NewWerror("unsupported SigAlg", sigAlg)
}
digest := goxml.Hash(goxml.SigningMethods[sigAlg].Hash, signed)
verified := 0
signerrors := []error{}
_, _, pubs, err := PublicKeyInfoByMethod(certificates, goxml.SigningMethods[sigAlg].Type)
if err != nil {
return goxml.Wrap(err)
}
for _, pub := range pubs {
signerror := goxml.Verify(pub, goxml.SigningMethods[sigAlg].Hash, digest[:], signature)
if signerror != nil {
signerrors = append(signerrors, signerror)
} else {
verified++
break
}
}
if verified != 1 {
errorstring := ""
delim := ""
for _, e := range signerrors {
errorstring += e.Error() + delim
delim = ", "
}
err = goxml.NewWerror("cause:unable to validate signature", errorstring)
return
}
return
}
// checkDestinationAndACS checks for valid destination
// Returns Error Otherwise
func checkDestinationAndACS(message, issuerMd, destinationMd *goxml.Xp, role int, location string) (checkedMessage *goxml.Xp, err error) {
var checkedDest string
var acsIndex string
mdRole := "./" + Roles[role]
protocol := message.QueryString(nil, "local-name(/*)")
switch protocol {
case "AuthnRequest":
acs := message.Query1(nil, "@AssertionConsumerServiceURL") // either index or ACSURL + Binding
binding := message.Query1(nil, "@ProtocolBinding")
if binding == "" {
binding = POST
}
if acs == "" {
acsIndex := message.Query1(nil, "@AssertionConsumerServiceIndex")
acs = issuerMd.Query1(nil, `./md:SPSSODescriptor/md:AssertionConsumerService[@index=`+strconv.Quote(acsIndex)+`]/@Location`)
}
if acs == "" {
acs = issuerMd.Query1(nil, `./md:SPSSODescriptor/md:AssertionConsumerService[@Binding=`+strconv.Quote(binding)+` and (@isDefault="true" or @isDefault!="false" or not(@isDefault))]/@Location`)
}