Repository navigation
fix(pki): reject an otherName value that is not explicitly tagged - #9192
Conversation
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]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
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 Regular contributors should join the org to skip this step. Once the patch is verified, the new status will be reflected by the I understand the commands that are listed here. DetailsInstructions 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. |
wallrj
left a comment
There was a problem hiding this comment.
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
| 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") | ||
| } | ||
|
|
There was a problem hiding this comment.
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"):
- An empty wrapper passes.
asn1.RawValue{Tag: 0, Class: asn1.ClassContextSpecific, IsCompound: true}(orFullBytes: []byte{0xA0, 0x00}) gets through this check,MarshalSANsemitsA0 00, andUnmarshalSANsthen fails withasn1: structure error: explicit tag has no child(asn1.go#L785-L788). The test table's "no value at all" case catches the bare zeroRawValuebut not the empty wrapped one. - 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 ownmatchOtherNamesthen errors on it, so CSR matching fails on an extensionMarshalSANsblessed.
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.
|
|
||
| // Add support for the remaining SAN types. | ||
| for _, val := range gns.OtherNames { | ||
| if err := checkOtherNameValue(val.Value); err != nil { |
There was a problem hiding this comment.
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.
| // 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 |
There was a problem hiding this comment.
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]>
|
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: 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. So the value inside the wrapper is parsed explicitly too, read from Kept it to one well-formed element and nothing more, since The doc comment, US spelling and the Revert-checked: with the The PR is still |
|
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 I verified locally at 51a52f6: /ok-to-test with claude fable-5 |
|
[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 DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
…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]>
Pull Request Motivation
From the open follow-ups in #9155:
RFC 5280 section 4.2.1.6 defines the value of an
OtherNameasand
OtherName.Valuecarries the matchingasn1:"tag:0,explicit"struct tag.encoding/asn1honors that tag when reading aRawValue, but writes aRawValueout verbatim (makeFieldreturns early forrawValueType) — the tag is inert on the marshalling side. A value handed toMarshalSANswithout the wrapper was therefore emitted without it, and nothing anywhere reported a problem.The same is true of the
tag:NparameteraddMarshalablepasses toasn1.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:
MarshalSANsnow parses its own output back withUnmarshalSANsand requires everyGeneralNamechoice 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
x400Addresscarries the same hazard one loop down. Three cases the previous version emitted are now rejected:A0 00, either shape)UnmarshalSANsthen failed withexplicit tag has no childx400Addresswith no[3]tag whose own tag is a universal tag 0–8GeneralNamechoice — anINTEGERcomes back as adNSName, sinceUnmarshalSANsdispatches onv.TagUnmarshalSANs, then failed in cert-manager's ownmatchOtherNamesOne 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/asn1does not descend into aRawValueunder an explicit tag (asn1.go#L789-L792 — "The inner element should not be parsed for RawValues"), soA0 01 FFparses back happily. I checked this with a probe before relying on it:So the value inside the wrapper is parsed explicitly as well — reading it from
parsed.Value.Bytes, the same placematchOtherNamesreads it from, which is also what keeps a value supplied throughFullBytesfrom being falsely rejected.valueisANY DEFINED BY type-id, so this requires one well-formed element and nothing more; a non-UTF8Stringinner 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
addMarshalablerecording that itstagparameter does nothing for anasn1.RawValue, and the contract documented on the exportedOtherName.Valuefield itself so the next out-of-tree caller does not hit the same surprise.Everything in tree already supplies the tags —
CreateCertificateRequestbuildsasn1.RawValue{Tag: 0, Class: asn1.ClassContextSpecific, IsCompound: true, Bytes: value}explicitly, and thegenerateOtherNametest 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.MarshalSANshas exactly one non-test caller,csr.go:251.Tests
TestMarshalSANsRejectsValuesItCannotReadBackcovers 4 accepted shapes and 7 rejected ones;TestMarshalSANsRejectsUntaggedX400Addresscovers the mirrored[3]case, including the silent reclassification. For every accepted shape it asserts both thatUnmarshalSANscan read the result and that the value inside the wrapper parses — the two properties that were broken.checkSANsRoundTripcall 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 reachMarshalSANs.go vetandgofmtclean.Kind
/kind bug
Release Note
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.