Documentation
¶
Overview ¶
Package xmldsig creates and verifies XML Digital Signatures (W3C XML Signature Syntax and Processing 1.1) and XAdES advanced electronic signatures (ETSI EN 319 132-1, the current eIDAS-referenced XAdES standard).
The API speaks opaque Document / Element handles (obtained from Parse); the library uses beevik/etree internally but does not expose it, so consumers need not depend on it. etree appears in the public surface only on the interop seam — FromEtree / FromEtreeElement to wrap, and (*Document).Etree() / (*Element).Etree() to unwrap — for callers that build or inspect the tree with etree directly.
Two verification surfaces share one trust core, distinguished by a naming convention:
- The Verify* methods (Verify, VerifyDocument, VerifyXAdES, …) return a result value and an error: a Go-error contract — the signature is valid, or it is not and the error explains why.
- Validate returns a *ValidationReport: the EN 319 102-1 three-valued status model (PASSED / FAILED / INDETERMINATE with a sub-indication), where an unresolved "try later" outcome is a first-class result rather than an error. Its ValidationProcess argument selects the §5.3 / §5.5 / §5.6 process.
The authoritative requirements contract lives in docs/spec.
Index ¶
- Constants
- Variables
- func CheckBaseline(sigEl *Element, level BaselineLevel) error
- func ExtendC(doc *Document, sigEl *Element, refs *CompleteRefs, opts ExtendCOptions) error
- func ExtendLT(doc *Document, sigEl *Element, data *ValidationData) error
- func ExtendLTA(doc *Document, sigEl *Element, tsa TSAClient, opts ExtendLTAOptions) error
- func ExtendT(doc *Document, sigEl *Element, tsa TSAClient, opts ExtendTOptions) error
- func ExtendX(doc *Document, sigEl *Element, tsa TSAClient, opts ExtendXOptions) error
- type AlgorithmID
- type BaselineLevel
- type Canonicalizer
- type CertificateRef
- type CommitmentType
- type CompleteRefs
- type CounterSignatureResult
- type DataObjectFormat
- type DataObjectTimeStamp
- type Document
- type Element
- type ExtendCOptions
- type ExtendLTAOptions
- type ExtendTOptions
- type ExtendXOptions
- type HTTPTSAClient
- type IDAttr
- type Indication
- type IssuerSerial
- type KeyInfo
- type KeyInfoMode
- type Manifest
- type ManifestSpec
- type Object
- type ParseOption
- type ParsedSignaturePolicy
- type Policy
- type RefSpec
- type Reference
- type RenewedDigestsSpec
- type Request
- type Result
- type RetrievalMethod
- type RevocationRef
- type Signature
- type SignaturePolicy
- type SignaturePolicyRequirement
- type SignatureProperties
- type SignatureProperty
- type SignedInfo
- type Signer
- func (s *Signer) CounterSign(doc *Document, parentSigEl *Element) (*Element, error)
- func (s *Signer) Sign(doc *Document, req *Request) (*Element, error)
- func (s *Signer) SignDetached(doc *Document, refs ...RefSpec) (*Element, error)
- func (s *Signer) SignEnveloped(doc *Document, target *Element) (*Element, error)
- func (s *Signer) SignEnveloping(data *Element) (*Document, error)
- type SubIndication
- type TSAClient
- type TimeStampInfo
- type TimeStampValidationDataInfo
- type Transform
- type TransformSpec
- type ValidatedReference
- type ValidationData
- type ValidationModel
- type ValidationProcess
- type ValidationReport
- type Verifier
- func (v *Verifier) Validate(doc *Document, sigEl *Element, process ValidationProcess) *ValidationReport
- func (v *Verifier) Verify(doc *Document, sigEl *Element) (*Result, error)
- func (v *Verifier) VerifyCounterSignature(doc *Document, parentSigEl, counterSigEl *Element) (*Result, error)
- func (v *Verifier) VerifyCounterSignatures(doc *Document, parentSigEl *Element) []*CounterSignatureResult
- func (v *Verifier) VerifyDocument(doc *Document) (*Result, error)
- func (v *Verifier) VerifyXAdES(doc *Document, sigEl *Element) (*XAdESResult, error)
- type X509Data
- type X509Digest
- type XAdESProperties
- type XAdESResult
- type XTimeStamp
Constants ¶
const ( // NamespaceXAdES is the ETSI TS 101 903 v1.3.2 namespace; conventional prefix "xades". NamespaceXAdES = "http://uri.etsi.org/01903/v1.3.2#" // NamespaceXAdES141 is the v1.4.1 additions namespace; conventional prefix "xadesv141". NamespaceXAdES141 = "http://uri.etsi.org/01903/v1.4.1#" // XAdESSignedPropertiesType is the ds:Reference/@Type that marks the reference covering // xades:SignedProperties. It is version-independent (no /v1.x.y) — INV-XADES-SIGNEDPROPS-COVERED. XAdESSignedPropertiesType = "http://uri.etsi.org/01903#SignedProperties" // XAdESCounterSignatureType marks a ds:Reference of a counter-signature. XAdESCounterSignatureType = "http://uri.etsi.org/01903#CountersignedSignature" // ManifestReferenceType is the ds:Reference/@Type of a reference pointing at a ds:Manifest // (xmldsig-core1 §5.1): core validation verifies the digest OVER the manifest element, not the // manifest's inner references. ManifestReferenceType = "http://www.w3.org/2000/09/xmldsig#Manifest" )
XAdES namespaces and the version-independent property identifiers (EN 319 132-1 §6.3.1).
const NamespaceDS = "http://www.w3.org/2000/09/xmldsig#"
NamespaceDS is the XML Signature core namespace. Its conventional prefix is "ds".
const NamespaceDSig11 = "http://www.w3.org/2009/xmldsig11#"
NamespaceDSig11 is the XML Signature 1.1 namespace (ECKeyValue, X509Digest, DSA additions).
Variables ¶
var ( // ErrSignatureInvalid indicates the SignatureValue did not verify under the key. ErrSignatureInvalid = errors.New("xmldsig: signature is invalid") // ErrDigestMismatch indicates a Reference's recomputed digest did not match its DigestValue. ErrDigestMismatch = errors.New("xmldsig: reference digest mismatch") // ErrAlgorithmNotAllowed indicates a declared algorithm is not on the verifier allowlist. ErrAlgorithmNotAllowed = errors.New("xmldsig: algorithm not allowed") // ErrSignedDataNotFound indicates a Reference's signed data could not be obtained — the URI did // not dereference. Maps to EN 319 102-1 SIGNED_DATA_NOT_FOUND. ErrSignedDataNotFound = errors.New("xmldsig: signed data not found") // ErrReferenceProcessing indicates a Reference's data WAS obtained but could not be processed into // the digest input — a permitted transform or the implicit canonicalization failed at runtime (as // opposed to the data being absent). Maps to EN 319 102-1 FORMAT_FAILURE, not SIGNED_DATA_NOT_FOUND. ErrReferenceProcessing = errors.New("xmldsig: reference processing failed") // ErrNoSigningCertificate indicates the signing certificate could not be identified (no // certificate in KeyInfo and none supplied). Maps to EN 319 102-1 NO_SIGNING_CERTIFICATE_FOUND. ErrNoSigningCertificate = errors.New("xmldsig: signing certificate not found") // ErrAlgorithmSunset indicates a signature/digest algorithm was used at or after its configured // reliability sunset (Policy.AlgorithmExpiry), or is not on the allow-list. Maps to EN 319 102-1 // CRYPTO_CONSTRAINTS_FAILURE_NO_POE — time-relative, so it recovers in the §5.5/§5.6 processes when // the signature is proven to predate the sunset. ErrAlgorithmSunset = errors.New("xmldsig: algorithm past its reliability sunset") // ErrTimestampBeforeIssuance indicates a validated SignatureTimeStamp proves the signature existed // before the signing certificate's notBefore — the signature provably predates its own certificate // (EN 319 132-1 Annex G.2.2). It is a definitive forgery/backdating indicator, so it maps to // EN 319 102-1 FAILED/NOT_YET_VALID (§5.5.4 step 4a), not the generic SIG_CONSTRAINTS_FAILURE. ErrTimestampBeforeIssuance = errors.New("xmldsig: SignatureTimeStamp precedes the signing certificate's validity") )
Sentinel errors returned by verification. Verification failures are deliberately coarse-grained so as not to leak cryptographic detail (docs/spec/security.md §6).
var ErrCounterSignatureBinding = errors.New("xmldsig: countersignature does not bind the parent SignatureValue")
ErrCounterSignatureBinding is returned when a countersignature does not bind the signature it is claimed to countersign: none of its validated references is a CountersignedSignature reference resolving to that signature's ds:SignatureValue element.
var ErrDirectiveNotAllowed = xmltree.ErrDirectiveNotAllowed
ErrDirectiveNotAllowed is returned by Parse for a document containing a DOCTYPE / markup declaration when DTDs are not permitted (the default). DTDs are an XXE / entity-expansion attack surface, are omitted by canonicalization, and do not appear in conformant XML-DSig / XAdES documents; pass AllowDTD to accept them.
var ErrTimestampImprintMismatch = errors.New("xmldsig: timestamp message imprint mismatch")
ErrTimestampImprintMismatch is returned when a timestamp token's RFC 3161 message imprint does not equal the digest of the octets the XAdES clause prescribes (INV-TS-IMPRINT).
var ErrTraversalLimit = xmltree.ErrTraversalLimit
ErrTraversalLimit is returned by Parse for a document whose element tree exceeds the configured depth or node-count limit (a pathological deeply-nested or huge document). See WithLimits.
var ErrUnsupportedTransform = errors.New("xmldsig: unsupported transform")
ErrUnsupportedTransform is returned for a transform this library does not run: general XPath filtering (only the bounded not(ancestor-or-self::ds:Signature) idiom is supported, see transformXPath), general XPath Filter 2.0 (only the bounded subtract /descendant::ds:Signature idiom, see transformXPathFilter2), and XSLT (refused — arbitrary computation in a signed document, xmldsig-core1 §6.6.5).
Functions ¶
func CheckBaseline ¶
func CheckBaseline(sigEl *Element, level BaselineLevel) error
CheckBaseline verifies that sigEl's XAdES signature structurally conforms to the EN 319 132-1 Table 2 presence and cardinality requirements of the given baseline level: every "shall be present" element is present (with valid cardinality), no "shall not be present" element is present, and bounded-cardinality elements are within bounds. B-LT/B-LTA require the embedded CertificateValues and RevocationValues containers the project baseline contract selects; B-LTA additionally requires TimeStampValidationData. It returns nil on conformance, or an error listing every violation. It does not verify the semantic completeness of B-LT/B-LTA validation material (requirements p/t/x) — that is established by the §5.6 LTA validation process — nor the deep content requirements that other validation steps already enforce (e.g. the SigningCertificateV2 binding).
func ExtendC ¶
func ExtendC(doc *Document, sigEl *Element, refs *CompleteRefs, opts ExtendCOptions) error
ExtendC raises the XAdES signature sigEl to XAdES-C: CompleteCertificateRefs and CompleteRevocationRefs built from refs. The document is mutated in place.
func ExtendLT ¶
func ExtendLT(doc *Document, sigEl *Element, data *ValidationData) error
ExtendLT raises the XAdES signature sigEl to B-LT: the validation-data VALUES (CertificateValues, RevocationValues) in data embedded so the signature is self-contained. The document is mutated in place.
func ExtendLTA ¶
func ExtendLTA(doc *Document, sigEl *Element, tsa TSAClient, opts ExtendLTAOptions) error
ExtendLTA raises the XAdES signature sigEl in doc to B-LTA: an archive timestamp over the whole signature, stamped by tsa. Repeatable for timestamp renewal. The document is mutated in place.
func ExtendT ¶
func ExtendT(doc *Document, sigEl *Element, tsa TSAClient, opts ExtendTOptions) error
ExtendT raises the XAdES signature sigEl in doc to B-T: a SignatureTimeStamp over the canonicalized ds:SignatureValue, stamped by tsa. The signature must already be XAdES; the document is mutated in place.
func ExtendX ¶
func ExtendX(doc *Document, sigEl *Element, tsa TSAClient, opts ExtendXOptions) error
ExtendX raises the XAdES signature sigEl in doc to XAdES-X: a SigAndRefsTimeStamp (default) or RefsOnlyTimeStamp, stamped by tsa. ExtendC must have run first (it timestamps the references). The document is mutated in place.
Types ¶
type AlgorithmID ¶
type AlgorithmID string
AlgorithmID is a URI identifying a canonicalization, digest, signature, MAC, or transform algorithm, exactly as it appears in the Algorithm attribute of a ds:Signature. Algorithm identifiers are compared as opaque strings; the registries in this package map the recognized ones onto their cryptographic implementations.
const ( AlgC14N10 AlgorithmID = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315" AlgC14N10WithComments AlgorithmID = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" AlgC14N11 AlgorithmID = "http://www.w3.org/2006/12/xml-c14n11" AlgC14N11WithComments AlgorithmID = "http://www.w3.org/2006/12/xml-c14n11#WithComments" AlgExcC14N AlgorithmID = "http://www.w3.org/2001/10/xml-exc-c14n#" AlgExcC14NWithComments AlgorithmID = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments" )
Canonicalization method identifiers (Canonical XML 1.0 §1.1). The trailing '#' in AlgExcC14N is part of the URI.
const ( AlgEnvelopedSignature AlgorithmID = "http://www.w3.org/2000/09/xmldsig#enveloped-signature" AlgBase64 AlgorithmID = "http://www.w3.org/2000/09/xmldsig#base64" AlgXPath AlgorithmID = "http://www.w3.org/TR/1999/REC-xpath-19991116" AlgXPathFilter2 AlgorithmID = "http://www.w3.org/2002/06/xmldsig-filter2" AlgXSLT AlgorithmID = "http://www.w3.org/TR/1999/REC-xslt-19991116" )
Transform identifiers (xmldsig-core1 §6.6) that are not also canonicalization methods.
const ( AlgSHA1 AlgorithmID = "http://www.w3.org/2000/09/xmldsig#sha1" AlgSHA224 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#sha224" AlgSHA256 AlgorithmID = "http://www.w3.org/2001/04/xmlenc#sha256" AlgSHA384 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#sha384" AlgSHA512 AlgorithmID = "http://www.w3.org/2001/04/xmlenc#sha512" )
Digest (message-digest) algorithm identifiers (xmldsig-core1 §6). SHA-256/512 use the xmlenc namespace; SHA-224/384 use xmldsig-more.
const ( AlgRSASHA1 AlgorithmID = "http://www.w3.org/2000/09/xmldsig#rsa-sha1" AlgRSASHA224 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha224" AlgRSASHA256 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" AlgRSASHA384 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384" AlgRSASHA512 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512" )
RSA PKCS#1 v1.5 signature method identifiers.
const ( AlgRSAPSSSHA1 AlgorithmID = "http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1" AlgRSAPSSSHA224 AlgorithmID = "http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1" AlgRSAPSSSHA256 AlgorithmID = "http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1" AlgRSAPSSSHA384 AlgorithmID = "http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1" AlgRSAPSSSHA512 AlgorithmID = "http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1" )
RSASSA-PSS signature method identifiers (RFC 6931). MGF1 uses the same hash as the message digest; salt length equals the digest length.
const ( AlgECDSASHA1 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1" AlgECDSASHA224 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224" AlgECDSASHA256 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256" AlgECDSASHA384 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384" AlgECDSASHA512 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512" )
ECDSA signature method identifiers. SignatureValue is the fixed-width big-endian r‖s concatenation (IEEE P1363), never ASN.1 DER (INV-ECDSA-P1363).
const ( AlgEd25519 AlgorithmID = "http://www.w3.org/2021/04/xmldsig-more#eddsa-ed25519" AlgEd448 AlgorithmID = "http://www.w3.org/2021/04/xmldsig-more#eddsa-ed448" )
EdDSA signature method identifiers (RFC 9231). Ed25519 is fully supported; AlgEd448 is recognized for completeness but unserviced (the Go standard library has no Ed448) and the registries return an "unsupported method" error for it.
const ( AlgDSASHA1 AlgorithmID = "http://www.w3.org/2000/09/xmldsig#dsa-sha1" AlgDSASHA256 AlgorithmID = "http://www.w3.org/2009/xmldsig11#dsa-sha256" )
DSA signature method identifiers. Verify-only and obsolete (xmldsig-core1 §6).
const ( AlgHMACSHA1 AlgorithmID = "http://www.w3.org/2000/09/xmldsig#hmac-sha1" AlgHMACSHA224 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha224" AlgHMACSHA256 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256" AlgHMACSHA384 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384" AlgHMACSHA512 AlgorithmID = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512" )
HMAC (keyed-MAC) signature method identifiers. An HMAC result authenticates the message under a shared key; it never establishes signer identity (docs/spec/security.md §4).
type BaselineLevel ¶
type BaselineLevel int
BaselineLevel is one of the four ETSI EN 319 132-1 §6.1 XAdES baseline signature levels. The levels are cumulative in their mandatory content: each requires everything B-B requires plus its own additions.
const ( BaselineBB BaselineLevel = iota // B-B: signed (and some unsigned) qualifying properties at signing BaselineBT // B-T: a trusted token (SignatureTimeStamp) proving the signature existed BaselineBLT // B-LT: the validation material for long-term availability BaselineBLTA // B-LTA: archive timestamp(s) for long-term integrity )
func DetectBaseline ¶
func DetectBaseline(sigEl *Element) (BaselineLevel, bool)
DetectBaseline returns the highest baseline level sigEl's signature conforms to, or ok=false when it is not a XAdES signature or meets no level. B-T, B-LT, and B-LTA are distinguished by their hard-required SignatureTimeStamp, validation-value containers, and v1.4.1 ArchiveTimeStamp.
func (BaselineLevel) String ¶
func (l BaselineLevel) String() string
type Canonicalizer ¶
type Canonicalizer interface {
// Canonicalize returns the canonical octets of the given node-set.
Canonicalize(nodes ...*Element) ([]byte, error)
// Algorithm reports the canonicalization algorithm this canonicalizer implements.
Algorithm() AlgorithmID
}
Canonicalizer turns an XML node-set into the deterministic octet stream defined by a canonicalization algorithm (the Canonical XML RECs). For a fixed input node-set and algorithm the output is byte-for-byte deterministic (INV-C14N-DETERMINISM).
The elements passed to Canonicalize are the apex elements of the node-set, in document order; each is canonicalized together with its in-scope context per the algorithm.
func NewCanonicalizer ¶
func NewCanonicalizer(id AlgorithmID, inclusivePrefixes ...string) (Canonicalizer, error)
NewCanonicalizer returns a Canonicalizer for one of the six canonicalization-method URIs (Canonical XML 1.0 §1.1). For the exclusive variants, inclusivePrefixes is the InclusiveNamespaces PrefixList (use "#default" for the default namespace); it is ignored for the inclusive (1.0/1.1) variants.
type CertificateRef ¶
type CertificateRef struct {
DigestMethod AlgorithmID
DigestValue []byte
// contains filtered or unexported fields
}
CertificateRef is a parsed CompleteCertificateRefs/Cert reference (its CertDigest).
type CommitmentType ¶
type CommitmentType struct {
Identifier string // CommitmentTypeId/Identifier (an OID/URI); required
Description string // optional
ObjectReferences []string // "#refId" list; empty ⇒ AllSignedDataObjects
}
CommitmentType is a xades:CommitmentTypeIndication: the commitment the signer makes about the referenced data objects (or all of them).
type CompleteRefs ¶
type CompleteRefs struct {
Certificates []*x509.Certificate // CA chain certificates (excluding the signing certificate)
CRLs [][]byte // DER-encoded CRLs
OCSPResponses [][]byte // DER-encoded OCSP responses
Digest AlgorithmID // digest for the references; default SHA-256
IssuerSerialV1 bool // use the V1 IssuerSerial form in certificate references
}
CompleteRefs configures XAdES-C (ExtendC): references to the CA certificates and the revocation data (CRLs / OCSP responses) that validate the signing certificate's chain. These are unsigned properties; they store digests and identifiers (the values themselves land in X-L). The caller supplies the chain and revocation material (fetching lands with X-L).
type CounterSignatureResult ¶
type CounterSignatureResult struct {
// Element is the nested ds:Signature element of the countersignature.
Element *Element
// Result is the verified countersignature (its references, signing certificate, and chain); nil
// when Err is non-nil.
Result *Result
// Err is the verification or binding error for this countersignature, or nil on success.
Err error
}
CounterSignatureResult reports the verification of one countersignature.
type DataObjectFormat ¶
type DataObjectFormat struct {
ObjectReference string // "#refId" pointing at a ds:Reference; required
Description string
ObjectIdentifier string // optional OID/URI
MimeType string
Encoding string
}
DataObjectFormat is a xades:DataObjectFormat: format metadata about one signed data object, identified by ObjectReference (which must be "#" + the Id of a ds:Reference).
type DataObjectTimeStamp ¶
type DataObjectTimeStamp struct {
ObjectReferences []string
Canonicalization AlgorithmID // imprint c14n; default exclusive c14n
ImprintDigest AlgorithmID // digest the TSA imprints; default SHA-256
}
DataObjectTimeStamp configures a signed data-object timestamp built at signing time. An empty ObjectReferences yields an AllDataObjectsTimeStamp (all data references); a non-empty list yields an IndividualDataObjectsTimeStamp over those references ("#refId").
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is an opaque handle to a parsed XML document. Obtain one from Parse (or FromEtree), pass it to the Sign* / Verify* / Validate / Extend* entry points, and serialize it with Bytes or WriteTo. It wraps the library's internal beevik/etree tree; reach that tree, when you must, via Etree.
func FromEtree ¶
FromEtree wraps a *etree.Document built or parsed with beevik/etree directly. The xmldsig Parse function already returns a wrapped Document; this is the interop escape hatch for callers that build the tree themselves. Returns nil for a nil document.
func Parse ¶
func Parse(data []byte, opts ...ParseOption) (*Document, error)
Parse reads XML into a Document with the corrections the W3C canonicalization input model requires but encoding/xml (and thus a plain etree parse) omits:
- XML 1.0 §2.11 end-of-line normalization over the WHOLE document — including comments and processing instructions, where encoding/xml does not normalize #xD/CRLF.
- XML 1.0 §3.3.3 attribute-value normalization (literal whitespace → a single space, while character/entity references survive).
- duplicate-attribute preservation, so duplicate-Id wrapping attempts stay visible to ID resolution and digesting.
- DTD rejection (see AllowDTD).
Documents that will be signed or verified MUST be parsed with this function. A tree parsed with etree directly canonicalizes differently from conformant implementations and yields non-interoperable or failing signatures.
func ParseString ¶
func ParseString(s string, opts ...ParseOption) (*Document, error)
ParseString is Parse for a string.
func (*Document) Etree ¶
Etree returns the underlying *etree.Document — the interop escape hatch for code that inspects or mutates the tree with beevik/etree directly. Returns nil for a nil Document.
type Element ¶
type Element struct {
// contains filtered or unexported fields
}
Element is an opaque handle to an element within a Document — in particular the exact node a verified reference digested (ValidatedReference.Element), which the application must act on rather than re-resolving it by name (INV-REF-IS-WHAT-APP-READS, docs/spec/security.md §1). Reach the underlying tree node via Etree.
func CounterSignatureElements ¶
CounterSignatureElements returns the nested ds:Signature elements carried in the xades:CounterSignature unsigned properties of sigEl (EN 319 132-1 §5.2.7.2), in document order. Each is an independent signature that countersigns sigEl's ds:SignatureValue. Returns nil when sigEl is not a XAdES signature or carries no countersignatures.
func FindSignatures ¶
FindSignatures returns every ds:Signature element in root's subtree (root included), in document order.
func FromEtreeElement ¶
FromEtreeElement wraps a *etree.Element built with beevik/etree directly (e.g. a ds:Object payload for Request.Objects or SignEnveloping). Returns nil for a nil element.
func (*Element) Etree ¶
Etree returns the underlying *etree.Element — the interop escape hatch. Returns nil for a nil Element.
type ExtendCOptions ¶
type ExtendCOptions struct {
// UseV2 emits the EN 319 132-1 V2 form CompleteCertificateRefsV2 (xadesv141, with IssuerSerialV2
// certificate references). Default (false) emits the legacy TS 101 903 V1 CompleteCertificateRefs.
UseV2 bool
}
ExtendCOptions carries the optional knobs for ExtendC; the required CompleteRefs is a parameter.
type ExtendLTAOptions ¶
type ExtendLTAOptions struct {
// TimeStampValidationData is the timestamps' validation data embedded with the archive timestamp
// (the TSU certificate/revocation material). BaselineBLTA conformance requires it to be present, so
// a baseline-conformant first LTA extension supplies it; renewal calls can omit it when the
// signature already carries that material.
TimeStampValidationData *ValidationData
// RenewManifestDigests, when set, incorporates a xadesv141:RenewedDigestsV2 unsigned property
// (EN 319 132-1 §5.5.3) BEFORE the archive timestamp: for every reference of every signed detached
// ds:Manifest, it records the detached object's digest recomputed under a stronger algorithm, so a
// substitution is detected even if the manifest's own digest algorithm is broken.
RenewManifestDigests *RenewedDigestsSpec
Canonicalization AlgorithmID // c14n for the timestamp imprint; default exclusive c14n
ImprintDigest AlgorithmID // digest the TSA imprints; default SHA-256
Context context.Context // default context.Background()
}
ExtendLTAOptions carries the optional knobs for ExtendLTA; the required TSA client is a parameter.
type ExtendTOptions ¶
type ExtendTOptions struct {
Canonicalization AlgorithmID // c14n for the timestamp imprint; default exclusive c14n
ImprintDigest AlgorithmID // digest the TSA imprints; default SHA-256
Context context.Context // default context.Background()
}
ExtendTOptions carries the optional knobs for ExtendT; the required TSA client is a parameter.
type ExtendXOptions ¶
type ExtendXOptions struct {
XTimeStamp XTimeStamp // variant: XSigAndRefs (default) or XRefsOnly
Canonicalization AlgorithmID // c14n for the timestamp imprint; default exclusive c14n
ImprintDigest AlgorithmID // digest the TSA imprints; default SHA-256
Context context.Context // default context.Background()
// UseV2 emits the EN 319 132-1 V2 forms SigAndRefsTimeStampV2 / RefsOnlyTimeStampV2 (§A.1.5,
// covering the V2 reference properties). Default (false) emits the legacy TS 101 903 V1 forms.
UseV2 bool
}
ExtendXOptions carries the optional knobs for ExtendX; the required TSA client is a parameter.
type HTTPTSAClient ¶
type HTTPTSAClient struct {
URL string
HTTPClient *http.Client // defaults to http.DefaultClient
PolicyOID []int // optional requested TSA policy OID
Header map[string]string // optional extra request headers
}
HTTPTSAClient is a TSAClient that POSTs RFC 3161 requests to an HTTP timestamp authority.
func NewHTTPTSAClient ¶
func NewHTTPTSAClient(url string) *HTTPTSAClient
NewHTTPTSAClient returns an HTTPTSAClient for the given TSA endpoint URL.
type IDAttr ¶
IDAttr names an attribute recognized as an XML ID for same-document "#id" reference resolution. Space is the etree prefix ("xml" for xml:id, "" for an unprefixed attribute). ID resolution never matches arbitrary attributes (xmldsig-core1 §4.5, security.md §1).
type Indication ¶
type Indication int
Indication is the main status of the EN 319 102-1 signature validation process (§5.1.3). The zero value is Indeterminate, so an unpopulated report never reads as valid.
const ( // Indeterminate (INDETERMINATE): the performed checks do not allow ascertaining the signature // to be Passed or Failed; the result may change with more information or at a later time. Indeterminate Indication = iota // Passed (TOTAL-PASSED): the cryptographic checks succeeded and all checks prescribed by the // signature validation policy passed. Passed // Failed (TOTAL-FAILED): the cryptographic checks failed, or the signing certificate was proven // invalid at signing time, or the signature is not processable by the cryptographic block. Failed )
func (Indication) String ¶
func (i Indication) String() string
type IssuerSerial ¶
IssuerSerial is a ds:X509IssuerSerial (issuer distinguished name + serial number).
type KeyInfo ¶
type KeyInfo struct {
Id string
KeyNames []string
KeyValue crypto.PublicKey // parsed ds:KeyValue public key (RSA/DSA/EC), or nil
X509Data []*X509Data
RetrievalMethods []*RetrievalMethod
// contains filtered or unexported fields
}
KeyInfo is a typed view of ds:KeyInfo (xmldsig-core1 §4.5). Parsing extracts the content but confers NO trust: a key here is trusted only after binding to a trust anchor (certificate chain or pinned key) by the verifier (INV-KEYINFO-UNTRUSTED).
type KeyInfoMode ¶
type KeyInfoMode int
KeyInfoMode selects what a generated ds:KeyInfo contains.
const ( // KeyInfoAuto includes the certificate chain as X509Data when Certs is set, else nothing. KeyInfoAuto KeyInfoMode = iota // KeyInfoNone omits ds:KeyInfo entirely. KeyInfoNone // KeyInfoX509Certificate includes the certificate chain as ds:X509Data/ds:X509Certificate. KeyInfoX509Certificate // KeyInfoKeyValue includes only the raw public key as ds:KeyValue (RSA/EC). KeyInfoKeyValue // KeyInfoX509AndKeyValue includes both the certificate chain and the raw public key. KeyInfoX509AndKeyValue )
type Manifest ¶
type Manifest struct {
Id string
References []*Reference
// contains filtered or unexported fields
}
Manifest is a typed view of a ds:Manifest. Its References are NOT verified by core validation (xmldsig-core1 §5.1); the caller applies its own policy.
type ManifestSpec ¶
type ManifestSpec struct {
Id string // ds:Manifest/@Id; the SignedInfo Reference points at "#Id" (required)
References []RefSpec // the manifest's inner references (to the detached data objects)
DigestMethod AlgorithmID // digest for the SignedInfo Reference to the manifest; default Signer.DigestMethod
}
ManifestSpec describes a ds:Manifest to embed and sign indirectly: the signer builds a ds:Object/ds:Manifest holding the inner References (digested over their — typically detached — data objects) and adds one SignedInfo Reference of Type ManifestReferenceType pointing at the Manifest, so the signature covers the manifest element (and thereby its reference digests), while core validation does not itself verify the manifest's inner references (xmldsig-core1 §5.1) — the relying application applies its own policy to them.
type Object ¶
type Object struct {
Id string
MimeType string
Encoding string
Manifests []*Manifest
SignatureProperties []*SignatureProperties
// contains filtered or unexported fields
}
Object is a typed view of a ds:Object. Its Manifests and SignatureProperties are the direct ds:Manifest / ds:SignatureProperties children it carries.
type ParseOption ¶
type ParseOption func(*parseConfig)
ParseOption configures Parse.
func AllowDTD ¶
func AllowDTD() ParseOption
AllowDTD opts into accepting documents that contain a DOCTYPE / markup declaration (off by default). DTD-bearing documents are parsed unmodified, so the §3.3.3 attribute-value normalization is not applied to them.
func WithLimits ¶
func WithLimits(maxDepth, maxNodes int) ParseOption
WithLimits bounds the parsed document's element tree against resource exhaustion (deeply-nested or huge documents): at most maxDepth nested elements and maxNodes total elements; exceeding either returns ErrTraversalLimit. A non-positive value keeps that dimension's default (5000 depth / 5,000,000 nodes). These default bounds are generous for real signed documents while keeping the library's recursive tree walks within safe stack depth.
type ParsedSignaturePolicy ¶
type ParsedSignaturePolicy struct {
Implied bool
Identifier string
Transforms []Transform // ds:Transforms applied to the policy document before hashing
DigestMethod AlgorithmID
DigestValue []byte
SPURI string
}
ParsedSignaturePolicy is the SignaturePolicyIdentifier extracted from an EPES signature. The properties are signed (inside SignedProperties), so these values are trusted content.
type Policy ¶
type Policy struct {
Canonicalization map[AlgorithmID]bool // acceptable CanonicalizationMethod / c14n transforms
Digest map[AlgorithmID]bool // acceptable DigestMethod
Signature map[AlgorithmID]bool // acceptable SignatureMethod
Transform map[AlgorithmID]bool // acceptable transforms (besides canonicalization)
MinRSABits int // minimum RSA modulus size; 0 disables the check
// AlgorithmExpiry optionally records, per signature/digest algorithm, the time up to which it is
// considered cryptographically reliable (a "sunset date", à la ETSI TS 119 312). An algorithm
// allowed by the lists above but used at or after its sunset is INDETERMINATE/
// CRYPTO_CONSTRAINTS_FAILURE_NO_POE in the Basic process (EN 319 102-1 §5.2.8), and recovers in the
// §5.5 / §5.6 processes when the signature is proven (best-signature-time / a POE) to predate the
// sunset. Absent ⇒ no sunset (the algorithm is reliable as long as it is on the allow-lists).
AlgorithmExpiry map[AlgorithmID]time.Time
// ValidationModel selects the X.509 validity model for the §5.6 past-validation processes
// (ShellModel default; see ValidationModel). Affects only the §5.6.2.2 step-2b revocation slide.
ValidationModel ValidationModel
// TimeStampDelay optionally bounds how long after the claimed SigningTime the signature may first be
// timestamped (EN 319 102-1 §5.5.4 step 5 / §5.6.3 step 8). When > 0 and the signature carries a
// SigningTime, the §5.5/§5.6 processes require best-signature-time < SigningTime + TimeStampDelay;
// otherwise the signature is INDETERMINATE/SIG_CONSTRAINTS_FAILURE (the claimed time is not credibly
// close to the proven one). Zero disables the check.
TimeStampDelay time.Duration
RequireKeyInfo bool // require a ds:KeyInfo
AllowExternalReferences bool // permit dereferencing non-same-document references
}
Policy is the verifier's allow-list and strength policy: which algorithms are acceptable, minimum key strength, and whether external references are dereferenced. A document never selects its own acceptable algorithm — anything outside the policy fails closed (INV-ALG-ALLOWLIST, docs/spec/security.md §2).
func DefaultPolicy ¶
func DefaultPolicy() Policy
DefaultPolicy is the strict-secure default: SHA-2 digests only (no SHA-1), modern signature methods (no DSA, no SHA-1 signatures, no HMAC — HMAC proves shared-key authentication, not signer identity, docs/spec/security.md §4), RSA ≥ 2048 bits, and no external dereference.
func EIDASPolicy ¶
func EIDASPolicy() Policy
EIDASPolicy returns a verification Policy for eIDAS-conformant XAdES signatures (ETSI EN 319 132-1 baseline). It is the strict DefaultPolicy — modern algorithms only, RSA ≥ 2048, SHA-2 digests — plus the two enveloped-equivalent XPath idioms the EU signing stacks emit on the document reference:
- XPath Filter 2.0 subtract /descendant::ds:Signature — the EU DSS reference library's default for enveloped XAdES (Policy.Transform[AlgXPathFilter2]);
- plain XPath not(ancestor-or-self::ds:Signature) — the Spanish @firma / AutoFirma form (Policy.Transform[AlgXPath]).
Only those bounded idioms run (both reduce to "exclude every ds:Signature subtree"); any other XPath / XPath Filter 2.0 expression still fails closed, as does XSLT. Everything else matches DefaultPolicy, so a signature that does NOT use an XPath transform verifies identically under both.
This is verification policy only. To also enforce structural baseline conformance, set Verifier.RequireBaseline (e.g. &BaselineBLTA value); supply Verifier.TSARoots for B-T/B-LT/B-LTA timestamps and Verifier.CRLs / Verifier.OCSPResponses (or the signature's embedded RevocationValues) for B-LT/B-LTA revocation material.
func FacturaePolicy ¶
FacturaePolicy returns a verification Policy tuned for Spanish Facturae electronic invoices.
Real Facturae signatures — confirmed against the official AutoFirma / @firma output, the Facturae-PHP library, and a real signed .xsig invoice — are XAdES-EPES, enveloped, with a single document ds:Reference (URI="") carrying only the enveloped-signature transform, a SignedInfo canonicalized with Canonical XML 1.0, and the legacy V1 xades:SigningCertificate. The default verifier already handles that shape: Canonical XML 1.0 is on the DefaultPolicy allow-list, and the SigningCertificate(V2→V1) binding falls back to the V1 form (checkSigningCertificateBinding). So modern Facturae (SHA-256/512) verifies under DefaultPolicy unchanged, and FacturaePolicy(false) is just DefaultPolicy.
Facturae invoices produced before roughly 2018 are signed entirely with SHA-1 (rsa-sha1 and sha1 digests, ~1024-bit RSA keys). Pass allowLegacySHA1=true to accept those: it enables the SHA-1 digest and RSA-SHA1 signature methods (verify-only) and lowers the RSA modulus floor to 1024 bits. SHA-1 is cryptographically weak — enable it only to verify genuinely old invoices, and prefer pairing it with a historical Verifier.Now inside the signing certificate's validity window.
type RefSpec ¶
type RefSpec struct {
URI string // "" whole document, "#id" same-document
Transforms []TransformSpec // ordered transform chain
DigestMethod AlgorithmID // default = Signer.DigestMethod
Type string // optional ds:Reference/@Type
Id string // optional ds:Reference/@Id
}
RefSpec describes one data object to sign.
type Reference ¶
type Reference struct {
URI string // value of the URI attribute when present
HasURI bool // distinguishes URI="" (whole document) from an absent URI
Id string
Type string
Transforms []Transform
DigestMethod AlgorithmID
DigestValue []byte // decoded from base64
// contains filtered or unexported fields
}
Reference is a typed view of a ds:Reference.
type RenewedDigestsSpec ¶
type RenewedDigestsSpec struct {
DigestMethod AlgorithmID // the stronger digest algorithm for the recomputed values (required)
Canonicalization AlgorithmID // canonicalization for the OriginalRefDigest; default exclusive c14n
}
RenewedDigestsSpec configures RenewedDigestsV2 generation (EN 319 132-1 §5.5.3).
type Request ¶
type Request struct {
Id string // ds:Signature/@Id (optional)
References []RefSpec // at least one
Objects []*Element // ds:Object payloads to embed (e.g. enveloping data, XAdES props)
Manifests []ManifestSpec // signed ds:Manifest objects (each indirectly signed via a Manifest reference)
Parent *Element // element to append the Signature to; nil => document root
}
Request fully describes a signature for the general Sign entry point.
type Result ¶
type Result struct {
Signature *Signature
References []*ValidatedReference // the references whose digests were validated
SigningCert *x509.Certificate // the leaf certificate, when verified via a chain
Chains [][]*x509.Certificate
}
Result reports what a successful verification established.
type RetrievalMethod ¶
RetrievalMethod is a ds:RetrievalMethod (a pointer to key information held elsewhere). It is parsed but never dereferenced by default (docs/spec/security.md §5).
type RevocationRef ¶
type RevocationRef struct {
Kind string // "CRL" or "OCSP"
DigestMethod AlgorithmID
DigestValue []byte
// contains filtered or unexported fields
}
RevocationRef is a parsed CompleteRevocationRefs reference (a CRLRef or OCSPRef DigestAlgAndValue).
type Signature ¶
type Signature struct {
Id string
SignedInfo *SignedInfo
SignatureValue []byte // decoded from base64
SigValueId string // ds:SignatureValue/@Id, if present
KeyInfo *KeyInfo // nil if absent
Objects []*Object
// contains filtered or unexported fields
}
Signature is a typed view of a ds:Signature element. Each node retains (internally) its underlying source element so that canonicalization operates on the exact source octets rather than a re-serialized copy.
func ParseSignature ¶
ParseSignature parses a ds:Signature element into a typed Signature. The element's prefix is irrelevant; membership in the ds namespace is checked by resolved URI.
type SignaturePolicy ¶
type SignaturePolicy struct {
Implied bool // emit SignaturePolicyImplied; the explicit fields below are ignored
Identifier string // SigPolicyId/Identifier (an OID or URI); required when not Implied
Description string // optional SigPolicyId/Description
Transforms []TransformSpec // optional ds:Transforms applied to the policy document before hashing
DigestMethod AlgorithmID // SigPolicyHash digest method; required when not Implied
DigestValue []byte // SigPolicyHash over the (transformed) policy document; required when not Implied
SPURI string // optional SigPolicyQualifier/SPURI (where to obtain the policy)
}
SignaturePolicy configures the xades:SignaturePolicyIdentifier of an EPES signature (EN 319 132-1 §5.2). Either Implied (the empty SignaturePolicyImplied) or an explicit policy identified by Identifier and committed to via its digest.
type SignaturePolicyRequirement ¶
type SignaturePolicyRequirement struct {
// ID is the exact SigPolicyId/Identifier the signature's SignaturePolicyIdentifier must name;
// VerifyXAdES fails if the signature's policy is absent, implied, or different. Required — a
// non-nil requirement with an empty ID is a configuration error.
ID string
// Document, when non-nil, additionally verifies the signed EPES SigPolicyHash: the signature's
// SigPolicyHash DigestValue must equal the digest of these octets under its DigestMethod, binding
// the signature to the verifier's own trusted copy of the policy. Supply the exact octets the hash
// is computed over — for a PDF signature policy (the common eIDAS/Facturae case) the raw PDF bytes;
// if the SigPolicyHash declares ds:Transforms, supply the already-transformed octets (the transforms
// are not applied here). Nil ⇒ the policy identifier is matched but its hash is not checked.
Document []byte
}
SignaturePolicyRequirement requires a XAdES-EPES signature to be committed to a specific signature policy. A Verifier with a non-nil RequireSignaturePolicy fails VerifyXAdES unless the signature's SignaturePolicyIdentifier names exactly ID (and, when Document is set, its SigPolicyHash matches).
type SignatureProperties ¶
type SignatureProperties struct {
Id string
Properties []*SignatureProperty
// contains filtered or unexported fields
}
SignatureProperties is a typed view of a ds:SignatureProperties.
type SignatureProperty ¶
SignatureProperty is a typed view of a ds:SignatureProperty.
type SignedInfo ¶
type SignedInfo struct {
Id string
CanonicalizationMethod AlgorithmID
C14NInclusivePrefixes []string // PrefixList when the method is exclusive c14n
SignatureMethod AlgorithmID
References []*Reference
// contains filtered or unexported fields
}
SignedInfo is a typed view of ds:SignedInfo — the element that is canonicalized and signed.
type Signer ¶
type Signer struct {
Key crypto.PrivateKey // RSA, ECDSA, or Ed25519 private key
Certs []*x509.Certificate // leaf certificate first; optional for plain XML-DSig
SignatureMethod AlgorithmID // default derived from Key
Canonicalization AlgorithmID // SignedInfo c14n; default exclusive c14n
InclusivePrefixes []string // PrefixList; applied only when Canonicalization is exclusive c14n
DigestMethod AlgorithmID // default per-reference digest; default SHA-256
KeyInfo KeyInfoMode // default KeyInfoAuto
// XAdES, when non-nil, produces a XAdES-BES/EPES signature: the signed qualifying
// properties are woven into the same SignedInfo. Requires Certs. Nil ⇒ plain XML-DSig.
XAdES *XAdESProperties
// TSA timestamps signed data objects (XAdES.DataObjectTimeStamps) at signing time.
TSA TSAClient
}
Signer holds the key, certificate chain, and algorithm configuration for producing signatures; it is reused across documents. Zero-valued algorithm fields take secure defaults (exclusive c14n for SignedInfo, SHA-256 digests, a signature method derived from the key). Set XAdES to produce a XAdES-BES/EPES signature (signed qualifying properties); the unsigned XAdES levels are added post-signing by the Extend* functions.
func (*Signer) CounterSign ¶
CounterSign produces an enveloped countersignature of parentSigEl (EN 319 132-1 §5.2.7.2): it ensures the parent's ds:SignatureValue carries an Id, appends a new xades:CounterSignature unsigned qualifying property to the parent's UnsignedSignatureProperties, and signs into it a ds:Signature whose CountersignedSignature reference (Type "http://uri.etsi.org/01903#CountersignedSignature") digests the parent's canonicalized ds:SignatureValue. parentSigEl must be a XAdES signature (it must carry QualifyingProperties to hold the unsigned CounterSignature property). The countersignature is produced under this Signer's configuration (plain XML-DSig, or XAdES when Signer.XAdES is set). Returns the nested countersignature element.
func (*Signer) Sign ¶
Sign builds a ds:Signature for req, appends it under req.Parent (or the document root), fills every reference digest and the signature value, and returns the Signature element. The document is mutated in place; serialize it to emit the signed XML.
func (*Signer) SignDetached ¶
SignDetached signs the given references (typically same-document "#id" siblings) and places the Signature at the document root. Each reference defaults to the signer's canonicalization transform and digest method when unset.
func (*Signer) SignEnveloped ¶
SignEnveloped signs target (or, when target is the document root, the whole document) and appends the Signature as the last child of target, using the enveloped-signature transform plus the signer's canonicalization.
Note: a whole-document enveloped signature (URI="") digests everything except its own Signature. Adding a second whole-document enveloped signature afterwards therefore changes the first signature's digest input and invalidates it. For multiple signatures, sign distinct elements by Id or use detached signatures.
func (*Signer) SignEnveloping ¶
SignEnveloping wraps data in a ds:Object inside a new enveloping Signature (the Signature is the document root), signs the Object, and returns the new self-contained document; its Root is the Signature.
type SubIndication ¶
type SubIndication int
SubIndication qualifies a non-Passed Indication (EN 319 102-1 §5.1.3 and the building-block outputs), across the Basic (§5.3), Time/LTV (§5.5) and Archival (§5.6) validation processes.
const ( NoSubIndication SubIndication = iota // FAILED sub-indications. FormatFailure // the signature is not processable (§5.2.2) HashFailure // a signed data object's digest does not match the signature (§5.2.7) SigCryptoFailure // the signature value did not verify under the signing key (§5.2.7) // INDETERMINATE sub-indications. SignedDataNotFound // the signed data could not be obtained/processed (§5.2.7) NoSigningCertificateFound // the signing certificate could not be identified (§5.2.3) NoCertificateChainFound // no certificate chain to a trust anchor was found (§5.2.6) CertificateChainGeneralFailure // chain validation failed for an otherwise unclassified reason (§5.2.6) OutOfBoundsNoPOE // validation time is outside the signing certificate's validity, no proof it was once within (§5.2.6 step 7) RevokedNoPOE // the signing certificate is revoked, no proof the signature predates revocation (§5.2.6 step 4-b) RevokedCANoPOE // a CA certificate in the chain is revoked (§5.2.6 step 4-d) TryLater // revocation status could not be established freshly; retry with fresher data (§5.2.6 step 4-a/4-c) // SigConstraintsFailure: a signature-element / XAdES-profile constraint was not met (§5.2.8 SAV; // §5.2.2 NOTE assigns profile/level conformance here, not to Format Checking). This bucket // carries signature-WRAPPING defences (SignedProperties-not-covered, SigningCertificate binding, // QualifyingProperties/@Target mismatch) and, until the §5.5 layering, timestamp-imprint // mismatch. INDETERMINATE here is the spec-mandated outcome (TOTAL-FAILED is reserved for // cryptographic failure or a proven-invalid certificate, §5.1.3) — a relying application MUST // NOT treat it as transient/"retry later"; the signature is not acceptable as-is. SigConstraintsFailure // a signature-element constraint was not met (§5.2.8) CryptoConstraintsFailureNoPOE // an algorithm is no longer acceptable and there is no proof it was used while still strong (§5.2.8) // §5.6 (LTA) sub-indications. NotYetValid // best-signature-time is before the signing certificate's notBefore (§5.6.2.4 step 3) — FAILED RevocationOutOfBoundsNoPOE // no POE places the signing certificate's issuer within its validity when the revocation data was used (§5.6.2.4 step 1) // OutOfBoundsNotRevoked: the validation time is outside the signing certificate's validity, but the // certificate is KNOWN not to have been revoked (fresh revocation data confirms a good status, // §5.2.6 step 7 / NOTE 8). Distinct from OUT_OF_BOUNDS_NO_POE (revocation status unknown): a proof // the signature predates the expiry can recover it (§5.5 step 4)d) / §5.6). OutOfBoundsNotRevoked // TimestampOrderFailure: a SignatureTimeStamp is not posterior to a content (data-object) timestamp, // so the timestamps are temporally incoherent (§5.5.4 step 4)e), RFC 3161 §2.4.2 ordering). TimestampOrderFailure )
func (SubIndication) String ¶
func (s SubIndication) String() string
type TSAClient ¶
type TSAClient interface {
Timestamp(ctx context.Context, input []byte, hash crypto.Hash) (tokenDER []byte, err error)
}
TSAClient obtains an RFC 3161 timestamp token over the given input octets. Implementations compute the message imprint (digest of input under hash) and return the DER-encoded TimeStampToken (a CMS SignedData). A nil TSAClient disables timestamping.
type TimeStampInfo ¶
type TimeStampInfo struct {
Time time.Time
HashAlgorithm crypto.Hash
TSACertificates []*x509.Certificate
Element *Element // the XAdESTimeStamp element it came from
}
TimeStampInfo reports a validated timestamp token.
type TimeStampValidationDataInfo ¶
type TimeStampValidationDataInfo struct {
Certificates []*x509.Certificate
CRLs []*x509.RevocationList
OCSPs []*ocsp.Response
// contains filtered or unexported fields
}
TimeStampValidationDataInfo is a parsed xadesv141:TimeStampValidationData property: the certificate and revocation values supplied for validating the signature's electronic timestamps (EN 319 132-1 §5.5.1). Distinct from the B-LT CertificateValues/RevocationValues, which validate the SIGNING certificate.
type Transform ¶
type Transform struct {
Algorithm AlgorithmID
InclusivePrefixes []string // PrefixList for the exclusive-c14n transform
// contains filtered or unexported fields
}
Transform is one ds:Transform in a Reference's transform chain.
type TransformSpec ¶
type TransformSpec struct {
Algorithm AlgorithmID
InclusivePrefixes []string // PrefixList for the exclusive-c14n transform
}
TransformSpec is one transform in a reference's chain.
type ValidatedReference ¶
ValidatedReference pairs a validated reference with the exact element it digested, so the caller acts on that node rather than re-resolving by name (INV-REF-IS-WHAT-APP-READS, docs/spec/security.md §1). Element is nil for the whole-document reference (URI="").
type ValidationData ¶
type ValidationData struct {
Certificates []*x509.Certificate // trust-anchor + CA-path + revocation-signer certs (EncapsulatedX509Certificate)
CRLs [][]byte // DER-encoded X.509 CRLs (EncapsulatedCRLValue)
OCSPResponses [][]byte // DER-encoded RFC 6960 OCSP responses (EncapsulatedOCSPValue)
}
ValidationData configures XAdES B-LT (ExtendLT): the certificate and revocation VALUES embedded into the signature for long-term validation (EN 319 132-1 §5.4.2 CertificateValues, §5.4.3 RevocationValues). Unlike the XAdES-C/X references (which store digests), B-LT embeds the actual DER material so the signature is self-contained. B-LT does not require a prior C/X step.
type ValidationModel ¶
type ValidationModel int
ValidationModel selects the X.509 validity model the §5.6 past-validation processes use (EN 319 102-1 §5.6.2.1 step 2, §5.6.2.2 step 2b). The zero value is ShellModel — the XAdES default and the established behavior — so an unset Policy is unchanged.
const ( // ShellModel: every certificate must be valid at the one validation time, and validation-time // sliding always slides control-time to a certificate's revocation time (EN 319 102-1 §5.6.2.2 // step 2b, RFC 5280 §6.1). The default. ShellModel ValidationModel = iota // ChainModel (EN 319 102-1 §5.6.2.2 / §5.6.2.1; the German "Kettenmodell"): the §5.6 past-validation // processes validate each certificate at the time it was USED, not all at one instant. Two effects: // - Revocation slide (§5.6.2.2 step 2b): validation-time sliding slides on a revocation only when the // reason is key compromise or unknown — an administrative revocation (superseded, // affiliationChanged, cessationOfOperation, privilegeWithdrawn) does not invalidate signatures // made before it (see revocationSlideTime). // - Path validity (§5.6.2.1 step 2 ii): the prospective chain is built so each CA is valid at the // time it ISSUED the subordinate, accepting a chain whose certificate validity windows do not // overlap at a single instant (a renewed upper CA) — see buildPastChainModel, which fails safe // (conservative no-chain) for any certificate carrying a constraint it does not enforce. ChainModel )
type ValidationProcess ¶
type ValidationProcess int
ValidationProcess selects which EN 319 102-1 signature validation process Validate runs. The processes nest, each building on the previous: Basic (§5.3) ⊂ WithTime (§5.5) ⊂ Archival (§5.6).
const ( // ProcessBasic runs the §5.3 Basic Signature validation process: Format Checking (§5.2.2), // signing-certificate identification (§5.2.3), X.509 Certificate Validation (§5.2.6), // Cryptographic Verification (§5.2.7) and Signature Acceptance Validation (§5.2.8), with // certificate validation at the verifier's current time. The zero value. ProcessBasic ValidationProcess = iota // ProcessWithTime runs the §5.5 process for Signatures with Time and Signatures with Long-Term // Validation Material: it starts from the Basic result and uses best-signature-time — the earliest // time the signature is proven to have existed, from trusted SignatureTimeStamp tokens — to recover // the revocation / expiry / crypto-sunset INDETERMINATE outcomes a proof of existence resolves. ProcessWithTime // ProcessArchival runs the §5.6 process for Signatures providing Long Term Availability and // Integrity of Validation Material: it starts from the §5.5 result and, with the proof-of-existence // set accumulated from TSA-trusted archive timestamps, runs past signature validation. ProcessArchival )
type ValidationReport ¶
type ValidationReport struct {
Indication Indication
SubIndication SubIndication
// XAdES is the underlying verified result when validation reached cryptographic success, else nil.
XAdES *XAdESResult
// Chain is the validated certificate chain (leaf first) when one was established.
Chain []*x509.Certificate
// BestSignatureTime is the earliest time the signature is proven to have existed (EN 319 102-1
// §5.5.3 / §5.5.4): the earliest trusted SignatureTimeStamp generation time, else the current
// time. Set only by the §5.5 process (Validate with ProcessWithTime); HasBestSignatureTime reports
// whether it was populated.
BestSignatureTime time.Time
HasBestSignatureTime bool
// Detail is a human-readable explanation. It never carries cryptographic secrets (the
// underlying errors are deliberately coarse — see errors.go).
Detail string
}
ValidationReport is the output of the EN 319 102-1 signature validation process (§5.1.3): the main Indication, a qualifying SubIndication, and supporting material.
type Verifier ¶
type Verifier struct {
Policy Policy
Roots *x509.CertPool // trust anchors; KeyInfo certificates are chain-validated against these
Intermediates *x509.CertPool // optional additional intermediate certificates
// KeyFunc, if set, supplies the verification key directly (e.g. a pinned public key, or an
// HMAC secret as []byte), bypassing certificate-chain validation. It is the caller's
// responsibility to return only a trusted key.
KeyFunc func(ki *KeyInfo, method AlgorithmID) (crypto.PublicKey, error)
// TrustedKeys pins public keys: a signature whose KeyInfo carries a bare ds:KeyValue is
// trusted only when that key matches one of these (there is no certificate chain to
// validate). Ignored when a certificate or KeyFunc establishes trust.
TrustedKeys []crypto.PublicKey
// IDAttributes augments the recognized ID attributes for "#id" resolution (e.g. SAML "ID").
IDAttributes []IDAttr
// RequireSignaturePolicy, when non-nil, requires a XAdES-EPES signature committed to a specific
// signature policy (its identifier, and optionally its hash): a signature whose SignaturePolicyIdentifier
// is absent, implied, or different fails VerifyXAdES. Nil ⇒ no policy requirement. See
// SignaturePolicyRequirement.
RequireSignaturePolicy *SignaturePolicyRequirement
// TSARoots are the trust anchors for timestamp (TSA) certificates: each timestamp token's TSA
// certificate is chain-validated against these at the token's genTime. A signature that carries
// timestamp tokens cannot validate those tokens when TSARoots is nil.
TSARoots *x509.CertPool
// Now supplies the time for certificate validity checks; defaults to time.Now.
Now func() time.Time
// CRLs and OCSPResponses supply revocation data for the EN 319 102-1 §5.2.6 revocation check,
// in addition to any embedded in the signature (XAdES RevocationValues). Each is honoured only
// when its signature verifies against the chain-validated issuer (INV-REVOCATION-AUTHENTIC).
CRLs []*x509.RevocationList
OCSPResponses []*ocsp.Response
// RequireRevocation, when true, requires a fresh non-revoked status for every certificate in the
// chain (the trust anchor excepted): a certificate with no fresh revocation data makes the
// signature INDETERMINATE/TRY_LATER. When false (default), a known revocation still fails, but
// absent/stale data does not (lenient, suitable for signatures without embedded revocation data).
RequireRevocation bool
// RequireBaseline, when non-nil, requires the signature to structurally conform to the given
// EN 319 132-1 baseline level (Table 2); a non-conforming signature makes Validate return
// INDETERMINATE/SIG_CONSTRAINTS_FAILURE (§5.2.8 Signature Acceptance Validation). Nil ⇒ no
// baseline-conformance requirement.
RequireBaseline *BaselineLevel
}
Verifier validates signatures under a Policy and a trust configuration. The verification key is established by binding KeyInfo to a trust anchor: either a configured certificate-chain root set (Roots) or a caller-supplied KeyFunc. A key is never trusted merely because it appears in KeyInfo (INV-KEYINFO-UNTRUSTED, docs/spec/security.md §4).
func (*Verifier) Validate ¶
func (v *Verifier) Validate(doc *Document, sigEl *Element, process ValidationProcess) *ValidationReport
Validate runs the selected EN 319 102-1 signature validation process over the XAdES signature sigEl in doc, returning a ValidationReport whose Indication/SubIndication encode the outcome — validation failures are reported in the status, not as Go errors (the three-valued PASSED/FAILED/INDETERMINATE model is why Validate* return a report while Verify* return an error). Each process starts from the previous one's result (see ValidationProcess): a higher process can RECOVER the recoverable INDETERMINATE outcomes of a lower one (a revocation/expiry/crypto-sunset the signature is proven to predate), but it also applies the additional acceptance checks its tier mandates (e.g. time-stamp delay and timestamp coherence in §5.5), so it is not a pure refinement — a higher process may report INDETERMINATE where the Basic process PASSED.
func (*Verifier) Verify ¶
Verify validates the ds:Signature element sigEl within doc: it enforces the algorithm allow-list, validates every reference digest, binds the key to a trust anchor, and confirms the signature over the canonicalized SignedInfo. All checks must pass.
func (*Verifier) VerifyCounterSignature ¶
func (v *Verifier) VerifyCounterSignature(doc *Document, parentSigEl, counterSigEl *Element) (*Result, error)
VerifyCounterSignature verifies counterSigEl as a signature and confirms it countersigns parentSigEl (EN 319 132-1 §5.2.7): the countersignature must verify cryptographically AND one of its validated references must be a CountersignedSignature reference (Type "http://uri.etsi.org/01903#CountersignedSignature") that resolves, by element identity, to parentSigEl's ds:SignatureValue element. The element-identity binding (INV-COUNTERSIG-BINDS-PARENT) is what blocks relocating a countersignature onto a signature it did not countersign — a reference merely typed as a countersignature, or one resolving to a different element, is rejected.
func (*Verifier) VerifyCounterSignatures ¶
func (v *Verifier) VerifyCounterSignatures(doc *Document, parentSigEl *Element) []*CounterSignatureResult
VerifyCounterSignatures discovers every direct countersignature of parentSigEl (the xades:CounterSignature properties, §5.2.7.2) and verifies each against parentSigEl. It returns one result per countersignature, in document order, each carrying either a verified Result or an Err — a failing countersignature does not abort the others, and (because a countersignature is an unsigned property) does not affect the validity of parentSigEl itself.
func (*Verifier) VerifyDocument ¶
VerifyDocument finds the single ds:Signature in doc and verifies it.
func (*Verifier) VerifyXAdES ¶
func (v *Verifier) VerifyXAdES(doc *Document, sigEl *Element) (*XAdESResult, error)
VerifyXAdES performs core XML-DSig validation and then the XAdES-BES/EPES obligations: it confirms SignedProperties is signed (INV-XADES-SIGNEDPROPS-COVERED) and that the SigningCertificate(V2) binds the certificate that actually verified the signature (INV-XADES-SIGNINGCERT-BINDING). It requires certificate-chain trust so a signing certificate is established (EN 319 132-1 Annex G.2.2).
type X509Data ¶
type X509Data struct {
Certificates []*x509.Certificate
SubjectNames []string // ds:X509SubjectName (RFC 4514 DN strings)
IssuerSerials []IssuerSerial // ds:X509IssuerSerial
SKIs [][]byte // ds:X509SKI (raw subject key identifier octets)
CRLs [][]byte // ds:X509CRL (DER)
Digests []X509Digest // dsig11:X509Digest
// contains filtered or unexported fields
}
X509Data is a typed view of a ds:X509Data element.
type X509Digest ¶
type X509Digest struct {
Algorithm AlgorithmID
Value []byte
}
X509Digest is a dsig11:X509Digest (a digest over a certificate's DER encoding).
type XAdESProperties ¶
type XAdESProperties struct {
// SigningTime, when non-zero, is emitted as xades:SigningTime (rendered in UTC, xsd:dateTime).
SigningTime time.Time
// SigningCertificateV1 selects the legacy SigningCertificate form (X509IssuerName DN string +
// serial). The default (false) emits SigningCertificateV2 with IssuerSerialV2 (DER ESS
// IssuerSerial), avoiding the DN-string canonicalization ambiguity (EN 319 132-1 §5.2).
SigningCertificateV1 bool
// CertDigestMethod is the digest algorithm for the SigningCertificate CertDigest; defaults
// to the Signer's DigestMethod.
CertDigestMethod AlgorithmID
// SignaturePolicy, when non-nil, emits a xades:SignaturePolicyIdentifier, making the
// signature XAdES-EPES rather than -BES (EN 319 132-1 §6).
SignaturePolicy *SignaturePolicy
// DataObjectFormats and CommitmentTypes populate xades:SignedDataObjectProperties.
DataObjectFormats []DataObjectFormat
CommitmentTypes []CommitmentType
// DataObjectTimeStamps are signed timestamps over the data objects, built at signing time;
// they require the Signer's TSA client.
DataObjectTimeStamps []DataObjectTimeStamp
}
XAdESProperties configures the signed qualifying properties of a XAdES-BES/EPES signature. A nil *XAdESProperties on a Signer produces a plain XML-DSig signature. When set, the Signer requires a certificate (for SigningCertificate) and gives the ds:Signature an Id.
type XAdESResult ¶
type XAdESResult struct {
*Result
QualifyingProperties *Element
SignedProperties *Element
SigningTime time.Time // parsed xades:SigningTime, if present
HasSigningTime bool
SignaturePolicy *ParsedSignaturePolicy // nil for BES (no SignaturePolicyIdentifier)
SignatureTimeStamps []*TimeStampInfo // validated SignatureTimeStamp tokens (XAdES-T)
DataObjectTimeStamps []*TimeStampInfo // validated All/Individual data-object timestamps
CertificateRefs []*CertificateRef // CompleteCertificateRefs (XAdES-C)
RevocationRefs []*RevocationRef // CompleteRevocationRefs (XAdES-C)
XTimeStamps []*TimeStampInfo // SigAndRefs/RefsOnly timestamps (XAdES-X)
EmbeddedCertificates []*x509.Certificate // CertificateValues (XAdES B-LT)
EmbeddedCRLs []*x509.RevocationList // RevocationValues/CRLValues (XAdES B-LT)
EmbeddedOCSPs []*ocsp.Response // RevocationValues/OCSPValues (XAdES B-LT)
ArchiveTimeStamps []*TimeStampInfo // validated xadesv141:ArchiveTimeStamp tokens (XAdES B-LTA)
// TimeStampValidationData holds each xadesv141:TimeStampValidationData property's parsed
// validation material for the signature's timestamps (XAdES B-LTA).
TimeStampValidationData []*TimeStampValidationDataInfo
}
XAdESResult reports what a successful XAdES verification established, on top of the core XML-DSig Result.
type XTimeStamp ¶
type XTimeStamp int
XTimeStamp selects the XAdES-X timestamp variant (ExtendX, EN 319 132-1 §5.1.4 / §6).
const ( // XSigAndRefs is a SigAndRefsTimeStamp (type 1): over ds:SignatureValue, the // SignatureTimeStamps, and the certificate/revocation references. XSigAndRefs XTimeStamp = iota // XRefsOnly is a RefsOnlyTimeStamp (type 2): over the certificate/revocation references only. XRefsOnly )
Source Files
¶
- algorithm.go
- baseline.go
- canonicalizer.go
- canonicalizer_impl.go
- counter_signature.go
- crl_indirect.go
- cryptobinary.go
- digest.go
- dom.go
- ecdsa.go
- eidas.go
- errors.go
- extend.go
- facturae.go
- hmac.go
- idresolve.go
- keyinfo.go
- lta.go
- model.go
- parse.go
- parse_signature.go
- reference.go
- renewed_digests.go
- revocation.go
- signaturemethod.go
- signer.go
- timestamp.go
- transform.go
- validation.go
- verifier.go
- xades.go
- xades_c.go
- xades_lt.go
- xades_lta.go
- xades_properties.go
- xades_verify.go
- xades_x.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
c14n
Package c14n implements W3C XML canonicalization: Canonical XML 1.0 and 1.1 (inclusive) and Exclusive XML Canonicalization 1.0, each with and without comments.
|
Package c14n implements W3C XML canonicalization: Canonical XML 1.0 and 1.1 (inclusive) and Exclusive XML Canonicalization 1.0, each with and without comments. |
|
xmltree
Package xmltree parses XML into a beevik/etree tree with the corrections this library needs for canonicalization that encoding/xml does not perform on its own.
|
Package xmltree parses XML into a beevik/etree tree with the corrections this library needs for canonicalization that encoding/xml does not perform on its own. |