Skip to content

std.crypto: Add secure DER parser #19775

Closed

Description

@clickingbuttons

The current DER parser lacks:

  • Checks to prevent out-of-bounds reads by verifying slice lengths are indeed inside its byte slice.
  • Checks to prevent hash collision attacks by verifying fields are in their shortest canonical form.
  • Checks to prevent hash collision attacks by verifying no bytes are unparsed.
  • OID parsing for auditing (see audit the standard library TLS implementation with respect to RFC 8446 #14178).
  • Tests.
  • An API to easily expect an element.

pub const der = struct {
pub const Class = enum(u2) {
universal,
application,
context_specific,
private,
};
pub const PC = enum(u1) {
primitive,
constructed,
};
pub const Identifier = packed struct(u8) {
tag: Tag,
pc: PC,
class: Class,
};
pub const Tag = enum(u5) {
boolean = 1,
integer = 2,
bitstring = 3,
octetstring = 4,
null = 5,
object_identifier = 6,
sequence = 16,
sequence_of = 17,
utc_time = 23,
generalized_time = 24,
_,
};
pub const Element = struct {
identifier: Identifier,
slice: Slice,
pub const Slice = struct {
start: u32,
end: u32,
pub const empty: Slice = .{ .start = 0, .end = 0 };
};
pub const ParseElementError = error{CertificateFieldHasInvalidLength};
pub fn parse(bytes: []const u8, index: u32) ParseElementError!Element {
var i = index;
const identifier = @as(Identifier, @bitCast(bytes[i]));
i += 1;
const size_byte = bytes[i];
i += 1;
if ((size_byte >> 7) == 0) {
return .{
.identifier = identifier,
.slice = .{
.start = i,
.end = i + size_byte,
},
};
}
const len_size = @as(u7, @truncate(size_byte));
if (len_size > @sizeOf(u32)) {
return error.CertificateFieldHasInvalidLength;
}
const end_i = i + len_size;
var long_form_size: u32 = 0;
while (i < end_i) : (i += 1) {
long_form_size = (long_form_size << 8) | bytes[i];
}
return .{
.identifier = identifier,
.slice = .{
.start = i,
.end = i + long_form_size,
},
};
}
};
};

Activity

  1. changed the title [-]Add secure DER parser[/-] [+]std.crypto: Add secure DER parser[/+] on Apr 27, 2024
  2. added 7 commits that reference this issue on May 15, 2024
    760d742
    df2bb8e
    6dbb679
    3b34d4c
    5ddb5be
    3c36279
    330d353
  3. added
    standard library
    on May 31, 2024
  4. added this to the 0.14.0 milestone on May 31, 2024
  5. modified the milestones: 0.14.0, 0.16.0 on Feb 9, 2025
  6. modified the milestones: 0.16.0, 0.14.0 on Feb 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    standard library

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions