From 9d37a6cc3d916e90ca8dd6fd4d61881227707437 Mon Sep 17 00:00:00 2001 From: Agniva De Sarker Date: Tue, 26 Apr 2022 11:28:49 +0530 Subject: [PATCH] MM-42927: Use new gosaml2 library (#20004) ```release-note NONE ``` Co-authored-by: Mattermod --- go.mod | 2 +- go.sum | 6 +- .../github.com/mattermost/gosaml2/.travis.yml | 11 +- .../github.com/mattermost/gosaml2/README.md | 6 +- .../mattermost/gosaml2/attribute.go | 47 +++ .../mattermost/gosaml2/authn_request.go | 14 + .../gosaml2/build_logout_response.go | 158 +++++++++ .../mattermost/gosaml2/build_request.go | 335 +++++++++++++++++- .../gosaml2/decode_logout_request.go | 85 +++++ .../mattermost/gosaml2/decode_response.go | 138 +++++++- vendor/github.com/mattermost/gosaml2/go.mod | 11 + vendor/github.com/mattermost/gosaml2/go.sum | 36 ++ .../mattermost/gosaml2/logout_request.go | 37 ++ .../mattermost/gosaml2/retrieve_assertion.go | 16 + vendor/github.com/mattermost/gosaml2/saml.go | 101 +++++- .../mattermost/gosaml2/test_constants.go | 23 ++ .../gosaml2/types/encrypted_assertion.go | 16 +- .../mattermost/gosaml2/types/encrypted_key.go | 77 +++- .../mattermost/gosaml2/types/metadata.go | 35 ++ .../mattermost/gosaml2/types/response.go | 33 +- .../mattermost/gosaml2/uuid/uuid.go | 14 + .../github.com/mattermost/gosaml2/validate.go | 78 ++++ .../mattermost/gosaml2/xml_constants.go | 18 +- .../xml-roundtrip-validator/LICENSE.txt | 201 +++++++++++ .../xml-roundtrip-validator/README.md | 73 ++++ .../xml-roundtrip-validator/SECURITY.md | 25 ++ .../mattermost/xml-roundtrip-validator/go.mod | 5 + .../mattermost/xml-roundtrip-validator/go.sum | 12 + .../xml-roundtrip-validator/validator.go | 292 +++++++++++++++ vendor/modules.txt | 4 +- 30 files changed, 1861 insertions(+), 48 deletions(-) create mode 100644 vendor/github.com/mattermost/gosaml2/build_logout_response.go create mode 100644 vendor/github.com/mattermost/gosaml2/decode_logout_request.go create mode 100644 vendor/github.com/mattermost/gosaml2/go.mod create mode 100644 vendor/github.com/mattermost/gosaml2/go.sum create mode 100644 vendor/github.com/mattermost/gosaml2/logout_request.go create mode 100644 vendor/github.com/mattermost/xml-roundtrip-validator/LICENSE.txt create mode 100644 vendor/github.com/mattermost/xml-roundtrip-validator/README.md create mode 100644 vendor/github.com/mattermost/xml-roundtrip-validator/SECURITY.md create mode 100644 vendor/github.com/mattermost/xml-roundtrip-validator/go.mod create mode 100644 vendor/github.com/mattermost/xml-roundtrip-validator/go.sum create mode 100644 vendor/github.com/mattermost/xml-roundtrip-validator/validator.go diff --git a/go.mod b/go.mod index 9bbfd4f430..9cb9f8fd74 100644 --- a/go.mod +++ b/go.mod @@ -63,7 +63,7 @@ require ( github.com/lib/pq v1.10.4 github.com/mailru/easyjson v0.7.7 // indirect github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404 - github.com/mattermost/gosaml2 v0.3.3 + github.com/mattermost/gosaml2 v0.8.0 github.com/mattermost/gziphandler v0.0.1 github.com/mattermost/ldap v0.0.0-20201202150706-ee0e6284187d github.com/mattermost/logr/v2 v2.0.15 diff --git a/go.sum b/go.sum index decba3c85c..3ef775a2bc 100644 --- a/go.sum +++ b/go.sum @@ -977,8 +977,8 @@ github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kN github.com/marstr/guid v1.1.0/go.mod h1:74gB1z2wpxxInTG6yaqA7KrtM0NZ+RbrcqDvYHefzho= github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404 h1:Khvh6waxG1cHc4Cz5ef9n3XVCxRWpAKUtqg9PJl5+y8= github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404/go.mod h1:RyS7FDNQlzF1PsjbJWHRI35exqaKGSO9qD4iv8QjE34= -github.com/mattermost/gosaml2 v0.3.3 h1:ysWrjp08tpWmo6rV2MQ88Eag/Ttjuj91fZsvibF4/Tg= -github.com/mattermost/gosaml2 v0.3.3/go.mod h1:Z429EIOiEi9kbq6yHoApfzlcXpa6dzRDc6pO+Vy2Ksk= +github.com/mattermost/gosaml2 v0.8.0 h1:nkYiByawqwJ7KncK1LDWKwTx5aRarBTQsmH+XcCVsWQ= +github.com/mattermost/gosaml2 v0.8.0/go.mod h1:1nMAdE2Psxaz+pj79Oytayi+hC3aZUi3SmJQlIe+sLM= github.com/mattermost/gziphandler v0.0.1 h1:uXHcXF5agnQ6bXabvpiwwwZOlCYoa7mKHH0lxns/o8w= github.com/mattermost/gziphandler v0.0.1/go.mod h1:CvvZR7sXqhj81V2swXuQY7T04Ccc89u7W7pHNPKev8g= github.com/mattermost/ldap v0.0.0-20201202150706-ee0e6284187d h1:/RJ/UV7M5c7L2TQ0KNm4yZxxFvC1nvRz/gY/Daa35aI= @@ -989,6 +989,8 @@ github.com/mattermost/morph v0.0.0-20220401091636-39f834798da8 h1:gwliVjCTqAC01m github.com/mattermost/morph v0.0.0-20220401091636-39f834798da8/go.mod h1:jxM3g1bx+k2Thz7jofcHguBS8TZn5Pc+o5MGmORObhw= github.com/mattermost/rsc v0.0.0-20160330161541-bbaefb05eaa0 h1:G9tL6JXRBMzjuD1kkBtcnd42kUiT6QDwxfFYu7adM6o= github.com/mattermost/rsc v0.0.0-20160330161541-bbaefb05eaa0/go.mod h1:nV5bfVpT//+B1RPD2JvRnxbkLmJEYXmRaaVl15fsXjs= +github.com/mattermost/xml-roundtrip-validator v0.1.0 h1:RXbVD2UAl7A7nOTR4u7E3ILa4IbtvKBHw64LDsmu9hU= +github.com/mattermost/xml-roundtrip-validator v0.1.0/go.mod h1:qccnGMcpgwcNaBnxqpJpWWUiPNr5H3O8eDgGV9gT5To= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= diff --git a/vendor/github.com/mattermost/gosaml2/.travis.yml b/vendor/github.com/mattermost/gosaml2/.travis.yml index 631959450b..b9b0e6aeea 100644 --- a/vendor/github.com/mattermost/gosaml2/.travis.yml +++ b/vendor/github.com/mattermost/gosaml2/.travis.yml @@ -1,13 +1,10 @@ language: go go: - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x + - 1.17 + - 1.16 + - 1.15 + - 1.14 - tip matrix: diff --git a/vendor/github.com/mattermost/gosaml2/README.md b/vendor/github.com/mattermost/gosaml2/README.md index 2cefd9d7e0..101b1e67d2 100644 --- a/vendor/github.com/mattermost/gosaml2/README.md +++ b/vendor/github.com/mattermost/gosaml2/README.md @@ -1,7 +1,7 @@ # gosaml2 -[![Build Status](https://travis-ci.org/russellhaering/gosaml2.svg?branch=master)](https://travis-ci.org/russellhaering/gosaml2) -[![GoDoc](https://godoc.org/github.com/russellhaering/gosaml2?status.svg)](https://godoc.org/github.com/russellhaering/gosaml2) +[![Build Status](https://github.com/mattermost/gosaml2/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/mattermost/gosaml2/actions/workflows/test.yml?query=branch%3Amain) +[![GoDoc](https://godoc.org/github.com/mattermost/gosaml2?status.svg)](https://godoc.org/github.com/mattermost/gosaml2) SAML 2.0 implemementation for Service Providers based on [etree](https://github.com/beevik/etree) and [goxmldsig](https://github.com/russellhaering/goxmldsig), a pure Go @@ -12,7 +12,7 @@ implementation of XML digital signatures. Install `gosaml2` into your `$GOPATH` using `go get`: ``` -go get github.com/russellhaering/gosaml2 +go get github.com/mattermost/gosaml2 ``` ## Example diff --git a/vendor/github.com/mattermost/gosaml2/attribute.go b/vendor/github.com/mattermost/gosaml2/attribute.go index 1b271cfb8e..6db015351b 100644 --- a/vendor/github.com/mattermost/gosaml2/attribute.go +++ b/vendor/github.com/mattermost/gosaml2/attribute.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 import "github.com/mattermost/gosaml2/types" @@ -17,3 +31,36 @@ func (vals Values) Get(k string) string { } return "" } + +//GetSize returns the number of values for an attribute at a key. +//Returns '0' in case of error or if key is not found. +func (vals Values) GetSize(k string) int { + if vals == nil { + return 0 + } + + v, ok := vals[k] + if ok { + return len(v.Values) + } + + return 0 +} + +//GetAll returns all the values for an attribute at a key. +//Returns an empty slice in case of error of if key is not found. +func (vals Values) GetAll(k string) []string { + var av []string + + if vals == nil { + return av + } + + if v, ok := vals[k]; ok && len(v.Values) > 0 { + for i := 0; i < len(v.Values); i++ { + av = append(av, string(v.Values[i].Value)) + } + } + + return av +} diff --git a/vendor/github.com/mattermost/gosaml2/authn_request.go b/vendor/github.com/mattermost/gosaml2/authn_request.go index 9f8360adc7..096b6b6c2a 100644 --- a/vendor/github.com/mattermost/gosaml2/authn_request.go +++ b/vendor/github.com/mattermost/gosaml2/authn_request.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 import "time" diff --git a/vendor/github.com/mattermost/gosaml2/build_logout_response.go b/vendor/github.com/mattermost/gosaml2/build_logout_response.go new file mode 100644 index 0000000000..e42b6d30b9 --- /dev/null +++ b/vendor/github.com/mattermost/gosaml2/build_logout_response.go @@ -0,0 +1,158 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package saml2 + +import ( + "bytes" + "encoding/base64" + "html/template" + + "github.com/beevik/etree" + "github.com/mattermost/gosaml2/uuid" +) + +func (sp *SAMLServiceProvider) buildLogoutResponse(statusCodeValue string, reqID string, includeSig bool) (*etree.Document, error) { + logoutResponse := &etree.Element{ + Space: "samlp", + Tag: "LogoutResponse", + } + + logoutResponse.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol") + logoutResponse.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion") + + arId := uuid.NewV4() + + logoutResponse.CreateAttr("ID", "_"+arId.String()) + logoutResponse.CreateAttr("Version", "2.0") + logoutResponse.CreateAttr("IssueInstant", sp.Clock.Now().UTC().Format(issueInstantFormat)) + logoutResponse.CreateAttr("Destination", sp.IdentityProviderSLOURL) + logoutResponse.CreateAttr("InResponseTo", reqID) + + // NOTE(russell_h): In earlier versions we mistakenly sent the IdentityProviderIssuer + // in the AuthnRequest. For backwards compatibility we will fall back to that + // behavior when ServiceProviderIssuer isn't set. + if sp.ServiceProviderIssuer != "" { + logoutResponse.CreateElement("saml:Issuer").SetText(sp.ServiceProviderIssuer) + } else { + logoutResponse.CreateElement("saml:Issuer").SetText(sp.IdentityProviderIssuer) + } + + status := logoutResponse.CreateElement("samlp:Status") + statusCode := status.CreateElement("samlp:StatusCode") + statusCode.CreateAttr("Value", statusCodeValue) + + doc := etree.NewDocument() + + // Only POST binding includes in (includeSig) + if includeSig { + signed, err := sp.SignLogoutResponse(logoutResponse) + if err != nil { + return nil, err + } + + doc.SetRoot(signed) + } else { + doc.SetRoot(logoutResponse) + } + return doc, nil +} +func (sp *SAMLServiceProvider) BuildLogoutResponseDocument(status string, reqID string) (*etree.Document, error) { + return sp.buildLogoutResponse(status, reqID, true) +} + +func (sp *SAMLServiceProvider) BuildLogoutResponseDocumentNoSig(status string, reqID string) (*etree.Document, error) { + return sp.buildLogoutResponse(status, reqID, false) +} + +func (sp *SAMLServiceProvider) SignLogoutResponse(el *etree.Element) (*etree.Element, error) { + ctx := sp.SigningContext() + + sig, err := ctx.ConstructSignature(el, true) + if err != nil { + return nil, err + } + + ret := el.Copy() + + var children []etree.Token + children = append(children, ret.Child[0]) // issuer is always first + children = append(children, sig) // next is the signature + children = append(children, ret.Child[1:]...) // then all other children + ret.Child = children + + return ret, nil +} + +func (sp *SAMLServiceProvider) buildLogoutResponseBodyPostFromDocument(relayState string, doc *etree.Document) ([]byte, error) { + respBuf, err := doc.WriteToBytes() + if err != nil { + return nil, err + } + + encodedRespBuf := base64.StdEncoding.EncodeToString(respBuf) + + var tmpl *template.Template + var rv bytes.Buffer + + if relayState != "" { + tmpl = template.Must(template.New("saml-post-form").Parse(`` + + `
` + + `` + + `` + + `` + + `
` + + `` + + `` + + ``)) + data := struct { + URL string + SAMLResponse string + RelayState string + }{ + URL: sp.IdentityProviderSLOURL, + SAMLResponse: encodedRespBuf, + RelayState: relayState, + } + if err = tmpl.Execute(&rv, data); err != nil { + return nil, err + } + } else { + tmpl = template.Must(template.New("saml-post-form").Parse(`` + + `
` + + `` + + `` + + `
` + + `` + + `` + + ``)) + data := struct { + URL string + SAMLResponse string + }{ + URL: sp.IdentityProviderSLOURL, + SAMLResponse: encodedRespBuf, + } + + if err = tmpl.Execute(&rv, data); err != nil { + return nil, err + } + } + + return rv.Bytes(), nil +} + +func (sp *SAMLServiceProvider) BuildLogoutResponseBodyPostFromDocument(relayState string, doc *etree.Document) ([]byte, error) { + return sp.buildLogoutResponseBodyPostFromDocument(relayState, doc) +} diff --git a/vendor/github.com/mattermost/gosaml2/build_request.go b/vendor/github.com/mattermost/gosaml2/build_request.go index 223b622bef..941d63b97f 100644 --- a/vendor/github.com/mattermost/gosaml2/build_request.go +++ b/vendor/github.com/mattermost/gosaml2/build_request.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 import ( @@ -5,6 +19,7 @@ import ( "compress/flate" "encoding/base64" "fmt" + "html/template" "net/http" "net/url" @@ -41,9 +56,9 @@ func (sp *SAMLServiceProvider) buildAuthnRequest(includeSig bool) (*etree.Docume authnRequest.CreateElement("saml:Issuer").SetText(sp.IdentityProviderIssuer) } + nameIdPolicy := authnRequest.CreateElement("samlp:NameIDPolicy") + nameIdPolicy.CreateAttr("AllowCreate", "true") if sp.NameIdFormat != "" { - nameIdPolicy := authnRequest.CreateElement("samlp:NameIDPolicy") - nameIdPolicy.CreateAttr("AllowCreate", "true") nameIdPolicy.CreateAttr("Format", sp.NameIdFormat) } @@ -171,6 +186,7 @@ func (sp *SAMLServiceProvider) buildAuthURLFromDocument(relayState, binding stri qs.Add("Signature", base64.StdEncoding.EncodeToString(rawSignature)) } + //Here the parameters may appear in any order. parsedUrl.RawQuery = qs.Encode() return parsedUrl.String(), nil } @@ -183,6 +199,87 @@ func (sp *SAMLServiceProvider) BuildAuthURLRedirect(relayState string, doc *etre return sp.buildAuthURLFromDocument(relayState, BindingHttpRedirect, doc) } +func (sp *SAMLServiceProvider) buildAuthBodyPostFromDocument(relayState string, doc *etree.Document) ([]byte, error) { + reqBuf, err := doc.WriteToBytes() + if err != nil { + return nil, err + } + + encodedReqBuf := base64.StdEncoding.EncodeToString(reqBuf) + + var tmpl *template.Template + var rv bytes.Buffer + + if relayState != "" { + tmpl = template.Must(template.New("saml-post-form").Parse(`` + + `
` + + `` + + `` + + `` + + `
` + + ``)) + + data := struct { + URL string + SAMLRequest string + RelayState string + }{ + URL: sp.IdentityProviderSSOURL, + SAMLRequest: encodedReqBuf, + RelayState: relayState, + } + if err = tmpl.Execute(&rv, data); err != nil { + return nil, err + } + } else { + tmpl = template.Must(template.New("saml-post-form").Parse(`` + + `
` + + `` + + `` + + `
` + + ``)) + + data := struct { + URL string + SAMLRequest string + }{ + URL: sp.IdentityProviderSSOURL, + SAMLRequest: encodedReqBuf, + } + if err = tmpl.Execute(&rv, data); err != nil { + return nil, err + } + } + + return rv.Bytes(), nil +} + +//BuildAuthBodyPost builds the POST body to be sent to IDP. +func (sp *SAMLServiceProvider) BuildAuthBodyPost(relayState string) ([]byte, error) { + var doc *etree.Document + var err error + + if sp.SignAuthnRequests { + doc, err = sp.BuildAuthRequestDocument() + } else { + doc, err = sp.BuildAuthRequestDocumentNoSig() + } + + if err != nil { + return nil, err + } + + return sp.buildAuthBodyPostFromDocument(relayState, doc) +} + +//BuildAuthBodyPostFromDocument builds the POST body to be sent to IDP. +//It takes the AuthnRequest xml as input. +func (sp *SAMLServiceProvider) BuildAuthBodyPostFromDocument(relayState string, doc *etree.Document) ([]byte, error) { + return sp.buildAuthBodyPostFromDocument(relayState, doc) +} + // BuildAuthURL builds redirect URL to be sent to principal func (sp *SAMLServiceProvider) BuildAuthURL(relayState string) (string, error) { doc, err := sp.BuildAuthRequestDocument() @@ -205,6 +302,240 @@ func (sp *SAMLServiceProvider) AuthRedirect(w http.ResponseWriter, r *http.Reque return nil } +func (sp *SAMLServiceProvider) buildLogoutRequest(includeSig bool, nameID string, sessionIndex string) (*etree.Document, error) { + logoutRequest := &etree.Element{ + Space: "samlp", + Tag: "LogoutRequest", + } + + logoutRequest.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol") + logoutRequest.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion") + + arId := uuid.NewV4() + + logoutRequest.CreateAttr("ID", "_"+arId.String()) + logoutRequest.CreateAttr("Version", "2.0") + logoutRequest.CreateAttr("IssueInstant", sp.Clock.Now().UTC().Format(issueInstantFormat)) + logoutRequest.CreateAttr("Destination", sp.IdentityProviderSLOURL) + + // NOTE(russell_h): In earlier versions we mistakenly sent the IdentityProviderIssuer + // in the AuthnRequest. For backwards compatibility we will fall back to that + // behavior when ServiceProviderIssuer isn't set. + // TODO: Throw error in case Issuer is empty. + if sp.ServiceProviderIssuer != "" { + logoutRequest.CreateElement("saml:Issuer").SetText(sp.ServiceProviderIssuer) + } else { + logoutRequest.CreateElement("saml:Issuer").SetText(sp.IdentityProviderIssuer) + } + + nameId := logoutRequest.CreateElement("saml:NameID") + nameId.SetText(nameID) + nameId.CreateAttr("Format", sp.NameIdFormat) + + //Section 3.7.1 - http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf says + //SessionIndex is optional. If the IDP supports SLO then it must send SessionIndex as per + //Section 4.1.4.2 of https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf. + //As per section 4.4.3.1 of //docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf, + //a LogoutRequest issued by Session Participant to Identity Provider, must contain + //at least one SessionIndex element needs to be included. + nameId = logoutRequest.CreateElement("samlp:SessionIndex") + nameId.SetText(sessionIndex) + + doc := etree.NewDocument() + + if includeSig { + signed, err := sp.SignLogoutRequest(logoutRequest) + if err != nil { + return nil, err + } + + doc.SetRoot(signed) + } else { + doc.SetRoot(logoutRequest) + } + + return doc, nil +} + +func (sp *SAMLServiceProvider) SignLogoutRequest(el *etree.Element) (*etree.Element, error) { + ctx := sp.SigningContext() + + sig, err := ctx.ConstructSignature(el, true) + if err != nil { + return nil, err + } + + ret := el.Copy() + + var children []etree.Token + children = append(children, ret.Child[0]) // issuer is always first + children = append(children, sig) // next is the signature + children = append(children, ret.Child[1:]...) // then all other children + ret.Child = children + + return ret, nil +} + +func (sp *SAMLServiceProvider) BuildLogoutRequestDocumentNoSig(nameID string, sessionIndex string) (*etree.Document, error) { + return sp.buildLogoutRequest(false, nameID, sessionIndex) +} + +func (sp *SAMLServiceProvider) BuildLogoutRequestDocument(nameID string, sessionIndex string) (*etree.Document, error) { + return sp.buildLogoutRequest(true, nameID, sessionIndex) +} + +//BuildLogoutBodyPostFromDocument builds the POST body to be sent to IDP. +//It takes the LogoutRequest xml as input. +func (sp *SAMLServiceProvider) BuildLogoutBodyPostFromDocument(relayState string, doc *etree.Document) ([]byte, error) { + return sp.buildLogoutBodyPostFromDocument(relayState, doc) +} + +func (sp *SAMLServiceProvider) buildLogoutBodyPostFromDocument(relayState string, doc *etree.Document) ([]byte, error) { + reqBuf, err := doc.WriteToBytes() + if err != nil { + return nil, err + } + + encodedReqBuf := base64.StdEncoding.EncodeToString(reqBuf) + var tmpl *template.Template + var rv bytes.Buffer + + if relayState != "" { + tmpl = template.Must(template.New("saml-post-form").Parse(`` + + `
` + + `` + + `` + + `` + + `
` + + ``)) + + data := struct { + URL string + SAMLRequest string + RelayState string + }{ + URL: sp.IdentityProviderSLOURL, + SAMLRequest: encodedReqBuf, + RelayState: relayState, + } + if err = tmpl.Execute(&rv, data); err != nil { + return nil, err + } + } else { + tmpl = template.Must(template.New("saml-post-form").Parse(`` + + `
` + + `` + + `` + + `
` + + ``)) + + data := struct { + URL string + SAMLRequest string + }{ + URL: sp.IdentityProviderSLOURL, + SAMLRequest: encodedReqBuf, + } + if err = tmpl.Execute(&rv, data); err != nil { + return nil, err + } + } + + return rv.Bytes(), nil +} + +func (sp *SAMLServiceProvider) BuildLogoutURLRedirect(relayState string, doc *etree.Document) (string, error) { + return sp.buildLogoutURLFromDocument(relayState, BindingHttpRedirect, doc) +} + +func (sp *SAMLServiceProvider) buildLogoutURLFromDocument(relayState, binding string, doc *etree.Document) (string, error) { + parsedUrl, err := url.Parse(sp.IdentityProviderSLOURL) + if err != nil { + return "", err + } + + logoutRequest, err := doc.WriteToString() + if err != nil { + return "", err + } + + buf := &bytes.Buffer{} + + fw, err := flate.NewWriter(buf, flate.DefaultCompression) + if err != nil { + return "", fmt.Errorf("flate NewWriter error: %v", err) + } + + _, err = fw.Write([]byte(logoutRequest)) + if err != nil { + return "", fmt.Errorf("flate.Writer Write error: %v", err) + } + + err = fw.Close() + if err != nil { + return "", fmt.Errorf("flate.Writer Close error: %v", err) + } + + qs := parsedUrl.Query() + + qs.Add("SAMLRequest", base64.StdEncoding.EncodeToString(buf.Bytes())) + + if relayState != "" { + qs.Add("RelayState", relayState) + } + + if binding == BindingHttpRedirect { + // Sign URL encoded query (see Section 3.4.4.1 DEFLATE Encoding of saml-bindings-2.0-os.pdf) + ctx := sp.SigningContext() + qs.Add("SigAlg", ctx.GetSignatureMethodIdentifier()) + var rawSignature []byte + //qs.Encode() sorts the keys (See https://golang.org/pkg/net/url/#Values.Encode). + //If RelayState parameter is present then RelayState parameter + //will be put first by Encode(). Hence encode them separately and concatenate. + //Signature string has to have parameters in the order - SAMLRequest=value&RelayState=value&SigAlg=value. + //(See Section 3.4.4.1 saml-bindings-2.0-os.pdf). + var orderedParams = []string{"SAMLRequest", "RelayState", "SigAlg"} + + var paramValueMap = make(map[string]string) + paramValueMap["SAMLRequest"] = base64.StdEncoding.EncodeToString(buf.Bytes()) + if relayState != "" { + paramValueMap["RelayState"] = relayState + } + paramValueMap["SigAlg"] = ctx.GetSignatureMethodIdentifier() + + ss := "" + + for _, k := range orderedParams { + v, ok := paramValueMap[k] + if ok { + //Add the value after URL encoding. + u := url.Values{} + u.Add(k, v) + e := u.Encode() + if ss != "" { + ss += "&" + e + } else { + ss = e + } + } + } + + //Now generate the signature on the string of ordered parameters. + if rawSignature, err = ctx.SignString(ss); err != nil { + return "", fmt.Errorf("unable to sign query string of redirect URL: %v", err) + } + + // Now add base64 encoded Signature + qs.Add("Signature", base64.StdEncoding.EncodeToString(rawSignature)) + } + + //Here the parameters may appear in any order. + parsedUrl.RawQuery = qs.Encode() + return parsedUrl.String(), nil +} + // signatureInputString constructs the string to be fed into the signature algorithm, as described // in section 3.4.4.1 of // https://www.oasis-open.org/committees/download.php/56779/sstc-saml-bindings-errata-2.0-wd-06.pdf diff --git a/vendor/github.com/mattermost/gosaml2/decode_logout_request.go b/vendor/github.com/mattermost/gosaml2/decode_logout_request.go new file mode 100644 index 0000000000..b1eacc74f9 --- /dev/null +++ b/vendor/github.com/mattermost/gosaml2/decode_logout_request.go @@ -0,0 +1,85 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package saml2 + +import ( + "encoding/base64" + "fmt" + + dsig "github.com/russellhaering/goxmldsig" +) + +func (sp *SAMLServiceProvider) validateLogoutRequestAttributes(request *LogoutRequest) error { + if request.Destination != "" && request.Destination != sp.ServiceProviderSLOURL { + return ErrInvalidValue{ + Key: DestinationAttr, + Expected: sp.ServiceProviderSLOURL, + Actual: request.Destination, + } + } + + if request.Version != "2.0" { + return ErrInvalidValue{ + Reason: ReasonUnsupported, + Key: "SAML version", + Expected: "2.0", + Actual: request.Version, + } + } + + return nil +} + +func (sp *SAMLServiceProvider) ValidateEncodedLogoutRequestPOST(encodedRequest string) (*LogoutRequest, error) { + raw, err := base64.StdEncoding.DecodeString(encodedRequest) + if err != nil { + return nil, err + } + + // Parse the raw request - parseResponse is generic + doc, el, err := parseResponse(raw) + if err != nil { + return nil, err + } + + var requestSignatureValidated bool + if !sp.SkipSignatureValidation { + el, err = sp.validateElementSignature(el) + if err == dsig.ErrMissingSignature { + // Unfortunately we just blew away our Response + el = doc.Root() + } else if err != nil { + return nil, err + } else if el == nil { + return nil, fmt.Errorf("missing transformed logout request") + } else { + requestSignatureValidated = true + } + } + + decodedRequest := &LogoutRequest{} + err = xmlUnmarshalElement(el, decodedRequest) + if err != nil { + return nil, fmt.Errorf("unable to unmarshal logout request: %v", err) + } + decodedRequest.SignatureValidated = requestSignatureValidated + + err = sp.ValidateDecodedLogoutRequest(decodedRequest) + if err != nil { + return nil, err + } + + return decodedRequest, nil +} diff --git a/vendor/github.com/mattermost/gosaml2/decode_response.go b/vendor/github.com/mattermost/gosaml2/decode_response.go index 8698056860..bf0aca60dd 100644 --- a/vendor/github.com/mattermost/gosaml2/decode_response.go +++ b/vendor/github.com/mattermost/gosaml2/decode_response.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 import ( @@ -13,6 +27,7 @@ import ( "github.com/beevik/etree" "github.com/mattermost/gosaml2/types" + rtvalidator "github.com/mattermost/xml-roundtrip-validator" dsig "github.com/russellhaering/goxmldsig" "github.com/russellhaering/goxmldsig/etreeutils" ) @@ -46,6 +61,29 @@ func (sp *SAMLServiceProvider) validateResponseAttributes(response *types.Respon return nil } +// validateLogoutResponseAttributes validates a SAML Response's tag and attributes. It does +// not inspect child elements of the Response at all. +func (sp *SAMLServiceProvider) validateLogoutResponseAttributes(response *types.LogoutResponse) error { + if response.Destination != "" && response.Destination != sp.ServiceProviderSLOURL { + return ErrInvalidValue{ + Key: DestinationAttr, + Expected: sp.ServiceProviderSLOURL, + Actual: response.Destination, + } + } + + if response.Version != "2.0" { + return ErrInvalidValue{ + Reason: ReasonUnsupported, + Key: "SAML version", + Expected: "2.0", + Actual: response.Version, + } + } + + return nil +} + func xmlUnmarshalElement(el *etree.Element, obj interface{}) error { doc := etree.NewDocument() doc.SetRoot(el) @@ -151,11 +189,7 @@ func (sp *SAMLServiceProvider) decryptAssertions(el *etree.Element) error { return nil } - if err := etreeutils.NSFindIterate(el, SAMLAssertionNamespace, EncryptedAssertionTag, decryptAssertion); err != nil { - return err - } else { - return nil - } + return etreeutils.NSFindIterate(el, SAMLAssertionNamespace, EncryptedAssertionTag, decryptAssertion) } func (sp *SAMLServiceProvider) validateElementSignature(el *etree.Element) (*etree.Element, error) { @@ -166,7 +200,11 @@ func (sp *SAMLServiceProvider) validateAssertionSignatures(el *etree.Element) er signedAssertions := 0 unsignedAssertions := 0 validateAssertion := func(ctx etreeutils.NSContext, unverifiedAssertion *etree.Element) error { - if unverifiedAssertion.Parent() != el { + parent := unverifiedAssertion.Parent() + if parent == nil { + return fmt.Errorf("parent is nil") + } + if parent != el { return fmt.Errorf("found assertion with unexpected parent element: %s", unverifiedAssertion.Parent().Tag) } @@ -223,6 +261,24 @@ func (sp *SAMLServiceProvider) ValidateEncodedResponse(encodedResponse string) ( return nil, err } + elAssertion, err := etreeutils.NSFindOne(el, SAMLAssertionNamespace, AssertionTag) + if err != nil { + return nil, err + } + elEncAssertion, err := etreeutils.NSFindOne(el, SAMLAssertionNamespace, EncryptedAssertionTag) + if err != nil { + return nil, err + } + // We verify that either one of assertion or encrypted assertion elements are present, + // but not both. + if (elAssertion == nil) == (elEncAssertion == nil) { + return nil, fmt.Errorf("found both or no assertion and encrypted assertion elements") + } + // And if a decryptCert is present, then it's only encrypted assertion elements. + if sp.SPKeyStore != nil && elAssertion != nil { + return nil, fmt.Errorf("all assertions are not encrypted") + } + var responseSignatureValidated bool if !sp.SkipSignatureValidation { el, err = sp.validateElementSignature(el) @@ -319,9 +375,11 @@ func maybeDeflate(data []byte, decoder func([]byte) error) error { // parseResponse is a helper function that was refactored out so that the XML parsing behavior can be isolated and unit tested func parseResponse(xml []byte) (*etree.Document, *etree.Element, error) { var doc *etree.Document + var rawXML []byte err := maybeDeflate(xml, func(xml []byte) error { doc = etree.NewDocument() + rawXML = xml return doc.ReadFromBytes(xml) }) if err != nil { @@ -333,5 +391,73 @@ func parseResponse(xml []byte) (*etree.Document, *etree.Element, error) { return nil, nil, fmt.Errorf("unable to parse response") } + // Examine the response for attempts to exploit weaknesses in Go's encoding/xml + err = rtvalidator.Validate(bytes.NewReader(rawXML)) + if err != nil { + return nil, nil, err + } + return doc, el, nil } + +// DecodeUnverifiedLogoutResponse decodes several attributes from a SAML Logout response, without doing any verifications. +func DecodeUnverifiedLogoutResponse(encodedResponse string) (*types.LogoutResponse, error) { + raw, err := base64.StdEncoding.DecodeString(encodedResponse) + if err != nil { + return nil, err + } + + var response *types.LogoutResponse + + err = maybeDeflate(raw, func(maybeXML []byte) error { + response = &types.LogoutResponse{} + return xml.Unmarshal(maybeXML, response) + }) + if err != nil { + return nil, err + } + + return response, nil +} + +func (sp *SAMLServiceProvider) ValidateEncodedLogoutResponsePOST(encodedResponse string) (*types.LogoutResponse, error) { + raw, err := base64.StdEncoding.DecodeString(encodedResponse) + if err != nil { + return nil, err + } + + // Parse the raw response + doc, el, err := parseResponse(raw) + if err != nil { + return nil, err + } + + var responseSignatureValidated bool + if !sp.SkipSignatureValidation { + el, err = sp.validateElementSignature(el) + if err == dsig.ErrMissingSignature { + // Unfortunately we just blew away our Response + el = doc.Root() + } else if err != nil { + return nil, err + } else if el == nil { + return nil, fmt.Errorf("missing transformed logout response") + } else { + responseSignatureValidated = true + } + } + + decodedResponse := &types.LogoutResponse{} + err = xmlUnmarshalElement(el, decodedResponse) + if err != nil { + return nil, fmt.Errorf("unable to unmarshal logout response: %v", err) + } + decodedResponse.SignatureValidated = responseSignatureValidated + + err = sp.ValidateDecodedLogoutResponse(decodedResponse) + if err != nil { + return nil, err + } + + return decodedResponse, nil +} diff --git a/vendor/github.com/mattermost/gosaml2/go.mod b/vendor/github.com/mattermost/gosaml2/go.mod new file mode 100644 index 0000000000..14a4e9945c --- /dev/null +++ b/vendor/github.com/mattermost/gosaml2/go.mod @@ -0,0 +1,11 @@ +module github.com/mattermost/gosaml2 + +go 1.13 + +require ( + github.com/beevik/etree v1.1.0 + github.com/jonboulle/clockwork v0.2.2 + github.com/mattermost/xml-roundtrip-validator v0.1.0 + github.com/russellhaering/goxmldsig v1.2.0 + github.com/stretchr/testify v1.6.1 +) diff --git a/vendor/github.com/mattermost/gosaml2/go.sum b/vendor/github.com/mattermost/gosaml2/go.sum new file mode 100644 index 0000000000..16df0ef211 --- /dev/null +++ b/vendor/github.com/mattermost/gosaml2/go.sum @@ -0,0 +1,36 @@ +github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs= +github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= +github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mattermost/xml-roundtrip-validator v0.1.0 h1:RXbVD2UAl7A7nOTR4u7E3ILa4IbtvKBHw64LDsmu9hU= +github.com/mattermost/xml-roundtrip-validator v0.1.0/go.mod h1:qccnGMcpgwcNaBnxqpJpWWUiPNr5H3O8eDgGV9gT5To= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/russellhaering/goxmldsig v1.2.0 h1:Y6GTTc9Un5hCxSzVz4UIWQ/zuVwDvzJk80guqzwx6Vg= +github.com/russellhaering/goxmldsig v1.2.0/go.mod h1:gM4MDENBQf7M+V824SGfyIUVFWydB7n0KkEubVJl+Tw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/mattermost/gosaml2/logout_request.go b/vendor/github.com/mattermost/gosaml2/logout_request.go new file mode 100644 index 0000000000..7dd4d35f79 --- /dev/null +++ b/vendor/github.com/mattermost/gosaml2/logout_request.go @@ -0,0 +1,37 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package saml2 + +import ( + "encoding/xml" + "github.com/mattermost/gosaml2/types" + "time" +) + +// LogoutRequest is the go struct representation of a logout request +type LogoutRequest struct { + XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol LogoutRequest"` + ID string `xml:"ID,attr"` + Version string `xml:"Version,attr"` + //ProtocolBinding string `xml:",attr"` + + IssueInstant time.Time `xml:"IssueInstant,attr"` + + Destination string `xml:"Destination,attr"` + Issuer *types.Issuer `xml:"Issuer"` + + NameID *types.NameID `xml:"NameID"` + SignatureValidated bool `xml:"-"` // not read, not dumped +} diff --git a/vendor/github.com/mattermost/gosaml2/retrieve_assertion.go b/vendor/github.com/mattermost/gosaml2/retrieve_assertion.go index 3da3e36e63..af70aa6df7 100644 --- a/vendor/github.com/mattermost/gosaml2/retrieve_assertion.go +++ b/vendor/github.com/mattermost/gosaml2/retrieve_assertion.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 import "fmt" @@ -88,6 +102,8 @@ func (sp *SAMLServiceProvider) RetrieveAssertionInfo(encodedResponse string) (*A if assertion.AuthnStatement.SessionNotOnOrAfter != nil { assertionInfo.SessionNotOnOrAfter = assertion.AuthnStatement.SessionNotOnOrAfter } + + assertionInfo.SessionIndex = assertion.AuthnStatement.SessionIndex } assertionInfo.WarningInfo = warningInfo diff --git a/vendor/github.com/mattermost/gosaml2/saml.go b/vendor/github.com/mattermost/gosaml2/saml.go index d9ff05fb12..f2bb7b3a6d 100644 --- a/vendor/github.com/mattermost/gosaml2/saml.go +++ b/vendor/github.com/mattermost/gosaml2/saml.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 import ( @@ -23,10 +37,14 @@ func (serr ErrSaml) Error() string { } type SAMLServiceProvider struct { - IdentityProviderSSOURL string - IdentityProviderIssuer string + IdentityProviderSSOURL string + IdentityProviderSSOBinding string + IdentityProviderSLOURL string + IdentityProviderSLOBinding string + IdentityProviderIssuer string AssertionConsumerServiceURL string + ServiceProviderSLOURL string ServiceProviderIssuer string SignAuthnRequests bool @@ -70,6 +88,62 @@ type RequestedAuthnContext struct { } func (sp *SAMLServiceProvider) Metadata() (*types.EntityDescriptor, error) { + keyDescriptors := make([]types.KeyDescriptor, 0, 2) + if sp.GetSigningKey() != nil { + signingCertBytes, err := sp.GetSigningCertBytes() + if err != nil { + return nil, err + } + keyDescriptors = append(keyDescriptors, types.KeyDescriptor{ + Use: "signing", + KeyInfo: dsigtypes.KeyInfo{ + X509Data: dsigtypes.X509Data{ + X509Certificates: []dsigtypes.X509Certificate{{ + Data: base64.StdEncoding.EncodeToString(signingCertBytes), + }}, + }, + }, + }) + } + if sp.GetEncryptionKey() != nil { + encryptionCertBytes, err := sp.GetEncryptionCertBytes() + if err != nil { + return nil, err + } + keyDescriptors = append(keyDescriptors, types.KeyDescriptor{ + Use: "encryption", + KeyInfo: dsigtypes.KeyInfo{ + X509Data: dsigtypes.X509Data{ + X509Certificates: []dsigtypes.X509Certificate{{ + Data: base64.StdEncoding.EncodeToString(encryptionCertBytes), + }}, + }, + }, + EncryptionMethods: []types.EncryptionMethod{ + {Algorithm: types.MethodAES128GCM}, + {Algorithm: types.MethodAES128CBC}, + {Algorithm: types.MethodAES256CBC}, + }, + }) + } + return &types.EntityDescriptor{ + ValidUntil: time.Now().UTC().Add(time.Hour * 24 * 7), // 7 days + EntityID: sp.ServiceProviderIssuer, + SPSSODescriptor: &types.SPSSODescriptor{ + AuthnRequestsSigned: sp.SignAuthnRequests, + WantAssertionsSigned: !sp.SkipSignatureValidation, + ProtocolSupportEnumeration: SAMLProtocolNamespace, + KeyDescriptors: keyDescriptors, + AssertionConsumerServices: []types.IndexedEndpoint{{ + Binding: BindingHttpPost, + Location: sp.AssertionConsumerServiceURL, + Index: 1, + }}, + }, + }, nil +} + +func (sp *SAMLServiceProvider) MetadataWithSLO(validityHours int64) (*types.EntityDescriptor, error) { signingCertBytes, err := sp.GetSigningCertBytes() if err != nil { return nil, err @@ -78,8 +152,14 @@ func (sp *SAMLServiceProvider) Metadata() (*types.EntityDescriptor, error) { if err != nil { return nil, err } + + if validityHours <= 0 { + //By default let's keep it to 7 days. + validityHours = int64(time.Hour * 24 * 7) + } + return &types.EntityDescriptor{ - ValidUntil: time.Now().UTC().Add(time.Hour * 24 * 7), // 7 days + ValidUntil: time.Now().UTC().Add(time.Duration(validityHours)), // default 7 days EntityID: sp.ServiceProviderIssuer, SPSSODescriptor: &types.SPSSODescriptor{ AuthnRequestsSigned: sp.SignAuthnRequests, @@ -90,7 +170,7 @@ func (sp *SAMLServiceProvider) Metadata() (*types.EntityDescriptor, error) { Use: "signing", KeyInfo: dsigtypes.KeyInfo{ X509Data: dsigtypes.X509Data{ - X509Certificates: []dsigtypes.X509Certificate{dsigtypes.X509Certificate{ + X509Certificates: []dsigtypes.X509Certificate{{ Data: base64.StdEncoding.EncodeToString(signingCertBytes), }}, }, @@ -100,15 +180,15 @@ func (sp *SAMLServiceProvider) Metadata() (*types.EntityDescriptor, error) { Use: "encryption", KeyInfo: dsigtypes.KeyInfo{ X509Data: dsigtypes.X509Data{ - X509Certificates: []dsigtypes.X509Certificate{dsigtypes.X509Certificate{ + X509Certificates: []dsigtypes.X509Certificate{{ Data: base64.StdEncoding.EncodeToString(encryptionCertBytes), }}, }, }, EncryptionMethods: []types.EncryptionMethod{ - {Algorithm: types.MethodAES128GCM}, - {Algorithm: types.MethodAES128CBC}, - {Algorithm: types.MethodAES256CBC}, + {Algorithm: types.MethodAES128GCM, DigestMethod: nil}, + {Algorithm: types.MethodAES128CBC, DigestMethod: nil}, + {Algorithm: types.MethodAES256CBC, DigestMethod: nil}, }, }, }, @@ -117,6 +197,10 @@ func (sp *SAMLServiceProvider) Metadata() (*types.EntityDescriptor, error) { Location: sp.AssertionConsumerServiceURL, Index: 1, }}, + SingleLogoutServices: []types.Endpoint{{ + Binding: BindingHttpPost, + Location: sp.ServiceProviderSLOURL, + }}, }, }, nil } @@ -189,6 +273,7 @@ type AssertionInfo struct { NameID string Values Values WarningInfo *WarningInfo + SessionIndex string AuthnInstant *time.Time SessionNotOnOrAfter *time.Time Assertions []types.Assertion diff --git a/vendor/github.com/mattermost/gosaml2/test_constants.go b/vendor/github.com/mattermost/gosaml2/test_constants.go index cee10012db..871e9713ce 100644 --- a/vendor/github.com/mattermost/gosaml2/test_constants.go +++ b/vendor/github.com/mattermost/gosaml2/test_constants.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 var idpCertificate = ` @@ -393,3 +407,12 @@ DJpRaioUTd2lGh4TLUxAxCxtUk/pascL+3Nn936LFmUCLxaxnbeGzPOXAhscCtU1H0nFsXRnKx5a cPXYSKFZZZktieSkww2Oi8dg2DYaQhGQMSFMVqgVfwEu4bvCRBvdSiNXdWGCZQmFVzBZZ/9rOLzP pvTFTPnpkavJm81FLlUhiE/oFgKlCDLWDknSpXAI0uZGERcwPca6xvIMh86LjQKjbVci9FYDStXC qRnqQ+TccSu/B6uONFsDEngGcXSKfB+aphoebe.simon@scaleft.com.evil.com123urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransportPhoebeSimonphoebe.simon@scaleft.comphoebesimon` + +const doubleColonAssertionInjectionAttackResponse = ` + +https://app.onelogin.com/saml/metadata/634027 + +<::Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0" ID="x" IssueInstant="2017-03-08T07:53:39Z">https://app.onelogin.com/saml/metadata/634027gd5V090n/m4JRrtpo5WgrwPyyy0=what@launchdarkly.com{audience}urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport +https://app.onelogin.com/saml/metadata/634027gd5V090n/m4JRrtpo5WgrwPyyy0=SLzvdNM+1R1+3XsXpC+/RIvb5L4Lhy7Eb7caPG2CLMPYhzbKLAwIiT7/0fEMO/xL7rdIgEShbcU9iu5PX4hGYBhirsFIZvdHytns5+JKHnlVBmHm4TsSU1z+dGMXBa//L0KFSrvdgBUpsr5vs50SuYnnVp61VN+zCLMqO221CQfP95QyMcSQ+fiyq4GOmWLwQy1m1+NV3U8zlapp6FIH5stW/dp4OqpRdafV96rVwmmR4yeUw7VAzbJuMrPgkXO9nUbHeMUTgQxkQ4ThzG5jt6fT+Ro1NOYS4zpVtzqlQwGzqWxQVRLEqXIf500/Qi0NuFQOW42ZAUiXDgdLENTVGA==MIIEJjCCAw6gAwIBAgIUOHrykO4ce1TbjvGgXXVVnR4NsqMwDQYJKoZIhvcNAQEFBQAwXTELMAkGA1UEBhMCVVMxFTATBgNVBAoMDExhdW5jaERhcmtseTEVMBMGA1UECwwMT25lTG9naW4gSWRQMSAwHgYDVQQDDBdPbmVMb2dpbiBBY2NvdW50IDEwMjEyNzAeFw0xNzAzMDYwMjQ2NTNaFw0yMjAzMDcwMjQ2NTNaMF0xCzAJBgNVBAYTAlVTMRUwEwYDVQQKDAxMYXVuY2hEYXJrbHkxFTATBgNVBAsMDE9uZUxvZ2luIElkUDEgMB4GA1UEAwwXT25lTG9naW4gQWNjb3VudCAxMDIxMjcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCaJ02AnJe5vq+zzkmrIHhRy8V/UxJogbJGEJW6nqrEmO7Q4sXO7dLIKxGccCEz0KAavGKWzSX9uhVvKpazpD4bW80wPQIgFxN3CjiA3qlYIfhhh4emSZo2AnaTuG4BPVGFNPx0jxXGAhh/3xkpIsqARJFPB6njT2+MwFctm3fockx3Yp4e1xoUD8qQR0f/8oq1LjrYd2Vlckmmw7qrzSqS8POHW/I1jx9Y/vAjTPWDKXmbmLcTe3188PDrthSyoBuaAGBRVTP9WTuYMh4kGvmfX6sNvIDGejUcUCq6IObRr4xLSZiGy5uoyqsQc9agAhQm+26Gpq0R3NSvN91JdbZHAgMBAAGjgd0wgdowDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUnbxBsHgNVq3OSXEuG5EkR0Jd1UswgZoGA1UdIwSBkjCBj4AUnbxBsHgNVq3OSXEuG5EkR0Jd1UuhYaRfMF0xCzAJBgNVBAYTAlVTMRUwEwYDVQQKDAxMYXVuY2hEYXJrbHkxFTATBgNVBAsMDE9uZUxvZ2luIElkUDEgMB4GA1UEAwwXT25lTG9naW4gQWNjb3VudCAxMDIxMjeCFDh68pDuHHtU247xoF11VZ0eDbKjMA4GA1UdDwEB/wQEAwIHgDANBgkqhkiG9w0BAQUFAAOCAQEAL/6j2qpMCrnolwKT7mfPEpA6btbtl0R0t6zSwYUVU9T3PK0/P3LKXvbjSySov0E4R9d5qlOcyj5CbYiuqAO2aON3xy82s0dN3FHRiO6kcjoRPwVIIF0S8x7tpzcPKa42zSPfBqMRw4ezUEzTijFriepkSWST1Btr3QeK2Cxhr0fC1xmw/YK82BV0/oVRslGL27ro+v3/dNY0A0r32Xe2+THomrY/YaZaDCPCjHo8dlxrX3D/mPfoiiKSkm2mGagQXT0giTHVo3oIq+u+KdrBcQn65EBcjfFKDIeFCdiVmO0xPl9mmWskVRLy2/wpuDIp6hnAphl9lj5DY48eBsrEXQ==arun@launchdarkly.com{audience}urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport + +` diff --git a/vendor/github.com/mattermost/gosaml2/types/encrypted_assertion.go b/vendor/github.com/mattermost/gosaml2/types/encrypted_assertion.go index 9bc056d497..daeb77b8ef 100644 --- a/vendor/github.com/mattermost/gosaml2/types/encrypted_assertion.go +++ b/vendor/github.com/mattermost/gosaml2/types/encrypted_assertion.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package types import ( @@ -48,7 +62,7 @@ func (ea *EncryptedAssertion) DecryptBytes(cert *tls.Certificate) ([]byte, error return nil, fmt.Errorf("cannot open AES-GCM: %s", err) } return plainText, nil - case MethodAES128CBC, MethodAES256CBC: + case MethodAES128CBC, MethodAES256CBC, MethodTripleDESCBC: nonce, data := data[:k.BlockSize()], data[k.BlockSize():] c := cipher.NewCBCDecrypter(k, nonce) c.CryptBlocks(data, data) diff --git a/vendor/github.com/mattermost/gosaml2/types/encrypted_key.go b/vendor/github.com/mattermost/gosaml2/types/encrypted_key.go index dde68a8ed0..a33b96de4d 100644 --- a/vendor/github.com/mattermost/gosaml2/types/encrypted_key.go +++ b/vendor/github.com/mattermost/gosaml2/types/encrypted_key.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package types import ( @@ -28,8 +42,13 @@ type EncryptedKey struct { //EncryptionMethod specifies the type of encryption that was used. type EncryptionMethod struct { - Algorithm string `xml:",attr,omitempty"` - DigestMethod DigestMethod `xml:",omitempty"` + Algorithm string `xml:",attr,omitempty"` + //Digest method is present for algorithms like RSA-OAEP. + //See https://www.w3.org/TR/xmlenc-core1/. + //To convey the digest methods an entity supports, + //DigestMethod in extensions element is used. + //See http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-metadata-algsupport.html. + DigestMethod *DigestMethod `xml:",omitempty"` } //DigestMethod is a digest type specification @@ -41,13 +60,15 @@ type DigestMethod struct { const ( MethodRSAOAEP = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" MethodRSAOAEP2 = "http://www.w3.org/2009/xmlenc11#rsa-oaep" + MethodRSAv1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5" ) //Well-known private key encryption methods const ( - MethodAES128GCM = "http://www.w3.org/2009/xmlenc11#aes128-gcm" - MethodAES128CBC = "http://www.w3.org/2001/04/xmlenc#aes128-cbc" - MethodAES256CBC = "http://www.w3.org/2001/04/xmlenc#aes256-cbc" + MethodAES128GCM = "http://www.w3.org/2009/xmlenc11#aes128-gcm" + MethodAES128CBC = "http://www.w3.org/2001/04/xmlenc#aes128-cbc" + MethodAES256CBC = "http://www.w3.org/2001/04/xmlenc#aes256-cbc" + MethodTripleDESCBC = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" ) //Well-known hash methods @@ -105,16 +126,22 @@ func (ek *EncryptedKey) DecryptSymmetricKey(cert *tls.Certificate) (cipher.Block case *rsa.PrivateKey: var h hash.Hash - switch ek.EncryptionMethod.DigestMethod.Algorithm { - case "", MethodSHA1: - h = sha1.New() // default - case MethodSHA256: - h = sha256.New() - case MethodSHA512: - h = sha512.New() - default: - return nil, fmt.Errorf("unsupported digest algorithm: %v", - ek.EncryptionMethod.DigestMethod.Algorithm) + if ek.EncryptionMethod.DigestMethod == nil { + //if digest method is not present lets set default method to SHA1. + //Digest method is used by methods like RSA-OAEP. + h = sha1.New() + } else { + switch ek.EncryptionMethod.DigestMethod.Algorithm { + case "", MethodSHA1: + h = sha1.New() // default + case MethodSHA256: + h = sha256.New() + case MethodSHA512: + h = sha512.New() + default: + return nil, fmt.Errorf("unsupported digest algorithm: %v", + ek.EncryptionMethod.DigestMethod.Algorithm) + } } switch ek.EncryptionMethod.Algorithm { @@ -131,6 +158,26 @@ func (ek *EncryptedKey) DecryptSymmetricKey(cert *tls.Certificate) (cipher.Block return nil, err } + return b, nil + case MethodRSAv1_5: + pt, err := rsa.DecryptPKCS1v15(rand.Reader, pk, cipherText) + if err != nil { + return nil, fmt.Errorf("rsa internal error: %v", err) + } + + //From https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf the xml encryption + //methods to be supported are from http://www.w3.org/2001/04/xmlenc#Element. + //https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#Element. + //https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/#sec-Algorithms + //Sec 5.4 Key Transport: + //The RSA v1.5 Key Transport algorithm given below are those used in conjunction with TRIPLEDES + //Please also see https://www.w3.org/TR/xmlenc-core/#sec-Algorithms and + //https://www.w3.org/TR/xmlenc-core/#rsav15note. + b, err := aes.NewCipher(pt) + if err != nil { + return nil, err + } + return b, nil default: return nil, fmt.Errorf("unsupported encryption algorithm: %s", ek.EncryptionMethod.Algorithm) diff --git a/vendor/github.com/mattermost/gosaml2/types/metadata.go b/vendor/github.com/mattermost/gosaml2/types/metadata.go index a7099181fd..84e0700672 100644 --- a/vendor/github.com/mattermost/gosaml2/types/metadata.go +++ b/vendor/github.com/mattermost/gosaml2/types/metadata.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package types import ( @@ -14,6 +28,7 @@ type EntityDescriptor struct { EntityID string `xml:"entityID,attr"` SPSSODescriptor *SPSSODescriptor `xml:"SPSSODescriptor,omitempty"` IDPSSODescriptor *IDPSSODescriptor `xml:"IDPSSODescriptor,omitempty"` + Extensions *Extensions `xml:"Extensions,omitempty"` } type Endpoint struct { @@ -37,6 +52,7 @@ type SPSSODescriptor struct { SingleLogoutServices []Endpoint `xml:"SingleLogoutService"` NameIDFormats []string `xml:"NameIDFormat"` AssertionConsumerServices []IndexedEndpoint `xml:"AssertionConsumerService"` + Extensions *Extensions `xml:"Extensions,omitempty"` } type IDPSSODescriptor struct { @@ -45,7 +61,9 @@ type IDPSSODescriptor struct { KeyDescriptors []KeyDescriptor `xml:"KeyDescriptor"` NameIDFormats []NameIDFormat `xml:"NameIDFormat"` SingleSignOnServices []SingleSignOnService `xml:"SingleSignOnService"` + SingleLogoutServices []SingleLogoutService `xml:"SingleLogoutService"` Attributes []Attribute `xml:"Attribute"` + Extensions *Extensions `xml:"Extensions,omitempty"` } type KeyDescriptor struct { @@ -65,3 +83,20 @@ type SingleSignOnService struct { Binding string `xml:"Binding,attr"` Location string `xml:"Location,attr"` } + +type SingleLogoutService struct { + XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:metadata SingleLogoutService"` + Binding string `xml:"Binding,attr"` + Location string `xml:"Location,attr"` +} + +type SigningMethod struct { + Algorithm string `xml:",attr"` + MinKeySize string `xml:"MinKeySize,attr,omitempty"` + MaxKeySize string `xml:"MaxKeySize,attr,omitempty"` +} + +type Extensions struct { + DigestMethod *DigestMethod `xml:",omitempty"` + SigningMethod *SigningMethod `xml:",omitempty"` +} diff --git a/vendor/github.com/mattermost/gosaml2/types/response.go b/vendor/github.com/mattermost/gosaml2/types/response.go index 4f338f03d3..70a730e7bd 100644 --- a/vendor/github.com/mattermost/gosaml2/types/response.go +++ b/vendor/github.com/mattermost/gosaml2/types/response.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package types import ( @@ -33,6 +47,18 @@ type Response struct { SignatureValidated bool `xml:"-"` // not read, not dumped } +type LogoutResponse struct { + XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol LogoutResponse"` + ID string `xml:"ID,attr"` + InResponseTo string `xml:"InResponseTo,attr"` + Destination string `xml:"Destination,attr"` + Version string `xml:"Version,attr"` + IssueInstant time.Time `xml:"IssueInstant,attr"` + Status *Status `xml:"Status"` + Issuer *Issuer `xml:"Issuer"` + SignatureValidated bool `xml:"-"` // not read, not dumped +} + type Status struct { XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol Status"` StatusCode *StatusCode `xml:"StatusCode"` @@ -149,7 +175,12 @@ type AttributeValue struct { } type AuthnStatement struct { - XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion AuthnStatement"` + XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion AuthnStatement"` + //Section 4.1.4.2 - https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf + //If the identity provider supports the Single Logout profile, defined in Section 4.4 + //, any such authentication statements MUST include a SessionIndex attribute to enable + //per-session logout requests by the service provider. + SessionIndex string `xml:"SessionIndex,attr,omitempty"` AuthnInstant *time.Time `xml:"AuthnInstant,attr,omitempty"` SessionNotOnOrAfter *time.Time `xml:"SessionNotOnOrAfter,attr,omitempty"` AuthnContext *AuthnContext `xml:"AuthnContext"` diff --git a/vendor/github.com/mattermost/gosaml2/uuid/uuid.go b/vendor/github.com/mattermost/gosaml2/uuid/uuid.go index e3765189a3..8dcb7a5cbf 100644 --- a/vendor/github.com/mattermost/gosaml2/uuid/uuid.go +++ b/vendor/github.com/mattermost/gosaml2/uuid/uuid.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package uuid // relevant bits from https://github.com/abneptis/GoUUID/blob/master/uuid.go diff --git a/vendor/github.com/mattermost/gosaml2/validate.go b/vendor/github.com/mattermost/gosaml2/validate.go index 7c85524f22..14a0f0dd42 100644 --- a/vendor/github.com/mattermost/gosaml2/validate.go +++ b/vendor/github.com/mattermost/gosaml2/validate.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 import ( @@ -229,3 +243,67 @@ func (sp *SAMLServiceProvider) Validate(response *types.Response) error { return nil } + +func (sp *SAMLServiceProvider) ValidateDecodedLogoutResponse(response *types.LogoutResponse) error { + err := sp.validateLogoutResponseAttributes(response) + if err != nil { + return err + } + + issuer := response.Issuer + if issuer == nil { + // FIXME?: SAML Core 2.0 Section 3.2.2 has Response.Issuer as [Optional] + return ErrMissingElement{Tag: IssuerTag} + } + + if sp.IdentityProviderIssuer != "" && response.Issuer.Value != sp.IdentityProviderIssuer { + return ErrInvalidValue{ + Key: IssuerTag, + Expected: sp.IdentityProviderIssuer, + Actual: response.Issuer.Value, + } + } + + status := response.Status + if status == nil { + return ErrMissingElement{Tag: StatusTag} + } + + statusCode := status.StatusCode + if statusCode == nil { + return ErrMissingElement{Tag: StatusCodeTag} + } + + if statusCode.Value != StatusCodeSuccess { + return ErrInvalidValue{ + Key: StatusCodeTag, + Expected: StatusCodeSuccess, + Actual: statusCode.Value, + } + } + + return nil +} + +func (sp *SAMLServiceProvider) ValidateDecodedLogoutRequest(request *LogoutRequest) error { + err := sp.validateLogoutRequestAttributes(request) + if err != nil { + return err + } + + issuer := request.Issuer + if issuer == nil { + // FIXME?: SAML Core 2.0 Section 3.2.2 has Response.Issuer as [Optional] + return ErrMissingElement{Tag: IssuerTag} + } + + if sp.IdentityProviderIssuer != "" && request.Issuer.Value != sp.IdentityProviderIssuer { + return ErrInvalidValue{ + Key: IssuerTag, + Expected: sp.IdentityProviderIssuer, + Actual: request.Issuer.Value, + } + } + + return nil +} diff --git a/vendor/github.com/mattermost/gosaml2/xml_constants.go b/vendor/github.com/mattermost/gosaml2/xml_constants.go index f5062f41aa..de36b4774b 100644 --- a/vendor/github.com/mattermost/gosaml2/xml_constants.go +++ b/vendor/github.com/mattermost/gosaml2/xml_constants.go @@ -1,3 +1,17 @@ +// Copyright 2016 Russell Haering et al. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package saml2 const ( @@ -46,7 +60,9 @@ const ( AuthnPolicyMatchMaximum = "maximum" AuthnPolicyMatchBetter = "better" - StatusCodeSuccess = "urn:oasis:names:tc:SAML:2.0:status:Success" + StatusCodeSuccess = "urn:oasis:names:tc:SAML:2.0:status:Success" + StatusCodePartialLogout = "urn:oasis:names:tc:SAML:2.0:status:PartialLogout" + StatusCodeUnknownPrincipal = "urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal" BindingHttpPost = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" BindingHttpRedirect = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" diff --git a/vendor/github.com/mattermost/xml-roundtrip-validator/LICENSE.txt b/vendor/github.com/mattermost/xml-roundtrip-validator/LICENSE.txt new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/vendor/github.com/mattermost/xml-roundtrip-validator/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/mattermost/xml-roundtrip-validator/README.md b/vendor/github.com/mattermost/xml-roundtrip-validator/README.md new file mode 100644 index 0000000000..ec81a2a67f --- /dev/null +++ b/vendor/github.com/mattermost/xml-roundtrip-validator/README.md @@ -0,0 +1,73 @@ +# xml-roundtrip-validator + +The Go module `github.com/mattermost/xml-roundtrip-validator` implements mitigations for multiple security issues in Go's `encoding/xml`. Applications that use `encoding/xml` for security-critical operations, such as XML signature validation and SAML, may use the `Validate` and `ValidateAll` functions to avoid impact from malicious XML inputs. + +## Usage + +### Validate + +```Go +import ( + "strings" + + xrv "github.com/mattermost/xml-roundtrip-validator" +) + +func DoStuffWithXML(input string) { + if err := xrv.Validate(strings.NewReader(input)); err != nil { + panic(err) + } + // validation succeeded, input is safe + actuallyDoStuffWithXML(input) +} +``` + +### ValidateAll + +```Go +import ( + "strings" + + xrv "github.com/mattermost/xml-roundtrip-validator" +) + +func DoStuffWithXML(input string) { + if errs := xrv.ValidateAll(strings.NewReader(input)); len(errs) != 0 { + for err := range errs { + // here you can log each error individually if you like + } + return + } + // validation succeeded, input is safe + actuallyDoStuffWithXML(input) +} +``` + +### CLI + +Compiling: + +``` +$ go build cmd/xrv.go +``` + +Running: + +``` +$ ./xrv good.xml +Document validated without errors +$ ./xrv bad.xml +validator: in token starting at 2:5: roundtrip error: expected {{ :Element} []}, observed {{ Element} []} +$ ./xrv -all bad.xml +validator: in token starting at 2:5: roundtrip error: expected {{ :Element} []}, observed {{ Element} []} +validator: in token starting at 3:5: roundtrip error: expected {{ Element} [{{ :attr} z}]}, observed {{ Element} [{{ attr} z}]} +``` + +## Go vulnerabilities addressed + +Descriptions of the Go vulnerabilities addressed by this module can be found in the advisories directory. Specifically, the issues addressed are: + + - [Element namespace prefix instability](./advisories/unstable-elements.md) + - [Attribute namespace prefix instability](./advisories/unstable-attributes.md) + - [Directive comment instability](./advisories/unstable-directives.md) + - Any other similar roundtrip issues we may not know about diff --git a/vendor/github.com/mattermost/xml-roundtrip-validator/SECURITY.md b/vendor/github.com/mattermost/xml-roundtrip-validator/SECURITY.md new file mode 100644 index 0000000000..4cb6c58d11 --- /dev/null +++ b/vendor/github.com/mattermost/xml-roundtrip-validator/SECURITY.md @@ -0,0 +1,25 @@ +Security +======== + +Safety and data security is of the utmost priority for the Mattermost community. If you are a security researcher and have discovered a security vulnerability in our codebase, we would appreciate your help in disclosing it to us in a responsible manner. + +Reporting security issues +------------------------- + +**Please do not use GitHub issues for security-sensitive communication.** + +Security issues in the community test server, any of the open source codebases maintained by Mattermost, or any of our commercial offerings should be reported via email to [responsibledisclosure@mattermost.com](mailto:responsibledisclosure@mattermost.com). Mattermost is committed to working together with researchers and keeping them updated throughout the patching process. Researchers who responsibly report valid security issues will be publicly credited for their efforts (if they so choose). + +For a more detailed description of the disclosure process and a list of researchers who have previously contributed to the disclosure program, see [Report a Security Vulnerability](https://mattermost.com/security-vulnerability-report/) on the Mattermost website. + +Security updates +---------------- + +Mattermost has a mandatory upgrade policy, and updates are only provided for the latest 3 releases and the current Extended Support Release (ESR). Critical updates are delivered as dot releases. Details on security updates are announced 30 days after the availability of the update. + +For more details about the security content of past releases, see the [Security Updates](https://mattermost.com/security-updates/) page on the Mattermost website. For timely notifications about new security updates, subscribe to the [Security Bulletins Mailing List](https://about.mattermost.com/security-bulletin). + +Contributing to this policy +--------------------------- + +If you have feedback or suggestions on improving this policy document, please [create an issue](https://github.com/mattermost/mattermost-server/issues/new). diff --git a/vendor/github.com/mattermost/xml-roundtrip-validator/go.mod b/vendor/github.com/mattermost/xml-roundtrip-validator/go.mod new file mode 100644 index 0000000000..227e437aeb --- /dev/null +++ b/vendor/github.com/mattermost/xml-roundtrip-validator/go.mod @@ -0,0 +1,5 @@ +module github.com/mattermost/xml-roundtrip-validator + +go 1.14 + +require github.com/stretchr/testify v1.6.1 diff --git a/vendor/github.com/mattermost/xml-roundtrip-validator/go.sum b/vendor/github.com/mattermost/xml-roundtrip-validator/go.sum new file mode 100644 index 0000000000..1f1e7af975 --- /dev/null +++ b/vendor/github.com/mattermost/xml-roundtrip-validator/go.sum @@ -0,0 +1,12 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/mattermost/xml-roundtrip-validator/validator.go b/vendor/github.com/mattermost/xml-roundtrip-validator/validator.go new file mode 100644 index 0000000000..523659dc03 --- /dev/null +++ b/vendor/github.com/mattermost/xml-roundtrip-validator/validator.go @@ -0,0 +1,292 @@ +package validator + +import ( + "bytes" + "encoding/xml" + "errors" + "fmt" + "io" +) + +// XMLRoundtripError is returned when a round-trip token doesn't match the original +type XMLRoundtripError struct { + Expected, Observed xml.Token + Overflow []byte +} + +func (err XMLRoundtripError) Error() string { + if len(err.Overflow) == 0 { + return fmt.Sprintf("roundtrip error: expected %v, observed %v", err.Expected, err.Observed) + } + return fmt.Sprintf("roundtrip error: unexpected overflow after token: %s", err.Overflow) +} + +// XMLValidationError is returned when validating an XML document fails +type XMLValidationError struct { + Start, End, Line, Column int64 + err error +} + +func (err XMLValidationError) Error() string { + return fmt.Sprintf("validator: in token starting at %d:%d: %s", err.Line, err.Column, err.err.Error()) +} + +func (err XMLValidationError) Unwrap() error { + return err.err +} + +// Validate makes sure the given XML bytes survive round trips through encoding/xml without mutations +func Validate(xmlReader io.Reader) error { + xmlBuffer := &bytes.Buffer{} + xmlReader = &byteReader{io.TeeReader(xmlReader, xmlBuffer)} + decoder := xml.NewDecoder(xmlReader) + decoder.Strict = false + decoder.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { return input, nil } + offset := int64(0) + for { + token, err := decoder.RawToken() + if err == io.EOF { + return nil + } else if err != nil { + return err + } + if err := CheckToken(token); err != nil { + xmlBytes := xmlBuffer.Bytes() + line := bytes.Count(xmlBytes[0:offset], []byte{'\n'}) + 1 + lineStart := int64(bytes.LastIndexByte(xmlBytes[0:offset], '\n')) + 1 + column := offset - lineStart + 1 + return XMLValidationError{ + Start: offset, + End: decoder.InputOffset(), + Line: int64(line), + Column: column, + err: err, + } + } + offset = decoder.InputOffset() + } +} + +// ValidateAll is like Validate, but instead of returning after the first error, +// it accumulates errors and validates the entire document +func ValidateAll(xmlReader io.Reader) []error { + xmlBuffer := &bytes.Buffer{} + xmlReader = io.TeeReader(xmlReader, xmlBuffer) + errs := []error{} + offset := int64(0) + line := int64(1) + column := int64(1) + for { + err := Validate(xmlReader) + if err == nil { + // reached the end with no additional errors + break + } + validationError := XMLValidationError{} + if errors.As(err, &validationError) { + // validation errors contain line numbers and offsets, but + // these offsets are based on the offset where Validate + // was called, so they need to be adjusted to accordingly + validationError.Start += offset + validationError.End += offset + if validationError.Line == 1 { + validationError.Column += column - 1 + } + validationError.Line += line - 1 + errs = append(errs, validationError) + xmlBytes := xmlBuffer.Bytes() + offset += int64(len(xmlBytes)) + newLines := int64(bytes.Count(xmlBytes, []byte("\n"))) + line += newLines + if newLines > 0 { + column = int64(len(xmlBytes) - bytes.LastIndex(xmlBytes, []byte("\n"))) + } else { + column += int64(len(xmlBytes)) + } + xmlBuffer.Reset() + } else { + // this was not a validation error, but likely + // completely unparseable XML instead; no point + // in trying to continue + errs = append(errs, err) + break + } + } + return errs +} + +// bufio implements a ByteReader but we explicitly don't want any buffering +type byteReader struct { + r io.Reader +} + +func (r *byteReader) ReadByte() (byte, error) { + var p [1]byte + n, err := r.r.Read(p[:]) + + // The doc for the io.ByteReader interface states: + // If ReadByte returns an error, no input byte was consumed, and the returned byte value is undefined. + // So if a byte is actually extracted from the reader, and we want to return it, we mustn't return the error. + if n > 0 { + // this byteReader is only used in the context of the Validate() function, + // we deliberately choose to completely ignore the error in this case. + // return the byte extracted from the reader + return p[0], nil + } + + return 0, err +} + +func (r *byteReader) Read(p []byte) (int, error) { + return r.r.Read(p) +} + +// CheckToken computes a round trip for a given xml.Token and returns an +// error if the newly calculated token differs from the original +func CheckToken(before xml.Token) error { + buffer := &bytes.Buffer{} + encoder := xml.NewEncoder(buffer) + + switch t := before.(type) { + case xml.EndElement: + // xml.Encoder expects matching StartElements for all EndElements + if err := encoder.EncodeToken(xml.StartElement{Name: t.Name}); err != nil { + return err + } + } + + if err := encoder.EncodeToken(before); err != nil { + return err + } + if err := encoder.Flush(); err != nil { + return err + } + encoded := buffer.Bytes() + decoder := xml.NewDecoder(bytes.NewReader(encoded)) + decoder.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { return input, nil } + + switch before.(type) { + case xml.EndElement: + // throw away the StartElement we added above + if _, err := decoder.RawToken(); err != nil { + return err + } + } + + after, err := decoder.RawToken() + if err != nil { + return err + } + + if !tokenEquals(before, after) { + return XMLRoundtripError{before, after, nil} + } + offset := decoder.InputOffset() + if offset != int64(len(encoded)) { + // this is likely unreachable, but just in case + return XMLRoundtripError{before, after, encoded[offset:]} + } + return nil +} + +func tokenEquals(before, after xml.Token) bool { + switch t1 := before.(type) { + + case xml.CharData: + t2, ok := after.(xml.CharData) + if !ok { + return false + } + return bytes.Equal(t1, t2) + + case xml.Comment: + t2, ok := after.(xml.Comment) + if !ok { + return false + } + return bytes.Equal(t1, t2) + + case xml.Directive: + t2, ok := after.(xml.Directive) + if !ok { + return false + } + return bytes.Equal(t1, t2) + + case xml.EndElement: + t2, ok := after.(xml.EndElement) + if !ok { + return false + } + // local name should equal; namespace prefixes get erased + return t1.Name.Local == t2.Name.Local && t2.Name.Space == "" + + case xml.ProcInst: + t2, ok := after.(xml.ProcInst) + if !ok { + return false + } + return t1.Target == t2.Target && bytes.Equal(t1.Inst, t2.Inst) + + case xml.StartElement: + t2, ok := after.(xml.StartElement) + if !ok { + return false + } + // encoding/xml messes up namespace prefixes on both tag and attribute names; + // they need adjusting to make the comparison possible + fixNamespacePrefixes(&t1, &t2) + if t1.Name != t2.Name { + return false + } + if len(t1.Attr) != len(t2.Attr) { + return false + } + // after the call to fixNamespacePrefixes, all attributes should match; + // ordering is preserved + for i, attr := range t1.Attr { + if attr != t2.Attr[i] { + return false + } + } + return true + } + return false +} + +func fixNamespacePrefixes(before, after *xml.StartElement) { + // if the after token has more attributes than the before token, + // the round trip likely introduced new xmlns attributes + if len(after.Attr) > len(before.Attr) { + + // handle erased tag prefixes; the corresponding xmlns attribute is always the first one + if (before.Name.Space != "" && after.Name.Space == "" && after.Attr[0].Name == xml.Name{Local: "xmlns"}) { + after.Name.Space = after.Attr[0].Value + after.Attr = after.Attr[1:] + } + + // handle attribute prefixes; the xmlns attribute always comes immediately before the prefixed attribute + for len(after.Attr) > len(before.Attr) && len(after.Attr) > 1 { + var xmlns *xml.Attr + i := 1 + for ; i < len(after.Attr); i++ { + if after.Attr[i-1].Name.Space == "xmlns" && after.Attr[i-1].Name.Local == after.Attr[i].Name.Space { + xmlns = &after.Attr[i-1] + break + } + } + if xmlns == nil { + break + } + prefix := xmlns.Name.Local + space := xmlns.Value + copy(after.Attr[i-1:], after.Attr[i:]) + after.Attr = after.Attr[:len(after.Attr)-1] + for j := range after.Attr { + if after.Attr[j].Name.Space == prefix { + after.Attr[j].Name.Space = space + } + } + } + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 8ce49d591e..50b83f5c62 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -394,7 +394,7 @@ github.com/mattermost/go-i18n/i18n github.com/mattermost/go-i18n/i18n/bundle github.com/mattermost/go-i18n/i18n/language github.com/mattermost/go-i18n/i18n/translation -# github.com/mattermost/gosaml2 v0.3.3 +# github.com/mattermost/gosaml2 v0.8.0 ## explicit github.com/mattermost/gosaml2 github.com/mattermost/gosaml2/types @@ -426,6 +426,8 @@ github.com/mattermost/morph/sources/file github.com/mattermost/rsc/gf256 github.com/mattermost/rsc/qr github.com/mattermost/rsc/qr/coding +# github.com/mattermost/xml-roundtrip-validator v0.1.0 +github.com/mattermost/xml-roundtrip-validator # github.com/mattn/go-colorable v0.1.12 ## explicit github.com/mattn/go-colorable