Skip to content

Reject non-canonical base64 in PEM bodies - #137

Open
deadcaf3 wants to merge 1 commit into
apple:mainfrom
deadcaf3:fix/strict-pem-base64
Open

deadcaf3 wants to merge 1 commit into
apple:mainfrom
deadcaf3:fix/strict-pem-base64

Conversation

@deadcaf3

Copy link
Copy Markdown

Motivation:

PEM bodies are decoded with Data(base64Encoded:), which accepts non-canonical input: "QUJ=" decodes to the same bytes as "QUI=", and "QUJD====" decodes the same as "QUJD". Several distinct PEM strings therefore map to one DER blob. RFC 4648 section 3.5 allows rejecting such input, and PEM carries signed material, so we should.

Modifications:

Validate the body before decoding it: the length must be a multiple of four, padding may only appear at the end and at most twice, and the bits beyond the last encoded byte must be zero. Add a test with canonical and non-canonical encodings of the same bytes.

Result:

Only canonical base64 is accepted in PEM bodies. The new test fails before this patch and passes after it.

Motivation:

Data(base64Encoded:) accepts excess padding and non-zero trailing
bits, so several distinct PEM strings decode to the same DER bytes.
RFC 4648 section 3.5 allows rejecting such input, and PEM carries
signed material, so we should.

Modifications:

Validate the body before decoding: length a multiple of four, padding
only at the end and at most twice, trailing bits zero. Add a test
covering canonical and non-canonical encodings of the same bytes.

Result:

Only canonical base64 is accepted in PEM bodies.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant