signedxml

package module
v0.0.0-...-cf137e6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2024 License: MIT Imports: 13 Imported by: 0

README

daugminas/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/daugminas/signedxml

Included Algorithms

Examples

Simple signing of a document with a private key

Three steps:

  1. Insert the to-be-signed document into an XML signature template (this uses an enveloped version)

  2. Prepare private key for signing (DER format)

  3. Sign the templated document with the private key

Full code:


  // 0. load inputs
	templateBytes, e := os.ReadFile("template.xml")
	if e != nil {
		panic(e)
	}
	targetBytes, e := os.ReadFile("signing_target.xml")
	if e != nil {
		panic(e)
	}
  keyBytes, e = os.ReadFile("private_key.pem")
	if e != nil {
		return
	}

	// 1. Insert target into the template
	finalXMLtoBeSigned, e := signedxml.InsertXMLintoSignatureTemplate(string(templateBytes), string(targetBytes), true)
	if e != nil {
		panic(e)
	}

  // 2. Prep the key
  key, e := signedxml.PrepPKCS8PrivateKey(keyBytes)
  if e != nil {
		panic(e)
	}

  // 3. Sign the document
	var signer *signedxml.Signer
	signer, e = signedxml.NewSigner(targetXML)
	if e != nil {
		return
	}

	signedXML, e = signer.Sign(key)
   if e != nil {
		panic(e)
	}
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)

Additional Information

About xml-sig:(https://www.xml.com/pub/a/2001/08/08/xmldsig.html#xml-sig) XML-DSIG how-to: https://www.di-mgt.com.au/xmldsig.html

Documentation

Overview

Package signedxml transforms and validates signedxml documents

Index

Constants

This section is empty.

Variables

View Source
var CanonicalizationAlgorithms map[string]CanonicalizationAlgorithm

CanonicalizationAlgorithms maps the CanonicalizationMethod or Transform Algorithm URIs to a type that implements the CanonicalizationAlgorithm interface.

Implementations are provided for the following transforms:

http://www.w3.org/2001/10/xml-exc-c14n# (ExclusiveCanonicalization)
http://www.w3.org/2001/10/xml-exc-c14n#WithComments (ExclusiveCanonicalizationWithComments)
http://www.w3.org/2000/09/xmldsig#enveloped-signature (EnvelopedSignature)

Custom implementations can be added to the map

Functions

func InsertTextIntoSignatureTemplate

func InsertTextIntoSignatureTemplate(xmlSignatureTemplate string, text string, unindent bool, addProcessInstructions bool) (out string, e error)

func InsertXMLintoSignatureTemplate

func InsertXMLintoSignatureTemplate(xmlSignatureTemplate string, xmlToBeInserted string, unindent bool, addProcessInstructions bool) (out string, e error)

Inserts an XML document into the XML template - both inputs in the form of a string. Returns a XML string document prepared for signing. No transforms are done.

Returns error, if something goes wrong. Typically, a missing <Signature> or <Object> tag in the template.. or Object "Id" attribute missing.

Params: xmlSignatureTemplate - the template to be used, i.e. where the document is inserted into; xmlToBeInserted - the XML document to be inserted into the template unindent - unindent/minify resulting document; addProcessInstructions - add processing instructions for at the header of the XML, i.e. `version="1.0" encoding="UTF-8"`

func PrepPKCS8PrivateKey

func PrepPKCS8PrivateKey(PEMKeyBytes []byte) (key any, e error)

Decodes private key bytes in the PEM format and parses it into PKCS #8, ASN.1 DER form, which then can be used by signer.Sign(key)

Types

type CanonicalizationAlgorithm

type CanonicalizationAlgorithm interface {
	// ProcessElement is called to transform an XML Element within an XML Document
	// using the implementing algorithm
	ProcessElement(inputXML *etree.Element, transformXML string) (outputXML string, err error)

	// ProcessDocument is called to transform an XML Document using the implementing
	// algorithm.
	ProcessDocument(doc *etree.Document, transformXML string) (outputXML string, err error)

	// Process is called to transform a string containing XML text using the implementing
	// algorithm. The inputXML parameter should contain a complete XML Document. It is not
	// correct to use this function on XML fragments. Retained for backward comparability.
	// Use ProcessElement or ProcessDocument if possible.
	Process(inputXML string, transformXML string) (outputXML string, err error)
}

CanonicalizationAlgorithm defines an interface for processing an XML document into a standard format.

If any child elements are in the Transform node, the entire transform node will be passed to the Process method through the transformXML parameter as an XML string. This is necessary for transforms that need additional processing data, like XPath (http://www.w3.org/TR/xmldsig-core/#sec-XPath). If there are no child elements in Transform (or CanonicalizationMethod), then an empty string will be passed through.

type EnvelopedSignature

type EnvelopedSignature struct{}

EnvelopedSignature implements the CanonicalizationAlgorithm interface and is used for processing the http://www.w3.org/2000/09/xmldsig#enveloped-signature transform algorithm

func (EnvelopedSignature) Process

func (e EnvelopedSignature) Process(inputXML string, transformXML string) (outputXML string, err error)

see CanonicalizationAlgorithm.Process

func (EnvelopedSignature) ProcessDocument

func (e EnvelopedSignature) ProcessDocument(doc *etree.Document,
	transformXML string) (outputXML string, err error)

see CanonicalizationAlgorithm.ProcessDocument

func (EnvelopedSignature) ProcessElement

func (e EnvelopedSignature) ProcessElement(inputXML *etree.Element, transformXML string) (outputXML string, err error)

see CanonicalizationAlgorithm.ProcessElement

type ExclusiveCanonicalization

type ExclusiveCanonicalization struct {
	WithComments bool
	// contains filtered or unexported fields
}

ExclusiveCanonicalization implements the CanonicalizationAlgorithm interface and is used for processing the http://www.w3.org/2001/10/xml-exc-c14n# and http://www.w3.org/2001/10/xml-exc-c14n#WithComments transform algorithms

func (ExclusiveCanonicalization) Process

func (e ExclusiveCanonicalization) Process(inputXML string, transformXML string) (outputXML string, err error)

see CanonicalizationAlgorithm.Process

func (ExclusiveCanonicalization) ProcessDocument

func (e ExclusiveCanonicalization) ProcessDocument(doc *etree.Document,
	transformXML string) (outputXML string, err error)

see CanonicalizationAlgorithm.ProcessDocument

func (ExclusiveCanonicalization) ProcessElement

func (e ExclusiveCanonicalization) ProcessElement(inputXML *etree.Element, transformXML string) (outputXML string, err error)

see CanonicalizationAlgorithm.ProcessElement

type Signer

type Signer struct {
	// contains filtered or unexported fields
}

Signer provides options for signing an XML document

func NewSigner

func NewSigner(xml string) (*Signer, error)

NewSigner returns a *Signer for the XML provided

func NewSignerFromDoc

func NewSignerFromDoc(doc *etree.Document) (*Signer, error)

NewSignerFromDoc returns a *Signer for the Document provided

func (*Signer) SetReferenceIDAttribute

func (s *Signer) SetReferenceIDAttribute(refIDAttribute string)

SetReferenceIDAttribute set the referenceIDAttribute

func (*Signer) SetSignature

func (s *Signer) SetSignature(sig string) error

SetSignature can be used to assign an external signature for the XML doc that Validator will verify

func (*Signer) Sign

func (s *Signer) Sign(privateKey interface{}) (string, error)

Sign populates the XML digest and signature based on the parameters present and privateKey given

type Validator

type Validator struct {
	Certificates []x509.Certificate
	// contains filtered or unexported fields
}

Validator provides options for verifying a signed XML document

func NewValidator

func NewValidator(xml string) (*Validator, error)

NewValidator returns a *Validator for the XML provided

func (*Validator) SetReferenceIDAttribute

func (v *Validator) SetReferenceIDAttribute(refIDAttribute string)

SetReferenceIDAttribute set the referenceIDAttribute

func (*Validator) SetSignature

func (s *Validator) SetSignature(sig string) error

SetSignature can be used to assign an external signature for the XML doc that Validator will verify

func (*Validator) SetXML

func (v *Validator) SetXML(xml string) error

SetXML is used to assign the XML document that the Validator will verify

func (*Validator) SigningCert

func (v *Validator) SigningCert() x509.Certificate

SigningCert returns the certificate, if any, that was used to successfully validate the signature of the XML document. This will be a zero value x509.Certificate before Validator.Validate is successfully called.

func (*Validator) ValidateReferences

func (v *Validator) ValidateReferences() ([]string, error)

ValidateReferences validates the Reference digest values, and the signature value over the SignedInfo.

If the signature is enveloped in the XML, then it will be used. Otherwise, an external signature should be assigned using Validator.SetSignature.

The references returned contain validated XML from the signature and must be used. Callers that ignore the returned references are vulnerable to XML injection.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL