Giter Site home page Giter Site logo

signedxml's Introduction

Moov Banner Logo

moov-io/signedxml

GoDoc Build Status Coverage Status Go Report Card Repo Size MIT  License Slack Channel Twitter

The signedxml package transforms and validates signed xml documents. The main use case is to support Single Sign On protocols like SAML and WS-Federation.

Other packages that provide similar functionality rely on C libraries, which makes them difficult to run across platforms without significant configuration. signedxml is written in pure go, and can be easily used on any platform. This package was originally created by Matt Smith and is in use at Moov Financial.

Install

go get github.com/moov-io/signedxml

Included Algorithms

Examples

Validating signed XML

If your signed xml contains the signature and certificate, then you can just pass in the xml and call ValidateReferences().

validator, err := signedxml.NewValidator(`<YourXMLString></YourXMLString>`)
xml, err = validator.ValidateReferences()

ValidateReferences() verifies the DigestValue and SignatureValue in the xml document, and returns the signed payload(s). If the error value is nil, then the signed xml is valid.

The x509.Certificate that was successfully used to validate the xml will be available by calling:

validator.SigningCert()

You can then verify that you trust the certificate. You can optionally supply your trusted certificates ahead of time by assigning them to the Certificates property of the Validator object, which is an x509.Certificate array.

Using an external Signature

If you need to specify an external Signature, you can use the SetSignature() function to assign it:

validator.SetSignature(<`Signature></Signature>`)

Generating signed XML

It is expected that your XML contains the Signature element with all the parameters set (except DigestValue and SignatureValue).

signer, err := signedxml.NewSigner(`<YourXMLString></YourXMLString`)
signedXML, err := signer.Sign(`*rsa.PrivateKey object`)

Sign() will generate the DigestValue and SignatureValue, populate it in the XML, and return the signed XML string.

Implementing custom transforms

Additional Transform algorithms can be included by adding to the CanonicalizationAlgorithms map. This interface will need to be implemented:

type CanonicalizationAlgorithm interface {
	Process(inputXML string, transformXML string) (outputXML string, err error)
}

Simple Example:

type NoChangeCanonicalization struct{}

func (n NoChangeCanonicalization) Process(inputXML string,
	transformXML string) (outputXML string, err error) {
	return inputXML, nil
}

signedxml.CanonicalizationAlgorithms["http://myTranform"] = NoChangeCanonicalization{}

See envelopedsignature.go and exclusivecanonicalization.go for examples of actual implementations.

Using a custom reference ID attribute

It is possible to set a custom reference ID attribute for both the signer and the validator. The default value is "ID"

Signer example:

signer.SetReferenceIDAttribute("customId")

Validator example:

validator.SetReferenceIDAttribute("customId")

Getting help

channel info
Twitter @moov You can follow Moov.io's Twitter feed to get updates on our project(s). You can also tweet us questions or just share blogs or stories.
GitHub Issue If you are able to reproduce a problem please open a GitHub Issue under the specific project that caused the error.
moov-io slack Join our slack channel to have an interactive discussion about the development of the project.

Contributions

Contributions are welcome. Just fork the repo and send a pull request.

Releated Projects

  • Moov RTP20022 implements ISO20022 messages in Go for Real Time Payments (RTP)

signedxml's People

Contributors

adamdecaf avatar calpicow avatar daugminas avatar dmlambea avatar laurenkt avatar liclac avatar ma314smith avatar muhitsarwar avatar renovate[bot] avatar rowland66 avatar z3spinner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

signedxml's Issues

Problem in namespace parsing

<?xml version="1.0" encoding="utf-8" standalone="no" ?><ns:BusMsg xmlns:ns="urn:rpp" xmlns:ns1="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.08.01" xmlns:ns2="urn:iso:std:iso:20022:tech:xsd:head.001.001.01"><ns:AppHdr><ns2:Fr><ns2:FIId><ns2:FinInstnId><ns2:Othr><ns2:Id>RPPEMYKL</ns2:Id></ns2:Othr></ns2:FinInstnId></ns2:FIId></ns2:Fr><ns2:To><ns2:FIId><ns2:FinInstnId><ns2:Othr><ns2:Id>ARPYMYNB</ns2:Id></ns2:Othr></ns2:FinInstnId></ns2:FIId></ns2:To><ns2:BizMsgIdr>20200706RPPEMYKL520HQR10392366</ns2:BizMsgIdr><ns2:MsgDefIdr>pacs.002.001.08.01</ns2:MsgDefIdr><ns2:BizSvc>RPP</ns2:BizSvc><ns2:CreDt>2020-07-06T06:42:02Z</ns2:CreDt><ns2:PssblDplct>false</ns2:PssblDplct><ns1:Sgntr xmlns:ns1="urn:iso:std:iso:20022:tech:xsd:head.001.001.01"><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds:DigestValue>3CssCiGJm3sMr82CySs3tq7QX/hPnOnfkUZd2h8jTWU=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>NNBXKzvtKP8LLO2afdDZAnjbsbN990Lwn/uzi0EEWf1CDZwNS8nb6+1fqad9ALhoQ2TYlGW0zMe6w/jYr6NiePGNUXzqiiG9ifiQ21ynElPDhFQ9irkmgMJIV3BRsLH3yKGSTMeb/GFfE/ToZbOkfy0Z5gtyc9R8/84PRKODA46R4VYSHVexmpzB96DjFlr0K8T5xuyYkNysJlxY/ZeAsenw9kCAx0oh+4AbnqzBgQn5gHjrSJc/RYgtWnnUZV5XrCjFXBJ9/zcgWUKltRVQgLUwVh93hhWresbwyXLWl5QCTGytleWY0rZmH6zi5vTwmoltSuSj/9TFicxKdvdSZg==</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509IssuerSerial><ds:X509IssuerName>C=my, O=TM, OU=TM Applied Business Certification Authority, CN=PayNet RPP</ds:X509IssuerName><ds:X509SerialNumber>6696817177145561609</ds:X509SerialNumber></ds:X509IssuerSerial></ds:X509Data></ds:KeyInfo></ds:Signature></ns1:Sgntr></ns:AppHdr><ns:Document><ns:FIToFIPmtStsRptInf><ns1:GrpHdr><ns1:MsgId>20200706DMM1MYKL52000000002</ns1:MsgId><ns1:CreDtTm>2020-07-06T14:42:01.000</ns1:CreDtTm></ns1:GrpHdr><ns1:OrgnlGrpInfAndSts><ns1:OrgnlMsgId>20200706ARPYMYNB52000000135</ns1:OrgnlMsgId><ns1:OrgnlMsgNmId>pacs.008.001.06.01</ns1:OrgnlMsgNmId></ns1:OrgnlGrpInfAndSts><ns1:TxInfAndSts><ns1:OrgnlEndToEndId>20200706ARPYMYNB520OQR00000135</ns1:OrgnlEndToEndId><ns1:OrgnlTxId>20200706ARPYMYNB52000000135</ns1:OrgnlTxId><ns1:TxSts>ACSP</ns1:TxSts><ns1:StsRsnInf><ns1:Rsn><ns1:Prtry>U000</ns1:Prtry></ns1:Rsn></ns1:StsRsnInf><ns1:ClrSysRef>002</ns1:ClrSysRef><ns1:OrgnlTxRef><ns1:IntrBkSttlmDt>2020-07-06</ns1:IntrBkSttlmDt><ns1:Cdtr><ns1:Nm>TEST</ns1:Nm></ns1:Cdtr><ns1:CdtrAcct><ns1:Id><ns1:Othr><ns1:Id>207</ns1:Id></ns1:Othr></ns1:Id><ns1:Tp><ns1:Prtry>DFLT</ns1:Prtry></ns1:Tp></ns1:CdtrAcct></ns1:OrgnlTxRef><ns1:SplmtryData><ns1:PlcAndNm>Test</ns1:PlcAndNm><ns1:Envlp><ns1:InstrForCdtrAcct><ns1:RsdntSts>1</ns1:RsdntSts><ns1:PrdTp>C</ns1:PrdTp><ns1:ShariaCmpl>N</ns1:ShariaCmpl><ns1:Dtls>1</ns1:Dtls></ns1:InstrForCdtrAcct><ns1:CdtrAcctCstmrCtg>RET</ns1:CdtrAcctCstmrCtg><ns1:QRTxInfo><ns1:QRCategory>01</ns1:QRCategory><ns1:AcceptedPymtType>01</ns1:AcceptedPymtType><ns1:PromoCd>a</ns1:PromoCd><ns1:Field1>a</ns1:Field1><ns1:Field2>a</ns1:Field2><ns1:Field3>a</ns1:Field3><ns1:Field4>a</ns1:Field4><ns1:Field5>a</ns1:Field5></ns1:QRTxInfo></ns1:Envlp></ns1:SplmtryData></ns1:TxInfAndSts></ns:FIToFIPmtStsRptInf></ns:Document></ns:BusMsg>
for above xml ns1 becomes "urn:iso:std:iso:20022:tech:xsd:head.001.001.01" in sgntr. So for other case ns1 cannot be "urn:iso:std:iso:20022:tech:xsd:pacs.002.001.08.01"

Critical security vulnerability

I would like to report a potentially critical security vulnerability, however I couldn't find a way to contact you. Could you please provide contact details?

This only works with the example certificate

This is a fantastic development effort, I am using it to sign my SAML assertion and its accepted at all IDP's. There is one issue however, the signature can only be verified if I used the example certificate that comes in the package. Can someone please tell me how to create a cert that works using openssl for the development.

If you guys give me this information, I am going to release a SAML package that will generate a proper SAML Response. This will be the first native golang SAML implementation that actually works for golang that produces a SAML response in a logical manner. I had to build my own SAML library because nothing on github worked properly.

Is change from moove-io to ma314smith expected?

renovate opened a PR to merge a recent change in this repo. However I am getting this error

go: github.com/ma314smith/[email protected]: parsing go.mod:
	module declares its path as: github.com/moov-io/signedxml
	        but was required as: github.com/ma314smith/signedxml

Is this an expected change? Why did package move from moov-io to ma314smith ?

Example not working

Hello,
Congratulations, very nice project. However your example is not working.

SAML Response with Signed Message & Assertion

It looks like this library, when signing, will find the first Signature and compute the Digest/Signature values for that. Is it possible to use this library also when you want to sign both the Message and the Assertions in a SAML response document - thus you would have two Signature blocks in the xml documents to sign both the whole document and then also the assertions.

Example of such a document with two Signature tags can be seen here: https://developers.onelogin.com/saml/examples/response#:~:text=A%20SAML%20Response%20is%20sent,NameID%20%2F%20attributes%20of%20the%20user.&text=A%20signed%20SAML%20Response%20with%20an%20encrypted%20Assertion,with%20an%20encrypted%20signed%20Assertion

Discrepancy in Signature Validation with XML Declaration Presence.

I've encountered an issue related to the validation of XML signatures generated and verified using specific canonicalization methods. Below is the template of the XML signature being used:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
        <SignedInfo>
            <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
            <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
            <Reference URI="">
                <Transforms>
                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                </Transforms>
                <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                <DigestValue/>
            </Reference>
        </SignedInfo>
        <SignatureValue/>
        <KeyInfo>
            <KeyValue>
                <RSAKeyValue>
                    <Modulus/>
                    <Exponent/>
                </RSAKeyValue>
            </KeyValue>
        </KeyInfo>

From my understanding, the canonicalization method specified by http://www.w3.org/TR/2001/REC-xml-c14n-20010315 should not include the XML declaration in the canonicalized output. Could you please confirm if this understanding is correct?

If so, I would expect that the XML declaration would be removed during the signature verification process, as it's not part of the canonical form used for computing the digest. However, I've observed that the digest value does not match during verification when the XML declaration is present. Removing the XML declaration manually results in a successful match of the digest value.

Could you clarify if it's intended behavior that the XML declaration must be manually removed before validating the signature? Or is there a potential issue or misunderstanding on my part regarding the canonicalization process and its impact on signature verification?

ExclusiveCanonicalization: neighbouring comments are not all stripped when `WithComments: false`

When there are runs of multiple comments like <!-- comment0 --><!-- comment1 --> then the second one is not stripped. This doesn't happen if there is whitespace between the comments.

It seems like all comments should be stripped, but I checked just to be sure in case it's some weird quirk of the Canonical XML spec:

The second parameter of input to the XML canonicalization method is a boolean flag indicating whether or not comments should be included in the canonical form output by the XML canonicalization method. If a canonical form contains comments corresponding to the comment nodes in the input node-set, the result is called canonical XML with comments. Note that the XPath data model does not create comment nodes for comments appearing within the document type declaration (DTD). Implementations are REQUIRED to be capable of producing canonical XML excluding all comments that may have appeared in the input document or document subset. Support for canonical XML with comments is RECOMMENDED.

Here's a minimal project test case which reproduces the issue:

package main

import (
	"github.com/moov-io/signedxml"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"testing"
)

func TestExclusiveCanonicalization_WithNeighbouringComments(t *testing.T) {
	str := `
<a>
  <!-- comment0 --><!-- comment1 -->
</a>
`
	ec := signedxml.ExclusiveCanonicalization{WithComments: false}
	str, err := ec.Process(str, "")
	require.NoError(t, err)
	assert.Equal(t, `
<a>
</a>`, str)
}

Output:

=== RUN   TestExclusiveCanonicalization_WithNeighbouringComments
    main_test.go:19: 
        	Error Trace:	main_test.go:19
        	Error:      	Not equal: 
        	            	expected: "\n<a>\n</a>"
        	            	actual  : "\n<a>\n  <!-- comment1 -->\n</a>"
        	            	
        	            	Diff:
        	            	--- Expected
        	            	+++ Actual
        	            	@@ -2,2 +2,3 @@
        	            	 <a>
        	            	+  <!-- comment1 -->
        	            	 </a>
        	Test:       	TestExclusiveCanonicalization_WithNeighbouringComments
--- FAIL: TestExclusiveCanonicalization_WithNeighbouringComments (0.00s)

With a comment run like:

  • <!-- comment0 --><!-- comment1 --><!-- comment3 --><!-- comment4 -->
    Then the output will be:
  • <!-- comment1 --><!-- comment4 -->

So it seems like a comment immediately following another comment with no whitespace between them will reduce in comments being missed for stripping.

Latest update causes build failures

We have renovate bot monitoring updates to our referenced packages. The latest update to this package is adding an indirect reference to github.com/lestrrat-go/libxml2 v0.0.0-20201123224832-e6d9de61b80d // indirect and this is causing build failures since we do not have configuration to pull in necessary libraries.

Was the inclusion intentional? Isn;t this package a pure implementation in go to prevent this issue? Any tips on resolving the issue highly appreciated.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/test.yml
  • actions/setup-go v5
  • actions/checkout v4
gomod
go.mod
  • go 1.21.0
  • go 1.23.0
  • github.com/beevik/etree v1.4.1
  • github.com/russellhaering/goxmldsig v1.4.0
  • github.com/smartystreets/goconvey v1.8.1
  • github.com/stretchr/testify v1.9.0

  • Check this box to trigger a request for Renovate to run again on this repository

Panic when Reference does not have any transform when signing

Hello, thank you for your great library.

Currently, I'm playing with this library and found that when I have some ds:Reference that does not have any ds:Transforms (not appear in XML document) the library will panic when I try to sign the XML document.

I dig through the code and find that this line is nil when the XML document doesn't have any ds:Transforms in ds:Reference causing panic (empty ds:Transforms is OK).

My current workaround

  • Add empty ds:Transforms to ds:Reference.

Example XML Before Signing

<Root>
  <Inner>
    <Text>Hello World!</Text>
  </Inner>
  <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
    Id="xmldsig-186cb59f-c7be-4e9d-a1e8-9fa311754f7e">
    <ds:SignedInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512" />
      <ds:Reference Id="xmldsig-186cb59f-c7be-4e9d-a1e8-9fa311754f7e-ref0">
        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha512" />
        <ds:DigestValue></ds:DigestValue>
        <ds:Transforms>
          <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
          <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        </ds:Transforms>
      </ds:Reference>
      <ds:Reference Type="http://uri.etsi.org/01903#SignedProperties">
        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha512" />
        <ds:DigestValue></ds:DigestValue>
      </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue></ds:SignatureValue>
    <ds:KeyInfo>
      <ds:X509Data>
        <ds:X509Certificate>HIDDEN</ds:X509Certificate>
      </ds:X509Data>
    </ds:KeyInfo>
    <ds:Object xmlns:xades="http://uri.etsi.org/01903/v1.3.2#"
      xmlns:xades141="http://uri.etsi.org/01903/v1.4.1#" Target="">
      <xades:SignedProperties Id="xmldsig-186cb59f-c7be-4e9d-a1e8-9fa311754f7e-signedprops">
        <xades:SignedSignatureProperties>
          <xades:SigningTime>2024-06-04T16:13:09.320+07:00</xades:SigningTime>
          <xades:SigningCertificate>
            <xades:Cert>
              <xades:CertDigest>
                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha512" />
                <ds:DigestValue>kiffFUcHZhaLu0OkrPZ1Ui99V784vgh4zJrJNNn82+XWUfDzz24SKy4GMId/hxDFxiQaak0AdJRWHPtLUgutIA==</ds:DigestValue>
              </xades:CertDigest>
            </xades:Cert>
            <xades:IssuerSerial>
              <ds:X509IssuerName>HIDDEN</ds:X509IssuerName>
              <ds:X509SerialNumber>HIDDEN</ds:X509SerialNumber>
            </xades:IssuerSerial>
          </xades:SigningCertificate>
        </xades:SignedSignatureProperties>
      </xades:SignedProperties>
    </ds:Object>
  </ds:Signature>
</Root>

PS. I'm also new to XML signing but I did walk through the XMLDSIG spec, and found that the min occurrence of ds:Transforms can be 0.

Thank you.

Signature at root

Hello everyone, joining after coming across the need for a signed XML (https://github.com/moov-io/signedxml?tab=readme-ov-file)
However (i hope this is the right channel and i apologize if it is not!)
I have an issue with .Sign() method.
This is the XML i am sending in:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
        <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod>
        <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod>
        <Reference URI="#test">
            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod>
            <Transforms>
                <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform>
            </Transforms>
            <DigestValue>YWJjMTIz</DigestValue>
        </Reference>
    </SignedInfo>
    <SignatureValue>YWJjMTIz</SignatureValue>
    <KeyInfo>
        <X509Data>
            <X509Certificate>testtest</X509Certificate>
        </X509Data>
    </KeyInfo>
    <Object xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Id="test">
        ...
ends with
</Object>
</Signature>

ANd i get this errror:
signedxml: unable to find Signature node
Not really sure what I should change?
According to the docs
Generating signed XML
It is expected that your XML contains the Signature element with all the parameters set (except DigestValue and SignatureValue).
Sorry, could not find any examples on the internet

Can Signature be on the root?

unable to find refereced xml

An attempt to sign the following response fails with unable to find refereced xml.

Relevant code follows:

func getSigningKey(fp string) (*rsa.PrivateKey, error) {
    fileContent, err := ioutil.ReadFile(fp)
    if err != nil {
        return nil, err
    }
    block, _ := pem.Decode(fileContent)
    if block == nil || block.Type != "RSA PRIVATE KEY" {
        return nil, fmt.Errorf("failed to decode PEM block containing RSA PRIVATE KEY")
    }
    key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    return key, nil
}

...

    // XML Signing
    signingKey, err := getSigningKey("assets/idp/azure_ad_app_signing_pkcs1_key.pem")
    if err != nil {
        t.Fatalf("error parsing signing key: %s", err)
    }
    signer, err := signedxml.NewSigner(authRequestPayloadPlain.String())
    if err != nil {
        t.Fatalf("error initializing XML signer: %s", err)
    }
    signedAuthRequestPayloadPlain, err := signer.Sign(signingKey)
    if err != nil {
        t.Fatalf("error signing XML doc: %s", err)
    }
 <samlp:Response ID="_9eefb041-27fe-4014-bf4b-932cd5f7f5d5" Version="2.0" IssueInstant="2020-04-21T04:44:24.286Z" Destination="https://127.0.0.1:3443/saml" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
          <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://sts.windows.net/1b9e886b-8ff2-4378-b6c8-6771259a5f51/</Issuer>
          <samlp:Status>
            <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
          </samlp:Status>
          <Assertion ID="_7298c1f7-4411-4bc6-b8e4-77622e935418" IssueInstant="2020-04-21T04:44:23.125Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
            <Issuer>https://sts.windows.net/1b9e886b-8ff2-4378-b6c8-6771259a5f51/</Issuer>
            <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
              <SignedInfo>
                <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
                <Reference URI="#_0369ee56-8152-4f92-b8c3-e1481fe74300">
                  <Transforms>
                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                  </Transforms>
                  <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                  <DigestValue>asdf</DigestValue>
                </Reference>
              </SignedInfo>
              <SignatureValue>asdf</SignatureValue>
            </Signature>
            <Subject>
              <NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">[email protected]</NameID>
              <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <SubjectConfirmationData NotOnOrAfter="2020-04-21T05:44:28.208Z" Recipient="https://127.0.0.1:3443/saml"/>
              </SubjectConfirmation>
            </Subject>
            <Conditions NotBefore="2020-04-21T04:39:28.099Z" NotOnOrAfter="2020-04-21T05:44:28.208Z">
              <AudienceRestriction>
                        <Audience>urn:caddy:mygatekeeper</Audience>
              </AudienceRestriction>
            </Conditions>
            <AttributeStatement>
              <Attribute Name="http://schemas.microsoft.com/identity/claims/tenantid">
                <AttributeValue>1b9e886b-8ff2-4378-b6c8-6771259a5f51</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.microsoft.com/identity/claims/objectidentifier">
                <AttributeValue>158d7011-cfd7-41b8-b456-8a8264ac5a04</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.microsoft.com/identity/claims/displayname">
                <AttributeValue>Greenberg, Paul</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.microsoft.com/identity/claims/identityprovider">
                <AttributeValue>https://sts.windows.net/1b9e886b-8ff2-4378-b6c8-6771259a5f51/</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.microsoft.com/claims/authnmethodsreferences">
                <AttributeValue>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AttributeValue>
                <AttributeValue>http://schemas.microsoft.com/claims/multipleauthn</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.microsoft.com/ws/2008/06/identity/claims/role">
                <AttributeValue>AzureAD_Editor</AttributeValue>
                <AttributeValue>AzureAD_Viewer</AttributeValue>
                <AttributeValue>AzureAD_Administrator</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname">
                <AttributeValue>Paul</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname">
                <AttributeValue>Greenberg</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress">
                <AttributeValue>[email protected]</AttributeValue>
              </Attribute>
              <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name">
                <AttributeValue>[email protected]</AttributeValue>
              </Attribute>
              <Attribute Name="http://claims.contoso.com/SAML/Attributes/RoleSessionName">
                <AttributeValue>[email protected]</AttributeValue>
              </Attribute>
              <Attribute Name="http://claims.contoso.com/SAML/Attributes/Role">
                <AttributeValue>AzureAD_Editor</AttributeValue>
                <AttributeValue>AzureAD_Viewer</AttributeValue>
                <AttributeValue>AzureAD_Administrator</AttributeValue>
              </Attribute>
              <Attribute Name="http://claims.contoso.com/SAML/Attributes/MaxSessionDuration">
                <AttributeValue>3600</AttributeValue>
              </Attribute>
            </AttributeStatement>
            <AuthnStatement AuthnInstant="2020-04-21T05:44:28.358Z" SessionIndex="_7298c1f7-4411-4bc6-b8e4-77622e935418">
              <AuthnContext>
                <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef>
              </AuthnContext>
            </AuthnStatement>
          </Assertion>
        </samlp:Response>

digest do not match

I get error The digest of soapBody was not correct.

any idea @adamdecaf why it could happen?

	signer, err := signedxml.NewSigner(xmlString)
	signedXML, err := signer.Sign(privateKey)
</Reference>
  <Reference URI="#soapBody">
    <Transforms>
      <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
    <DigestValue>TLcN2ydc2+DlKl5IEzl1PDHTf4E=</DigestValue>
  </Reference>

Namespace Propagation

I've been working on getting some code moved off of PHP and into Go, and in testing found different behavior from a known working PHP system. It appears that namespaces aren't getting propagated when taking the subset that is getting signed, as in the example in section 3.7 here https://www.w3.org/TR/2001/REC-xml-c14n-20010315

In our case the (extremely abbreviated) XML is:

<E:Envelope xmlns:E="http://schemas.xmlsoap.org/soap/envelope/">
    <E:Body id="Body">

where in the dump I've extracted from inside the PHP library I'm using the body gets converted to

<E:Body xmlns:E="http://schemas.xmlsoap.org/soap/envelope/" id="Body">

and then generates the correct DigestValue.

I believe the canonicalization algorithm requires that when taking a subset, it needs to look up the chain for any namespace declarations, and move them to the highest level tag(s) that first reference that namespace (or something like that, the c14n specs are painful).

Misleading error "Unable to find Algorithm in CanonicalizationMethod element"

I'm currently working on some rather old systems and was getting the "Unable to find Algorithm in CanonicalizationMethod element" error while signing an XML document. This error implies that signedxml is not able to find the element's attribute, yet this is also triggered by unsupported algorithms.

In the Sing method, if the check for the canonAlgoURI is successful, but the URI is not present in the CanonicalizationAlgorithms map, the error will default to the said error message.

The error was triggered by trying to use the now outdated ExclusiveCanonicalization 1.0 as the attribute for SignedInfo.CanonicalizationMethod (http://www.w3.org/TR/2001/REC-xml-c14n-20010315).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.