Skip to content

fix(pki): reject an otherName value that is not explicitly tagged - #9192

Merged
cert-manager-prow[bot] merged 2 commits into
cert-manager:masterfrom
hamodywe:fix/othername-tag-v2
Aug 30, 2026
Merged

cert-manager-prow[bot] merged 2 commits into
cert-manager:masterfrom
hamodywe:fix/othername-tag-v2

Conversation

@hamodywe

@hamodywe hamodywe commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request Motivation

From the open follow-ups in #9155:

MarshalSANs accepts unwrapped otherName values and emits an extension that UnmarshalSANs then rejects (sans.go#L204)

RFC 5280 section 4.2.1.6 defines the value of an OtherName as

value [0] EXPLICIT ANY DEFINED BY type-id

and OtherName.Value carries the matching asn1:"tag:0,explicit" struct tag. encoding/asn1 honors that tag when reading a RawValue, but writes a RawValue out verbatim (makeField returns early for rawValueType) — the tag is inert on the marshalling side. A value handed to MarshalSANs without the wrapper was therefore emitted without it, and nothing anywhere reported a problem.

The same is true of the tag:N parameter addMarshalable passes to asn1.MarshalWithParams, which is why this is a class of bug rather than one instance.

The change

Rather than hand-roll a check per loop, check the finished extension against the parser: MarshalSANs now parses its own output back with UnmarshalSANs and requires every GeneralName choice to return in the same number it went in as. The marshaller and the parser agree by construction, for every choice at once and for any choice added later, instead of a mirror of the parser that can drift from it — which is the bug being fixed.

Reworked from the first version of this PR after @wallrj's review, which found two ways past the hand-rolled check and pointed out that x400Address carries the same hazard one loop down. Three cases the previous version emitted are now rejected:

input what used to happen
an empty wrapper (A0 00, either shape) passed the shape check; UnmarshalSANs then failed with explicit tag has no child
an x400Address with no [3] tag whose own tag is a universal tag 0–8 read back as a different GeneralName choice — an INTEGER comes back as a dNSName, since UnmarshalSANs dispatches on v.Tag
a correct wrapper holding bytes that are not one well-formed element survived marshal and UnmarshalSANs, then failed in cert-manager's own matchOtherNames

One correction to the review, and the reason the change is not purely the round-trip. The suggestion was that parse-back would reject both otherName cases for free. It rejects the empty wrapper, but not the third row: encoding/asn1 does not descend into a RawValue under an explicit tag (asn1.go#L789-L792 — "The inner element should not be parsed for RawValues"), so A0 01 FF parses back happily. I checked this with a probe before relying on it:

case                         parse-back only    parse-back + inner
control wrapped+valid        accept             accept
control FullBytes wrapped    accept             accept
unwrapped FullBytes          REJECT             REJECT
empty wrapper                REJECT             REJECT
garbage inside wrapper       accept             REJECT
two elements inside wrapper  accept             REJECT

So the value inside the wrapper is parsed explicitly as well — reading it from parsed.Value.Bytes, the same place matchOtherNames reads it from, which is also what keeps a value supplied through FullBytes from being falsely rejected. value is ANY DEFINED BY type-id, so this requires one well-formed element and nothing more; a non-UTF8String inner value is still accepted, and there is a test for that.

Also addressed from the review: the doc comment now says "returns an error" rather than "reports whether", US spelling throughout, a comment on addMarshalable recording that its tag parameter does nothing for an asn1.RawValue, and the contract documented on the exported OtherName.Value field itself so the next out-of-tree caller does not hit the same surprise.

Everything in tree already supplies the tags — CreateCertificateRequest builds asn1.RawValue{Tag: 0, Class: asn1.ClassContextSpecific, IsCompound: true, Bytes: value} explicitly, and the generateOtherName test helper does the same — so this asserts what the callers were already doing and moves the failure to the point where the mistake is made. MarshalSANs has exactly one non-test caller, csr.go:251.

Tests

TestMarshalSANsRejectsValuesItCannotReadBack covers 4 accepted shapes and 7 rejected ones; TestMarshalSANsRejectsUntaggedX400Address covers the mirrored [3] case, including the silent reclassification. For every accepted shape it asserts both that UnmarshalSANs can read the result and that the value inside the wrapper parses — the two properties that were broken.

  • Revert-checked: with the checkSANsRoundTrip call removed and the tests kept, exactly the 8 rejection cases fail and every accepted shape still passes.
  • ./pkg/util/..., ./internal/apis/certmanager/..., ./pkg/controller/certificates/... and ./pkg/apis/... are all green — that is the full set of packages that reach MarshalSANs.
  • go vet and gofmt clean.

Kind

/kind bug

Release Note

`MarshalSANs` now verifies that the SubjectAlternativeName extension it produces can be parsed back, and returns an error instead of emitting one that cannot. This rejects `otherName` and `x400Address` values supplied without the context-specific tag RFC 5280 requires, which previously produced an unreadable extension or, for `x400Address`, one that parsed back as a different name type.

AI disclosure: this change, and my replies on it, were prepared with the assistance of Claude Code. I review the change, the verification and each reply before it is posted, and I stand behind them as my own.

RFC 5280 defines an OtherName value as `[0] EXPLICIT ANY DEFINED BY
type-id`, and OtherName.Value carries the matching `tag:0,explicit`
struct tag. encoding/asn1 honours that tag when reading a RawValue but
writes a RawValue out verbatim, so a value handed to MarshalSANs without
the wrapper was emitted without it.

The result was a SubjectAlternativeName extension that does not follow
RFC 5280 and that UnmarshalSANs, in this same package, cannot read back.
Nothing reported an error along the way.

Everything in tree already supplies the wrapper - CreateCertificateRequest
builds it explicitly - so this checks the invariant the callers were
holding to anyway, and turns a silently malformed extension into an error
at the point the mistake is made.

Signed-off-by: hamodywe <[email protected]>
@cert-manager-prow cert-manager-prow Bot added kind/bug Categorizes issue or PR as related to a bug. release-note Denotes a PR that will be considered when it comes time to generate release notes. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. labels Aug 24, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cert-manager-prow cert-manager-prow Bot added the needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. label Aug 24, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

Hi @hamodywe. Thanks for your PR.

I'm waiting for a cert-manager member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work.

Regular contributors should join the org to skip this step.

Once the patch is verified, the new status will be reflected by the ok-to-test label.

I understand the commands that are listed here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@cert-manager-prow cert-manager-prow Bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Aug 24, 2026
@wallrj
wallrj requested a balanced review from Copilot August 24, 2026 17:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@wallrj wallrj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @hamodywe — the premise checks out. I verified against go1.25.5 that makeField returns early for rawValueType before any tag params are applied (marshal.go#L607-L619), so the tag:0,explicit struct tag really is dead on the marshalling side, and rejecting rather than auto-wrapping is the right call: an already-wrapped value is byte-indistinguishable from an inner ANY that happens to be context-[0]. Values parsed by UnmarshalSANs keep the [0] wrapper in FullBytes, so parse→re-marshal of well-formed certificates still passes the new check.

Two gaps in the check itself, confirmed by running probes against this branch — see the inline comments. Both (and the doc nit) would be closed at once by validating via parse-back through the same path UnmarshalSANs already uses.

One more suggestion that doesn't fit an inline comment: the contract this PR enforces at runtime isn't documented on the exported type. The asn1:"tag:0,explicit" tag on OtherName.Value reads as a promise that the marshaller applies the wrapper, but it's only honoured on unmarshal. A doc comment on the field ("must already carry the explicit [0] wrapper; encoding/asn1 writes a RawValue verbatim") would spare the next out-of-tree caller the same surprise.

with claude fable-5

Comment thread pkg/util/pki/sans.go Outdated
Comment on lines +219 to +230
return fmt.Errorf("x509: otherName value is not valid DER: %w", err)
}
if len(rest) != 0 {
return errors.New("x509: trailing data after otherName value")
}
}

// [0] EXPLICIT is a constructed, context-specific tag 0.
if raw.Class != asn1.ClassContextSpecific || raw.Tag != 0 || !raw.IsCompound {
return errors.New("x509: otherName value must be wrapped in an explicit [0] tag, as required by RFC 5280 section 4.2.1.6")
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This validates the wrapper's outer shape but not its contents, which leaves two ways to break the invariant the new test states ("whatever MarshalSANs accepts, UnmarshalSANs must be able to read"):

  1. An empty wrapper passes. asn1.RawValue{Tag: 0, Class: asn1.ClassContextSpecific, IsCompound: true} (or FullBytes: []byte{0xA0, 0x00}) gets through this check, MarshalSANs emits A0 00, and UnmarshalSANs then fails with asn1: structure error: explicit tag has no child (asn1.go#L785-L788). The test table's "no value at all" case catches the bare zero RawValue but not the empty wrapped one.
  2. Garbage inside a correct wrapper passes. Bytes: []byte{0xFF} survives marshal and even unmarshal (the parser skips the inner element for RawValue fields), but cert-manager's own matchOtherNames then errors on it, so CSR matching fails on an extension MarshalSANs blessed.

Both confirmed by running probe tests against this branch.

Rather than patching each case into this hand-rolled check, consider validating by parse-back through the same path UnmarshalSANs already uses: marshal the value and unmarshal it with asn1.UnmarshalWithParams(..., "tag:0") into an OtherName, requiring success and no trailing data. That's ~5 lines with a single source of truth — the two validators can't drift apart, which is the exact bug class this PR fixes — and it rejects both cases above for free. The trade-off is losing the bespoke RFC 5280 error message, which could be kept by wrapping the parse-back error.

Comment thread pkg/util/pki/sans.go Outdated

// Add support for the remaining SAN types.
for _, val := range gns.OtherNames {
if err := checkOtherNameValue(val.Value); err != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same hazard is left unguarded one loop down: X400Addresses hands addMarshalable a RawValue with tag:3, but the tag param is equally dead for a RawValue (same makeField early return). Confirmed by probe test against this branch: an unwrapped X400 value marshals without complaint and UnmarshalSANs then fails with bad SAN choice — and an inner universal tag 0–8 would be silently misparsed as a different SAN type, since UnmarshalSANs dispatches on v.Tag.

A mirrored check for context-specific tag 3 (or the parse-back approach suggested above, applied to both loops) would close the bug class rather than this one instance. At minimum, a comment on addMarshalable noting that its tag param is ignored for RawValue arguments would stop the next reader assuming it wraps.

Comment thread pkg/util/pki/sans.go Outdated
// checkOtherNameValue reports whether an OtherName value carries the explicit
// [0] tag that RFC 5280 section 4.2.1.6 requires of it:
//
// value [0] EXPLICIT ANY DEFINED BY type-id

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: "reports whether" is the Go idiom for boolean predicates, but this returns error. Suggest e.g. "checkOtherNameValue returns an error unless the OtherName value carries the explicit [0] tag that RFC 5280 section 4.2.1.6 requires."

Also, US spelling in code comments please — "honoured" → "honored" here, and "marshalled" → "marshaled" in the test failure message — matching the Go standard library's usage.

Reworked after review. The hand-rolled check validated the wrapper's outer
shape only, which left two ways past it, and it guarded otherName alone while
x400Address carries the same hazard.

Check the finished extension by parsing it back with UnmarshalSANs and
requiring each GeneralName choice to return in the same number it went in as.
The marshaller and the parser then agree by construction, for every choice at
once and for any choice added later, instead of a per-loop check that can drift
from the parser it mirrors - which is the class of bug being fixed.

This closes three cases the previous version emitted:

  - an empty wrapper: A0 00 passed the shape check, and UnmarshalSANs then
    failed on the result with "explicit tag has no child";
  - an x400Address with no [3] tag whose own tag is one of the universal tags
    0-8: UnmarshalSANs dispatches on that tag, so it came back as a different
    GeneralName choice entirely - an INTEGER is read back as a dNSName;
  - a correct wrapper holding bytes that are not one well-formed element:
    encoding/asn1 does not descend into a RawValue under an explicit tag, so
    this survives both marshalling and UnmarshalSANs, and fails later in
    matchOtherNames. The round-trip alone does not catch it, so the value
    inside the wrapper is parsed explicitly, where matchOtherNames reads it.

Also documents the contract on OtherName.Value and notes on addMarshalable
that its tag parameter does nothing for an asn1.RawValue.

Signed-off-by: hamodywe <[email protected]>

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: hamodywe <[email protected]>
@hamodywe

Copy link
Copy Markdown
Contributor Author

Thanks @wallrj — this was a much better shape, and both gaps reproduced exactly as you described.

Reworked to check the finished extension against the parser rather than mirroring it: MarshalSANs now parses its own output back with UnmarshalSANs and requires each GeneralName choice to return in the same number it went in as. That covers the x400Address case in the same stroke, and it turned out to be worse than unreadable — an untagged value whose own tag is a universal 0–8 comes back as a different choice entirely, so an INTEGER is read as a dNSName. There's a test for that specifically.

One correction, and it's the reason the change isn't purely the round-trip: parse-back rejects the empty wrapper, but not garbage inside a correct one. encoding/asn1 doesn't descend into a RawValue under an explicit tag (asn1.go#L789-L792 — "The inner element should not be parsed for RawValues"), so A0 01 FF parses back happily and only fails later in matchOtherNames. I probed both candidates before relying on either:

case                         parse-back only    parse-back + inner
control wrapped+valid        accept             accept
control FullBytes wrapped    accept             accept
unwrapped FullBytes          REJECT             REJECT
empty wrapper                REJECT             REJECT
garbage inside wrapper       accept             REJECT
two elements inside wrapper  accept             REJECT

So the value inside the wrapper is parsed explicitly too, read from parsed.Value.Bytes — where matchOtherNames reads it, and also what keeps a value supplied through FullBytes from being falsely rejected (reading .Bytes off the input instead was a bug in my first attempt at this).

Kept it to one well-formed element and nothing more, since value is ANY DEFINED BY type-id — a non-UTF8String inner value is still accepted, and there's a test for that.

The doc comment, US spelling and the addMarshalable note are all in. I also documented the contract on OtherName.Value itself, as you suggested.

Revert-checked: with the checkSANsRoundTrip call removed and the tests kept, exactly the 8 rejection cases fail and every accepted shape still passes. ./pkg/util/..., ./internal/apis/certmanager/..., ./pkg/controller/certificates/... and ./pkg/apis/... are all green — the full set of packages that reach MarshalSANs.

The PR is still needs-ok-to-test, so none of that has run in CI yet.

@wallrj

wallrj commented Aug 30, 2026

Copy link
Copy Markdown
Member

Thanks @hamodywe — this is a better fix than the one I sketched. You were right to correct me: parse-back alone does not catch garbage inside a well-formed wrapper, since encoding/asn1 doesn't descend into a RawValue under an explicit tag, and your explicit inner-element check (reading from the parsed value, where matchOtherNames reads it) closes that properly. Generalising the check to a per-choice count comparison covers x400Address and any future choice in one stroke, and the universal-tag-2-read-back-as-dNSName test is a great illustration of why the count comparison is needed, not just parse success.

I verified locally at 51a52f6: go test ./pkg/util/pki/... passes, and with the checkSANsRoundTrip call reverted, exactly the 8 rejection cases fail while every accepted shape still passes.

/ok-to-test
/approve
/lgtm
/label tide/merge-method-squash

with claude fable-5

@cert-manager-prow cert-manager-prow Bot added ok-to-test tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges. lgtm Indicates that a PR is ready to be merged. and removed needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. labels Aug 30, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wallrj

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@cert-manager-prow cert-manager-prow Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Aug 30, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit 45c8f3c into cert-manager:master Aug 30, 2026
6 checks passed
hjoshi123 pushed a commit to hjoshi123/cert-manager that referenced this pull request Aug 31, 2026
…rt-manager#9192)

* fix(pki): reject an otherName value that is not explicitly tagged

RFC 5280 defines an OtherName value as `[0] EXPLICIT ANY DEFINED BY
type-id`, and OtherName.Value carries the matching `tag:0,explicit`
struct tag. encoding/asn1 honours that tag when reading a RawValue but
writes a RawValue out verbatim, so a value handed to MarshalSANs without
the wrapper was emitted without it.

The result was a SubjectAlternativeName extension that does not follow
RFC 5280 and that UnmarshalSANs, in this same package, cannot read back.
Nothing reported an error along the way.

Everything in tree already supplies the wrapper - CreateCertificateRequest
builds it explicitly - so this checks the invariant the callers were
holding to anyway, and turns a silently malformed extension into an error
at the point the mistake is made.

Signed-off-by: hamodywe <[email protected]>

* fix(pki): check the marshaled SANs against the parser, not by hand

Reworked after review. The hand-rolled check validated the wrapper's outer
shape only, which left two ways past it, and it guarded otherName alone while
x400Address carries the same hazard.

Check the finished extension by parsing it back with UnmarshalSANs and
requiring each GeneralName choice to return in the same number it went in as.
The marshaller and the parser then agree by construction, for every choice at
once and for any choice added later, instead of a per-loop check that can drift
from the parser it mirrors - which is the class of bug being fixed.

This closes three cases the previous version emitted:

  - an empty wrapper: A0 00 passed the shape check, and UnmarshalSANs then
    failed on the result with "explicit tag has no child";
  - an x400Address with no [3] tag whose own tag is one of the universal tags
    0-8: UnmarshalSANs dispatches on that tag, so it came back as a different
    GeneralName choice entirely - an INTEGER is read back as a dNSName;
  - a correct wrapper holding bytes that are not one well-formed element:
    encoding/asn1 does not descend into a RawValue under an explicit tag, so
    this survives both marshalling and UnmarshalSANs, and fails later in
    matchOtherNames. The round-trip alone does not catch it, so the value
    inside the wrapper is parsed explicitly, where matchOtherNames reads it.

Also documents the contract on OtherName.Value and notes on addMarshalable
that its tag parameter does nothing for an asn1.RawValue.

Signed-off-by: hamodywe <[email protected]>

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: hamodywe <[email protected]>

---------

Signed-off-by: hamodywe <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@wallrj wallrj mentioned this pull request Sep 1, 2026
39 of 41 tasks
@wallrj wallrj mentioned this pull request Nov 4, 2026
2 of 40 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. kind/bug Categorizes issue or PR as related to a bug. lgtm Indicates that a PR is ready to be merged. ok-to-test release-note Denotes a PR that will be considered when it comes time to generate release notes. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants