1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const std = @import("std");
pub const Entry = struct {
frame: []const u8,
curve_type: u8,
pubkey: []const u8,
};
pub fn parse(allocator: std.mem.Allocator, bytes: []const u8) ![]Entry {
if (bytes.len < 4) return error.ShortCorpus;
const count = std.mem.readInt(u32, bytes[0..4], .big);
if (count > (bytes.len - 4) / 40) return error.ShortCorpus;
const entries = try allocator.alloc(Entry, count);
errdefer allocator.free(entries);
var at: usize = 4;
for (entries) |*entry| {
if (bytes.len - at < 4) return error.ShortCorpus;
const len = std.mem.readInt(u32, bytes[at..][0..4], .big);
at += 4;
if (len == 0) return error.EmptyFrame;
if (len > bytes.len - at) return error.ShortCorpus;
const frame = bytes[at..][0..len];
at += len;
if (bytes.len - at < 2) return error.ShortCorpus;
const curve = bytes[at];
const key_len = bytes[at + 1];
at += 2;
if (curve > 1 or key_len != 33) return error.InvalidCorpusKey;
if (key_len > bytes.len - at) return error.ShortCorpus;
entry.* = .{ .frame = frame, .curve_type = curve, .pubkey = bytes[at..][0..key_len] };
at += key_len;
}
if (at != bytes.len) return error.TrailingCorpus;
return entries;
}
const fixture: [44]u8 = blk: {
var bytes: [44]u8 = @splat(2);
@memcpy(bytes[0..11], &[_]u8{ 0, 0, 0, 1, 0, 0, 0, 1, 0xaa, 0, 33 });
break :blk bytes;
};
test "entries borrow original frame and signing key bytes" {
const entries = try parse(std.testing.allocator, &fixture);
defer std.testing.allocator.free(entries);
try std.testing.expectEqual(@as(usize, 1), entries.len);
try std.testing.expectEqualSlices(u8, &.{0xaa}, entries[0].frame);
try std.testing.expectEqual(@intFromPtr(&fixture[8]), @intFromPtr(entries[0].frame.ptr));
try std.testing.expectEqual(@intFromPtr(&fixture[11]), @intFromPtr(entries[0].pubkey.ptr));
}
test "every truncated prefix and trailing byte is rejected" {
for (0..fixture.len) |len| {
try std.testing.expectError(error.ShortCorpus, parse(std.testing.allocator, fixture[0..len]));
}
var trailing: [45]u8 = undefined;
@memcpy(trailing[0..44], &fixture);
trailing[44] = 0;
try std.testing.expectError(error.TrailingCorpus, parse(std.testing.allocator, &trailing));
}
test "unsupported curves and key widths are rejected" {
var bytes = fixture;
bytes[9] = 2;
try std.testing.expectError(error.InvalidCorpusKey, parse(std.testing.allocator, &bytes));
bytes = fixture;
bytes[10] = 32;
try std.testing.expectError(error.InvalidCorpusKey, parse(std.testing.allocator, &bytes));
}