Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The bytes a TSIG signature is computed over (RFC 8945 §4.3), written down.//!//! This library does no cryptography and this file does not change that. What//! a keyed hash covers is a question about *serialization* -- which fields, in//! which order, in which form -- and that is the one thing a message library//! is for. So everything here writes into an `Io.Writer` and stops: point that//! writer at an HMAC and you have a signer, point it at `Writer.fixed` and you//! have the digest input in your hand, which is the only way a signature bug//! is ever found.//!//! The caller supplies the secret, the clock and the hash. `rdata.Tsig` is the//! record itself, and `rdata.Tsig.ErrorCode` is what a receiver says went//! wrong.//!//! ### What gets hashed//!//! In order, with nothing between the fields and no padding://!//! 1. the MAC of the request, when there is one -- §4.3.1, and see below;//! 2. the message, as it was *before* its signature was added -- §4.3.2;//! 3. the TSIG variables -- §4.3.3: the key name, class, TTL, algorithm name,//! time signed, fudge, error and other data.//!//! ### The two things that are not the message you have//!//! **A signed message has to be unsigned again before it is hashed.** §4.3.2//! says a receiver digests the message "after the TSIG RR has been removed,//! the ARCOUNT decremented, and the message ID replaced by the original//! message ID from the TSIG if those IDs differ". None of that is what arrived//! on the wire, and all of it is recoverable without a copy: `writeMessage`//! writes twelve patched header bytes and then the body up to where the//! signature began.//!//! **A transfer's second and subsequent messages hash something smaller.**//! §5.3.1: the prior MAC, then every message since the last signature, then//! only the *timers* -- time signed and fudge -- rather than all the variables.//! `Scope` is that choice.
const std = @import("std");const Writer = std.Io.Writer;
const Header = @import("Header.zig");const Message = @import("Message.zig");const Name = @import("Name.zig");const Record = @import("Record.zig");const rdata = @import("rdata.zig");const types = @import("types.zig");
/// The class a TSIG record carries, which is not a class: RFC 8945 §4.2 spends/// the field on a constant.pub const class: types.Class = .any;/// Likewise the TTL, which is zero because nothing may cache a signature.pub const ttl: u32 = 0;
/// The name of each algorithm RFC 8945 §6 registers, as it appears in a key/// file, on a command line and in the record's algorithm field. The bytes are/// the whole of what is hashed of them, so they are here as text and a caller/// turns them into a `Name`.pub const algorithm_names = struct { pub const hmac_md5 = "hmac-md5.sig-alg.reg.int."; pub const hmac_sha1 = "hmac-sha1."; pub const hmac_sha224 = "hmac-sha224."; pub const hmac_sha256 = "hmac-sha256."; pub const hmac_sha384 = "hmac-sha384."; pub const hmac_sha512 = "hmac-sha512.";};
/// The fields of a TSIG that are hashed and are not the message (RFC 8945/// §4.3.3).////// `key` and `algorithm` are hashed in canonical form -- uncompressed and/// lowercased -- so that two peers who typed the same name in different cases/// compute the same digest. Everything else goes in as it is sent.pub const Variables = struct { /// The key's name, which is the TSIG record's owner name. key: Name, algorithm: Name, time_signed: u48, fudge: u16, /// `rdata.Tsig.ErrorCode`, as a number because this is serialization. error_code: u16 = 0, other: []const u8 = &.{},
/// The variables of a signature that is already on a message. pub fn of(key: Name, signature: rdata.Tsig) Variables { return .{ .key = key, .algorithm = signature.algorithm, .time_signed = signature.time_signed, .fudge = signature.fudge, .error_code = signature.error_code, .other = signature.other, }; }
test of { // Verifying: the variables are what arrived, apart from the key name, // which is the record's owner rather than part of its data. const signature: rdata.Tsig = .{ .algorithm = Name.literal(algorithm_names.hmac_sha256), .time_signed = 1_700_000_000, .fudge = 300, .mac = "\xde\xad\xbe\xef", .original_id = 0x1234, .error_code = 0, .other = &.{}, }; const variables: Variables = .of(Name.literal("key.example"), signature); try testing.expectFmt("key.example.", "{f}", .{variables.key}); try testing.expectEqual(@as(u48, 1_700_000_000), variables.time_signed); }};
/// How much of the variables a digest covers.pub const Scope = enum { /// All of them: a request, and the first message of an answer. full, /// The time signed and the fudge alone, which is what RFC 8945 §5.3.1 /// leaves in the digest of the second and later messages of a multi-message /// answer. The key and the algorithm are not repeated because the chain /// already covers them: this message's digest begins with the MAC of the /// one that did. timers,};
/// The MAC of the request: a two-byte length and then the bytes (RFC 8945/// §4.3.1).////// Written first, and only for a response -- it is what ties an answer to the/// question that was asked, and without it a signed answer to one query/// verifies just as well against another.pub fn writePriorMac(w: *Writer, mac: []const u8) Writer.Error!void { try w.writeInt(u16, @intCast(mac.len), .big); try w.writeAll(mac);}
test writePriorMac { var digest: [64]u8 = undefined; var w: Writer = .fixed(&digest); try writePriorMac(&w, "\xde\xad\xbe\xef"); try testing.expectEqualSlices(u8, "\x00\x04\xde\xad\xbe\xef", w.buffered());}
/// The message as it was before it was signed (RFC 8945 §4.3.2).////// `signature` is the TSIG record found in the message, or null for a message/// that carries none -- an unsigned envelope in the middle of a transfer,/// which §5.3.1 hashes whole and unaltered.////// With one, three things change and only three: ARCOUNT goes back down by/// one, the identifier goes back to the record's `original_id`, and the/// message ends where the record began. Nothing is written into the caller's/// buffer, which matters -- that buffer is usually the one the next message is/// about to be read into, and the record being unwritten is one the caller may/// still be holding.pub fn writeMessage(w: *Writer, message: Message, signature: ?Record) Writer.Error!void { const bytes = message.bytes; if (signature) |record| { var head: [Header.len]u8 = bytes[0..Header.len].*;
// The identifier a forwarder may have changed, put back. const original_id = originalId(record) orelse std.mem.readInt(u16, head[0..2], .big); std.mem.writeInt(u16, head[0..2], original_id, .big);
// And the count that was raised to make room for the signature. const additional = std.mem.readInt(u16, head[10..12], .big); std.mem.writeInt(u16, head[10..12], additional -| 1, .big);
try w.writeAll(&head); try w.writeAll(bytes[Header.len..record.start]); } else { try w.writeAll(bytes); }}
test writeMessage { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0x1234 }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .soa }); const unsigned_len = b.pos; try b.record(.additional, .{ .name = Name.literal("key.example"), .class = class, .ttl = ttl, .data = .{ .tsig = .{ .algorithm = Name.literal(algorithm_names.hmac_sha256), .time_signed = 1_700_000_000, .fudge = 300, .mac = "\xde\xad\xbe\xef", .original_id = 0x1234, .error_code = 0, .other = &.{}, } }, }); const message = try Message.parse(b.finish()); const found = (try find(message)).?;
var digest: [512]u8 = undefined; var w: Writer = .fixed(&digest); try writeMessage(&w, message, found.record); // The message as it was before it was signed: no TSIG, and an additional // count of zero again. try testing.expectEqual(@as(usize, unsigned_len), w.buffered().len); try testing.expectEqual(@as(u16, 0), (try Header.parse(w.buffered())).counts.additional);}
fn originalId(record: Record) ?u16 { const data = record.data() catch return null; return switch (data) { .tsig => |signature| signature.original_id, else => null, };}
/// The TSIG variables (RFC 8945 §4.3.3), or the two timers of them.pub fn writeVariables(w: *Writer, variables: Variables, scope: Scope) Writer.Error!void { switch (scope) { .full => { try variables.key.writeCanonical(w); try w.writeInt(u16, @backingInt(class), .big); try w.writeInt(u32, ttl, .big); try variables.algorithm.writeCanonical(w); try writeTimers(w, variables); try w.writeInt(u16, variables.error_code, .big); try w.writeInt(u16, @intCast(variables.other.len), .big); try w.writeAll(variables.other); }, .timers => try writeTimers(w, variables), }}
test writeVariables { const variables: Variables = .{ .key = Name.literal("KEY.Example"), .algorithm = Name.literal(algorithm_names.hmac_sha256), .time_signed = 1_700_000_000, .fudge = 300, }; var digest: [256]u8 = undefined;
// In full, the key name comes first and comes lowercased, then the class. var full: Writer = .fixed(&digest); try writeVariables(&full, variables, .full); try testing.expectStringStartsWith(full.buffered(), "\x03key\x07example\x00\x00\xff");
// The second and later messages of a transfer hash the two timers alone. var timers: Writer = .fixed(&digest); try writeVariables(&timers, variables, .timers); try testing.expectEqualSlices(u8, "\x00\x00\x65\x53\xf1\x00" ++ "\x01\x2c", timers.buffered());}
fn writeTimers(w: *Writer, variables: Variables) Writer.Error!void { try w.writeInt(u16, @intCast(variables.time_signed >> 32), .big); try w.writeInt(u32, @truncate(variables.time_signed), .big); try w.writeInt(u16, variables.fudge, .big);}
pub const FindError = error{ /// A TSIG record was found somewhere other than last in the additional /// section, which RFC 8945 §5.2 makes a format error: a signature that /// does not cover the end of the message covers nothing that matters. TsigNotLast, /// The TSIG record's class is not ANY or its TTL is not zero, which RFC /// 8945 §4.2 makes a MUST. `writeVariables` digests the two constants /// rather than the bytes that arrived, so a record carrying anything else /// would verify with six bytes no signature covers. TsigNotConstant,} || Message.OptError;
/// The signature on a message, if it has one.////// It must be the last record of the additional section -- that is where the/// bytes it covers stop, so a TSIG anywhere else is not a signature of this/// message but a record that looks like one. Its class and TTL must be the/// constants `class` and `ttl`, since those, not what arrived, are what is/// hashed.pub fn find(message: Message) FindError!?Found { var records = message.additional(); var last: ?Record = null; var seen_before_last = false; while (try records.next()) |record| { if (last) |previous| { if (previous.type == .tsig) seen_before_last = true; } last = record; }
const record = last orelse return null; if (seen_before_last) return error.TsigNotLast; if (record.type != .tsig) return null; if (record.class != class or record.ttl != ttl) return error.TsigNotConstant;
const data = record.data() catch return error.MalformedRdata; return .{ .record = record, .tsig = data.tsig };}
test find { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0x1234 }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .soa }); try b.record(.additional, .{ .name = Name.literal("key.example"), .class = class, .ttl = ttl, .data = .{ .tsig = .{ .algorithm = Name.literal(algorithm_names.hmac_sha256), .time_signed = 1_700_000_000, .fudge = 300, .mac = "\xde\xad\xbe\xef", .original_id = 0x1234, .error_code = 0, .other = &.{}, } }, }); const message = try Message.parse(b.finish());
const found = (try find(message)).?; try testing.expectFmt("key.example.", "{f}", .{found.record.name}); try testing.expectEqualSlices(u8, "\xde\xad\xbe\xef", found.tsig.mac);}
/// A signature and the record it was read from, which is what says where the/// signed part of the message ends.pub const Found = struct { record: Record, tsig: rdata.Tsig,};
const testing = std.testing;const Builder = @import("Builder.zig");
/// Builds a signed-looking message: a question, and a TSIG carrying `mac`.fn signedMessage(buffer: []u8, names: *Name.Buffer, mac: []const u8, original_id: u16) ![]u8 { var key_buffer: Name.Buffer = undefined; var algorithm_buffer: Name.Buffer = undefined;
var builder = try Builder.init(buffer, .{ .id = 0x1234 }, .{ .compression = false }); try builder.question(.{ .name = try .fromText(names, "example.com"), .type = .a }); try builder.record(.additional, .{ .name = try .fromText(&key_buffer, "key.example"), .class = class, .ttl = ttl, .data = .{ .tsig = .{ .algorithm = try .fromText(&algorithm_buffer, algorithm_names.hmac_sha256), .time_signed = 1_700_000_000, .fudge = 300, .mac = mac, .original_id = original_id, .error_code = 0, .other = &.{}, } }, }); return builder.finish();}
test "the signature is found only where it is allowed to be" { var buffer: [512]u8 = undefined; var names: Name.Buffer = undefined; const bytes = try signedMessage(&buffer, &names, "\xde\xad\xbe\xef", 0x1234);
const message = try Message.parse(bytes); const found = (try find(message)).?; try testing.expectEqual(types.Type.tsig, found.record.type); try testing.expectEqualSlices(u8, "\xde\xad\xbe\xef", found.tsig.mac); try testing.expectEqual(@as(u16, 300), found.tsig.fudge);
// A message with no additional section at all has no signature, and that // is not an error -- an unsigned envelope in the middle of a transfer is // the ordinary case. var plain: [512]u8 = undefined; var plain_names: Name.Buffer = undefined; var builder = try Builder.init(&plain, .{ .id = 1 }, .{}); try builder.question(.{ .name = try .fromText(&plain_names, "example.com"), .type = .a }); const unsigned = try Message.parse(builder.finish()); try testing.expectEqual(@as(?Found, null), try find(unsigned));}
test "a signature that is not the last record signs nothing" { // The bytes a TSIG covers end where it begins, so a record after it is one // the signature does not cover -- which is exactly how somebody would add // something to a signed message. var buffer: [512]u8 = undefined; var names: Name.Buffer = undefined; var key_buffer: Name.Buffer = undefined; var algorithm_buffer: Name.Buffer = undefined;
var builder = try Builder.init(&buffer, .{ .id = 0x1234 }, .{ .compression = false }); try builder.question(.{ .name = try .fromText(&names, "example.com"), .type = .a }); try builder.record(.additional, .{ .name = try .fromText(&key_buffer, "key.example"), .class = class, .ttl = ttl, .data = .{ .tsig = .{ .algorithm = try .fromText(&algorithm_buffer, algorithm_names.hmac_sha256), .time_signed = 1_700_000_000, .fudge = 300, .mac = "\x00", .original_id = 0x1234, .error_code = 0, .other = &.{}, } }, }); try builder.opt(.{});
const message = try Message.parse(builder.finish()); try testing.expectError(error.TsigNotLast, find(message));}
test "a signature whose class or TTL is not the constant is refused" { // The digest takes ANY and zero from the constants, so changing either on // the wire must not leave a message that still verifies. var buffer: [512]u8 = undefined; var names: Name.Buffer = undefined; const bytes = try signedMessage(&buffer, &names, "\xde\xad\xbe\xef", 0x1234); const found = (try find(try Message.parse(bytes))).?; // The class and the TTL come after the type, eight bytes before the data. const at = found.record.rdata_offset - 8;
var changed: [512]u8 = undefined; @memcpy(changed[0..bytes.len], bytes); changed[at + 1] = @intCast(@backingInt(types.Class.in)); try testing.expectError(error.TsigNotConstant, find(try Message.parse(changed[0..bytes.len])));
@memcpy(changed[0..bytes.len], bytes); changed[at + 5] = 1; try testing.expectError(error.TsigNotConstant, find(try Message.parse(changed[0..bytes.len])));}
test "the message a signature covers is the message without it" { var buffer: [512]u8 = undefined; var names: Name.Buffer = undefined; const bytes = try signedMessage(&buffer, &names, "\xde\xad\xbe\xef", 0x1234); const message = try Message.parse(bytes); const found = (try find(message)).?;
var digest: [512]u8 = undefined; var w: Writer = .fixed(&digest); try writeMessage(&w, message, found.record); const written = w.buffered();
// The header, with the additional count back at zero, and then everything // up to where the signature began -- so the question is there and the // record is not. try testing.expectEqual(@as(usize, found.record.start), written.len); try testing.expectEqual(@as(u16, 0), std.mem.readInt(u16, written[10..12], .big)); try testing.expectEqual(@as(u16, 0x1234), std.mem.readInt(u16, written[0..2], .big)); try testing.expectEqualSlices(u8, bytes[Header.len..found.record.start], written[Header.len..]);
// And the caller's buffer was not touched: the count in it is still one. try testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, bytes[10..12], .big));}
test "an identifier a forwarder changed is put back before it is hashed" { // RFC 8945 §4.3.2: the digest uses `original_id`, because that is what was // signed, and a forwarder is allowed to renumber the message afterwards. var buffer: [512]u8 = undefined; var names: Name.Buffer = undefined; const bytes = try signedMessage(&buffer, &names, "\xde\xad\xbe\xef", 0xabcd);
// Renumber it the way a forwarder would, after the fact. std.mem.writeInt(u16, buffer[0..2], 0x9999, .big);
const message = try Message.parse(bytes); const found = (try find(message)).?; var digest: [512]u8 = undefined; var w: Writer = .fixed(&digest); try writeMessage(&w, message, found.record); try testing.expectEqual(@as(u16, 0xabcd), std.mem.readInt(u16, w.buffered()[0..2], .big));}
test "an unsigned message is hashed exactly as it arrived" { var buffer: [512]u8 = undefined; var names: Name.Buffer = undefined; var builder = try Builder.init(&buffer, .{ .id = 7 }, .{}); try builder.question(.{ .name = try .fromText(&names, "example.com"), .type = .a }); const bytes = builder.finish();
const message = try Message.parse(bytes); var digest: [512]u8 = undefined; var w: Writer = .fixed(&digest); try writeMessage(&w, message, null); try testing.expectEqualSlices(u8, bytes, w.buffered());}
test "the variables, in full and in the two timers alone" { var key_buffer: Name.Buffer = undefined; var algorithm_buffer: Name.Buffer = undefined; const variables: Variables = .{ // Capitals on purpose: they are lowercased on the way into the digest, // and two peers who disagree about the case still agree about the MAC. .key = try .fromText(&key_buffer, "KEY.Example"), .algorithm = try .fromText(&algorithm_buffer, "HMAC-SHA256."), .time_signed = 0x0000_1234_5678, .fudge = 300, };
var digest: [256]u8 = undefined; var w: Writer = .fixed(&digest); try writeVariables(&w, variables, .full); try testing.expectEqualSlices( u8, "\x03key\x07example\x00" ++ // the key name, lowercased "\x00\xff" ++ // CLASS=ANY "\x00\x00\x00\x00" ++ // TTL=0 "\x0bhmac-sha256\x00" ++ // the algorithm, lowercased "\x00\x00\x12\x34\x56\x78" ++ // six bytes of time "\x01\x2c" ++ // the fudge "\x00\x00" ++ // no error "\x00\x00", // and nothing else w.buffered(), );
// The timers alone are the eight bytes in the middle, and nothing else: // no name, no class, no error. A digest that included the rest would // verify against a peer that did the same and against nothing else. var timers: [64]u8 = undefined; var t: Writer = .fixed(&timers); try writeVariables(&t, variables, .timers); try testing.expectEqualSlices(u8, "\x00\x00\x12\x34\x56\x78\x01\x2c", t.buffered());}
test "the prior MAC is a length and then the bytes" { var digest: [64]u8 = undefined; var w: Writer = .fixed(&digest); try writePriorMac(&w, "\x01\x02\x03"); try testing.expectEqualSlices(u8, "\x00\x03\x01\x02\x03", w.buffered());}
test "an error a receiver reports goes into the digest with its other data" { // A BADTIME carries the receiver's own clock in `other`, and both the code // and the clock are hashed -- so a complaint cannot be turned into a // different complaint on the way back. var key_buffer: Name.Buffer = undefined; var algorithm_buffer: Name.Buffer = undefined; const variables: Variables = .{ .key = try .fromText(&key_buffer, "k."), .algorithm = try .fromText(&algorithm_buffer, "hmac-sha256."), .time_signed = 1, .fudge = 300, .error_code = @backingInt(rdata.Tsig.ErrorCode.badtime), .other = "\x00\x00\x65\x00\x00\x00", };
var digest: [256]u8 = undefined; var w: Writer = .fixed(&digest); try writeVariables(&w, variables, .full); const written = w.buffered(); try testing.expectEqualSlices(u8, "\x00\x12\x00\x06\x00\x00\x65\x00\x00\x00", written[written.len - 10 ..]);}