cms

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: BSD-3-Clause Imports: 18 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cms

Read, verify and sign CMS SignedData (RFC 5652) in pure Go, with no dependencies beyond the standard library — the container behind a PDF signature, a UEFI authenticated variable and an S/MIME message. CGO_ENABLED=0.

sd, err := cms.Parse(der)          // the signature's DER, e.g. a PDF's /Contents
if err != nil { … }
certs, err := sd.Verify(signed)    // the bytes it signed; nil when attached
if err != nil { … }
// certs[i] is the certificate signer i used. Whether to TRUST it — its chain,
// validity and revocation — is yours: crypto/x509's Verify, and
// go-authn/revocation for CRLs.

Signing

der, err := cms.Sign(signed, cms.SignOptions{
	Signer:      key,   // any crypto.Signer: RSA, ECDSA or Ed25519 — a card or an HSM too
	Certificate: cert,  // embedded; the SignerInfo names it by issuer and serial
	Chain:       chain, // optional intermediates
	Hash:        crypto.SHA256,
	Detached:    true,  // a PDF signature's /Contents: the content is not inside
	SigningTime:          time.Now(), // optional signing-time attribute
	SigningCertificateV2: true,       // RFC 5035: what CAdES / PAdES baseline require
})

Sign returns one DER ContentInfo with one signer. Combinations it emits, each judged by openssl cms -verify and by Verify:

keys RSA PKCS #1 v1.5, RSASSA-PSS (PSS: true), ECDSA, Ed25519
digest SHA-256 (default), SHA-384, SHA-512; Ed25519 always SHA-512 (RFC 8419 §3.1)
content attached or Detached; ContentType defaults to id-data (other types force version 3 and signed attributes, §5.1)
attributes content-type and message-digest; optional signing-time (UTCTime for 1950–2049, GeneralizedTime outside, §11.3) and signing-certificate-v2 (RFC 5035 §5.4.1, SHA-256 hash algorithm left out as DER's DEFAULT); or none at all (NoSignedAttrs)
  • Signed attributes are DER: a SET OF sorted by encoding, because §5.4 signs those bytes and Verify is strict about them. The embedded certificate set is sorted and deduplicated for the same reason.
  • Digest algorithm identifiers carry no NULL parameters, as RFC 5754 §2 has implementations generate them; RSA's rsaEncryption carries one, as PKCS #1 and OpenSSL write it.
  • Refused, with ErrUnsupported: SHA-1 (by name) and any other hash, a key that is not RSA, ECDSA or Ed25519. With ErrOptions: no signer or certificate, a certificate whose public key is not the signer's, Ed25519 with a digest other than SHA-512, PSS on a non-RSA key, NoSignedAttrs with a content type other than id-data or with attributes requested, a signing time outside years 0–9999, and Ed25519 without signed attributes: RFC 8419 §3.2 allows it and Verify reads it, but OpenSSL does not verify what this package writes (4.1.0 answers "no content" to the attached form; the 3.x on CI answers "invalid eddsa instance" to the detached one), so it is not emitted.
  • The signature is checked before it is returned. Public() matching the certificate does not vouch for what a card, HSM or remote signer returns, so Sign verifies the signature under the certificate, over the exact bytes signed and with the algorithm and PSS parameters it declares. A signature from another key, a nil one, or PKCS #1 v1.5 where PSS was asked, is refused.
  • ErrSigner is what the signer's own failure and that refusal both wrap (the signer's error stays in the chain), so a caller can branch on ErrSigner (the key or device), ErrOptions (the request) and ErrUnsupported (an algorithm).
  • Verify does not check signing-certificate-v2. Pinning the signer's certificate to that attribute is the caller's, with the chain.
UEFI authenticated variables

go-filesystems/uefi's private encoder writes a detached PKCS #7 SignedData over SHA-256, RSA PKCS #1 v1.5, no signed attributes, one embedded certificate. SignOptions{Signer, Certificate, Hash: crypto.SHA256, Detached: true, NoSignedAttrs: true} is that shape; a test pins it (the signature is the plain RSA signature of SHA-256 of the content, which is what edk2 recomputes) and openssl smime -verify, which drives the PKCS #7 reader edk2 is built on, accepts it. The one byte-level difference is that the digest identifiers omit the NULL parameters RFC 5754 asks implementations not to write.

What it checks

Every rule below is enforced, and every refusal is tested by message, so a test cannot pass because some other check happened to fire first.

RFC rule
§5.3 both signer-identifier forms are read: issuer and serial, and subject key identifier
§5.3 signedAttrs must be present when the content is not id-data, and is never an empty set
§5.3, §11.1 exactly one content-type attribute, with exactly one value
§5.3, §11.2 exactly one message-digest attribute, with exactly one value
§5.6 the signed content type equals eContentType
§5.6 the digest is recomputed here — "The recipient MUST NOT rely on any message digest values computed by the originator"
§5.4 the signature covers signedAttrs with its [0] IMPLICIT tag rewritten to SET OF, on the bytes as they arrived — never a re-encoding
§5.1 an unimplemented algorithm is refused gracefully, as ErrUnsupported
§5.3 (DER) signedAttrs is a constructed [0]; each attribute is a SEQUENCE of an OID and a real SET, with nothing after it
8419 §3.1 Ed25519 requires digestAlgorithm SHA-512 and no signature-algorithm parameters

Section numbers are RFC 5652's unless marked 8419.

Beyond the RFC, a signature algorithm that names a hash of its own (sha256WithRSAEncryption, ecdsa-with-SHA384) must name the same hash as the digestAlgorithm. Otherwise one SignerInfo would be making two statements about which hash protects it, and only one would be checked.

⚠ Stricter than OpenSSL on two of these. OpenSSL 4.1.0 accepts a primitive 0x80 tag on the signed attributes — one bit away from a valid signature, still verifying — and Ed25519 over SHA-256. This package refuses both. The oracle agreement below still holds because no OpenSSL-made fixture exercises either: OpenSSL never writes them, it only fails to refuse them.

Resource bounds

  • 16 MiB of input at most.
  • 16 signers at most, and the content is hashed once per digest algorithm, not once per signer. A size bound is not a work bound: review repeated one valid self-signed signer 4 000 times in a 5 MB input over 4 MiB of content, and verification took 25 s of CPU — about forty thousand signers would fit under the size limit. The cap is what bounds Ed25519 without signed attributes, which hashes the content inside ed25519.Verify on every call.

Algorithms: RSA PKCS #1 v1.5, RSASSA-PSS, ECDSA and Ed25519 (RFC 8419), over SHA-256, SHA-384 and SHA-512. The signature arithmetic itself is crypto/x509's CheckSignature, not reimplemented here.

Refused by name: SHA-1 (collisions in it are practical), and RSASSA-PSS parameters other than the ones crypto/x509 verifies — the digest's hash, MGF1 over that hash, and a hash-length salt.

Three errors, because a caller needs three answers

error means
ErrMalformed not a SignedData this package can read
ErrUnsupported a signature, using something not implemented here
ErrInvalid readable and supported, and the signature does not hold

The fuzz targets hold this as an invariant: every refusal wraps exactly one of the three. A decoder error passed up unclassified would leave a caller unable to tell a forgery from a format it merely does not speak.

⛔ What it does not do — yet

  • DER only. RFC 5652 allows the outer structure to be BER, and some producers write indefinite lengths. encoding/asn1 does not read them, so such an input is refused as ErrMalformed, never guessed at. The signed attributes must be DER in every case (§5.3), so this limit never weakens what is verified — it only turns away some well-formed inputs.
  • Signing is one signer, no unsigned attributes, no timestamps. No counter-signatures, no RFC 3161 timestamp token, no CRLs or OCSP responses in the container, no subject-key-identifier signer identifier, no BER.
  • No chain validation, on purpose: RFC 5652 §5.6 places it "beyond the scope of this document". Verify returns the certificates that signed; trust is a separate decision with separate inputs.
  • Every signer must verify. §5.1 lets an application accept one good signature from a signer that signed several times; a caller that wants that can verify signers individually.

How it is judged

The judge is OpenSSL's cms command, not this package: a fixture written by the code under test can only agree with it.

  • Eleven signatures made by OpenSSL 4.1.0 are committed under testdata/: RSA (attached, detached, without attributes, by key identifier, SHA-384, SHA-512), RSASSA-PSS, ECDSA P-256 (with and without attributes, SHA-384) and Ed25519. Private keys are generated in a temporary directory and discarded; only certificates, signatures and content are committed.
  • TestOpenSSLAgrees hands each fixture, and each of its tampered variants, to openssl cms -verify and to this package, and requires the same verdict: 34 of 34 agree, the tampered ones refused by both. The tampering includes a byte of the content inside an attached signature — the first version of this test checked only the detached form and so tested no tampering at all on the attached one.
  • The rules OpenSSL will never produce a violation of — duplicate attributes, a lying content type, mismatched hashes — are built by changing OpenSSL's output in exactly one place. The builder first proves it is the identity: an unchanged rebuild must equal the fixture byte for byte.

⛔ The oracle found a real defect before the first commit. The parser read the [0] EXPLICIT wrapper of eContent as if it were the OCTET STRING inside it, so it could read no attached signature at all. Detached signatures — the only kind a PDF uses — never reached that line, which is why everything else passed.

Measured

  • Signing oracle: TestSignedByUsJudgedByOpenSSL signs 58 combinations (keys × digests × attached/detached × attribute sets) and asks OpenSSL and Verify about each one untouched and tampered: 203 verdicts, every pair equal, only the untouched ones accepted. Sweeping sign.go's refusals left 0 survivors.

  • Coverage: every block — 0 of 294 uncovered, judged by covblocks, which counts blocks rather than printing a rounded percentage.

  • Mutation-swept: every refusal in the package, 45 mutations, 0 survived and 0 caught by a crash — each guard is held by an assertion that names it. Getting there took three changes the sweep forced: refusal tests now turn a panic into a named failure, and one message was reworded because another refusal's message contained it, so its test passed with its guard deleted.

  • Fuzzed: FuzzVerify asserts that nothing verifies unless what its signature binds — signed attributes, signature, public key, content — is exactly what OpenSSL signed. Disabling the signature check makes it report a forgery in 5.7 s, and that input is in the committed corpus.

    ⛔ But an early count here measured less than it claimed. It reported 13 694 176 executions with no failure, and a one-bit change — the signed-attributes tag turned from constructed to primitive — verified the whole time, which this target's own invariant calls a forgery. The fuzzer never flipped that bit; external review found it by reading the tag check. It is refused now, and the flipped input is seeded so every plain go test asks again rather than hoping a mutator finds it. A clean fuzz run is a statement about the inputs it happened to build.

  • go vet on darwin, linux, windows, and the 32-bit 386 and arm targets.

Install

go get github.com/go-authn/cms

License

BSD 3-Clause.

Documentation

Overview

Package cms reads, verifies and signs CMS SignedData (RFC 5652): the container a PDF signature, a UEFI authenticated variable and an S/MIME message carry. Sign produces one; see SignOptions.

Parse reads the structure; (*SignedData).Verify checks every signer's signature against the signed content and returns the certificate each one used. Whether that certificate should be TRUSTED — its chain, its validity period, its revocation — is a separate question that RFC 5652 §5.6 places "beyond the scope of this document", and so does this package: hand the returned certificates to crypto/x509's Verify, and to go-authn/revocation for CRLs.

⛔ DER ONLY, for now. RFC 5652 lets the outer structure be BER, and some producers write indefinite lengths; encoding/asn1 does not read them, and a structure that cannot be read is REFUSED with ErrMalformed rather than guessed at. The signed attributes themselves must be DER in every case (§5.3), so this limit never weakens what is verified — it only refuses some well-formed inputs that a BER-to-DER pass would accept.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMalformed: the bytes are not a SignedData this package can read.
	ErrMalformed = errors.New("cms: malformed")
	// ErrUnsupported: well-formed, but uses something this package does not
	// implement (an algorithm, SHA-1, a certificate it cannot find).
	ErrUnsupported = errors.New("cms: unsupported")
	// ErrInvalid: readable and supported, and the signature does not hold.
	ErrInvalid = errors.New("cms: signature invalid")
)

The errors every failure wraps, so a caller can tell "this is not a signature" from "this is a signature I cannot check" from "this signature is wrong" — three answers RFC 5652 §5.1 asks an implementation to keep apart ("MUST gracefully handle unimplemented signature algorithms").

View Source
var ErrOptions = errors.New("cms: invalid signing options")

ErrOptions: the signing request is not one this package will carry out — a missing key, a certificate that is not the key's, a combination the RFCs forbid. Algorithms it does not implement wrap ErrUnsupported instead, as they do when reading.

View Source
var ErrSigner = errors.New("cms: signer failed")

ErrSigner: the crypto.Signer failed, or returned a signature that does not verify under the signer's certificate (another key, ignored PSS options, an empty signature). The signer's own error stays in the chain, so errors.Is finds it as well.

Functions

func Sign added in v0.2.0

func Sign(content []byte, o SignOptions) ([]byte, error)

Sign returns a DER ContentInfo holding a SignedData with ONE signer.

⛔ What it will not emit: SHA-1 or any digest outside SHA-2 256/384/512; RSASSA-PSS parameters other than "this hash, MGF1 with it, salt of its length"; Ed25519 with another digest; a certificate whose key is not the signer's; a signature that omits the attributes yet claims another content type. Everything Sign writes is DER — signedAttrs in particular is a SET OF sorted by encoding (§5.4 signs those bytes, and the reader here is strict about them) — and every product is meant to pass this package's Verify and OpenSSL's `cms -verify`, which the tests assert.

Types

type Attribute

type Attribute struct {
	Type   asn1.ObjectIdentifier
	Values [][]byte
}

Attribute is one signed attribute: a type and its values, each value kept as its complete DER encoding.

type IssuerAndSerial

type IssuerAndSerial struct {
	RawIssuer []byte
	Serial    *big.Int
}

IssuerAndSerial identifies a certificate by its issuer's name, as encoded, and its serial number.

type SignOptions added in v0.2.0

type SignOptions struct {
	// Signer holds the private key: an *rsa.PrivateKey, an *ecdsa.PrivateKey
	// or an ed25519.PrivateKey, or any crypto.Signer whose Public key is one
	// of those types (a smart card, an HSM, a remote signer).
	Signer crypto.Signer
	// Certificate is the signer's certificate. It is embedded, and the
	// SignerInfo names it by issuer and serial number (RFC 5652 §5.3). Its
	// public key must be Signer's.
	Certificate *x509.Certificate
	// Chain is further certificates to embed (intermediates).
	Chain []*x509.Certificate

	// Hash is the digest: crypto.SHA256 (the default), SHA384 or SHA512.
	// Ed25519 signs with SHA-512 (RFC 8419 §3.1) and refuses any other.
	// SHA-1 is refused by name.
	Hash crypto.Hash
	// PSS selects RSASSA-PSS (MGF1 with Hash, salt as long as the hash)
	// instead of RSASSA-PKCS1-v1_5. RSA keys only.
	PSS bool
	// Rand is the entropy for RSA-PSS and ECDSA; crypto/rand when nil.
	Rand io.Reader

	// ContentType is the eContentType; id-data when nil.
	ContentType asn1.ObjectIdentifier
	// Detached leaves the content out of the container, as a PDF signature
	// does: the verifier is handed the signed bytes (Verify's argument).
	Detached bool

	// NoSignedAttrs signs the content itself, with no signedAttrs — the
	// PKCS#7 shape UEFI authenticated variables use. It needs id-data
	// (§5.3) and excludes SigningTime and SigningCertificateV2, which are
	// attributes.
	NoSignedAttrs bool
	// SigningTime, when not zero, adds the signing-time attribute (§11.3),
	// to the second. PAdES carries the time elsewhere and CAdES leaves it
	// optional, so it is opt-in.
	SigningTime time.Time
	// SigningCertificateV2 adds the signing-certificate-v2 attribute of
	// RFC 5035 §5.4.1, which ETSI CAdES / PAdES baseline signatures require:
	// the hash of the signer's certificate, and its issuer and serial.
	SigningCertificateV2 bool
}

SignOptions says what Sign emits. The zero value, apart from Signer and Certificate, is a SignedData over id-data with signed attributes (content-type and message-digest), SHA-256, the content ATTACHED.

type SignedData

type SignedData struct {
	Version          int
	DigestAlgorithms []pkix.AlgorithmIdentifier
	// ContentType is encapContentInfo's eContentType: id-data for a PDF
	// signature and for most others.
	ContentType asn1.ObjectIdentifier
	// Content is the encapsulated content, or nil when the signature is
	// DETACHED — as a PDF signature always is: the signed bytes are the
	// file's /ByteRange, and Verify takes them as its argument.
	Content []byte
	// Certificates are those the SignedData carries. Certificate choices
	// other than an X.509 certificate (attribute certificates, "other") are
	// skipped and counted in SkippedCertificates.
	Certificates        []*x509.Certificate
	SkippedCertificates int
	Signers             []Signer
}

SignedData is a parsed CMS SignedData.

func Parse

func Parse(der []byte) (*SignedData, error)

Parse reads a DER-encoded ContentInfo holding a SignedData.

func (*SignedData) Verify

func (sd *SignedData) Verify(detached []byte) ([]*x509.Certificate, error)

Verify checks every signer's signature and returns the certificate each signer used, in signer order.

detached is the signed content when the SignedData does not carry it — for a PDF signature, the concatenation of the file's /ByteRange. It must be nil when the content is attached: supplying content that the container also carries is refused rather than silently preferring one of the two.

⛔ EVERY signer must verify. RFC 5652 §5.1 lets an application treat one good signature from a given signer as enough when that signer signed several times; a caller that wants that can verify signers itself. A container with no signers at all is refused: it signs nothing.

The returned certificates are only those that SIGNED. Whether to trust them — chain, validity, revocation — is the caller's, per §5.6.

type Signer

type Signer struct {
	Version int
	// Exactly one of IssuerAndSerial and SubjectKeyID is set: RFC 5652 §5.3
	// requires a recipient to accept both forms of SignerIdentifier.
	IssuerAndSerial *IssuerAndSerial
	SubjectKeyID    []byte

	DigestAlgorithm pkix.AlgorithmIdentifier
	// SignedAttrs is nil when the signer signed the content directly.
	SignedAttrs        []Attribute
	SignatureAlgorithm pkix.AlgorithmIdentifier
	Signature          []byte
	// contains filtered or unexported fields
}

Signer is one SignerInfo.

Jump to

Keyboard shortcuts

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