~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
400 lines · 14.4 KB Raw History
//! Network safety checks for identity resolution.

const std = @import("std");
const HttpTransport = @import("zttp").Client;

pub const NetworkSafetyError = error{
    MissingHost,
    UnsafeIdentityHost,
    IdentityDnsResolutionFailed,
};

const max_dns_response_size = 1 * 1024 * 1024;

pub const CheckedIdentityUrl = struct {
    host: []u8,
    dial_host: ?[]u8,

    pub fn deinit(self: *CheckedIdentityUrl, allocator: std.mem.Allocator) void {
        allocator.free(self.host);
        if (self.dial_host) |dial_host| allocator.free(dial_host);
    }

    pub fn resolvedConnection(self: CheckedIdentityUrl) ?HttpTransport.ResolvedConnection {
        return .{
            .dial_host = self.dial_host orelse return null,
            .logical_host = self.host,
        };
    }
};

pub fn checkIdentityUrl(url: []const u8) (std.Uri.ParseError || NetworkSafetyError)!void {
    const uri = try std.Uri.parse(url);
    var host_buf: [std.Io.net.HostName.max_len]u8 = undefined;
    const host_name = std.Io.net.HostName.fromUri(uri, &host_buf) catch return error.MissingHost;
    try checkIdentityHost(host_name.bytes);
}

pub fn checkIdentityUrlResolved(
    allocator: std.mem.Allocator,
    transport: *HttpTransport,
    doh_endpoint: []const u8,
    url: []const u8,
) (std.Uri.ParseError || NetworkSafetyError || error{ OutOfMemory, ResponseTooLarge })!void {
    var checked = try resolveIdentityUrl(allocator, transport, doh_endpoint, url);
    checked.deinit(allocator);
}

pub fn resolveIdentityUrl(
    allocator: std.mem.Allocator,
    transport: *HttpTransport,
    doh_endpoint: []const u8,
    url: []const u8,
) (std.Uri.ParseError || NetworkSafetyError || error{ OutOfMemory, ResponseTooLarge })!CheckedIdentityUrl {
    const host = try hostFromUrlAlloc(allocator, url);
    errdefer allocator.free(host);
    try checkIdentityHost(host);

    // Literal IPs were fully checked above. Only DNS names need DoH preflight.
    if (isIpLiteral(host)) {
        return .{ .host = host, .dial_host = null };
    }

    var saw_address = false;
    const dial_host = try checkDnsAnswers(allocator, transport, doh_endpoint, host, "A", &saw_address);
    errdefer if (dial_host) |addr| allocator.free(addr);
    const maybe_ip6 = try checkDnsAnswers(allocator, transport, doh_endpoint, host, "AAAA", &saw_address);
    if (maybe_ip6) |ip6| allocator.free(ip6);
    if (!saw_address) return error.IdentityDnsResolutionFailed;
    if (dial_host == null) return error.IdentityDnsResolutionFailed;

    return .{ .host = host, .dial_host = dial_host };
}

fn hostFromUrlAlloc(
    allocator: std.mem.Allocator,
    url: []const u8,
) (std.Uri.ParseError || NetworkSafetyError || error{OutOfMemory})![]u8 {
    const uri = try std.Uri.parse(url);
    var host_buf: [std.Io.net.HostName.max_len]u8 = undefined;
    const host_name = std.Io.net.HostName.fromUri(uri, &host_buf) catch return error.MissingHost;
    return try allocator.dupe(u8, host_name.bytes);
}

pub fn checkIdentityHost(host: []const u8) NetworkSafetyError!void {
    if (host.len == 0) return error.MissingHost;

    const host_without_trailing_dot = stripTrailingDot(host);
    if (std.ascii.eqlIgnoreCase(host_without_trailing_dot, "localhost")) {
        return error.UnsafeIdentityHost;
    }

    if (std.Io.net.Ip4Address.parse(host, 0)) |ip4| {
        if (isNonRoutableIp4(ip4.bytes)) return error.UnsafeIdentityHost;
        return;
    } else |_| {}

    const ip6_text = stripIp6Brackets(host);
    if (std.Io.net.Ip6Address.parse(ip6_text, 0)) |ip6| {
        if (ip4FromIp6Mapped(ip6.bytes)) |ip4| {
            if (isNonRoutableIp4(ip4)) return error.UnsafeIdentityHost;
        }
        if (isNonRoutableIp6(ip6.bytes)) return error.UnsafeIdentityHost;
        return;
    } else |_| {}
}

fn isIpLiteral(host: []const u8) bool {
    if (std.Io.net.Ip4Address.parse(host, 0)) |_| return true else |_| {}

    const ip6_text = stripIp6Brackets(host);
    if (std.Io.net.Ip6Address.parse(ip6_text, 0)) |_| return true else |_| {}

    return false;
}

fn checkDnsAnswers(
    allocator: std.mem.Allocator,
    transport: *HttpTransport,
    doh_endpoint: []const u8,
    host: []const u8,
    record_type: []const u8,
    saw_address: *bool,
) (NetworkSafetyError || error{ OutOfMemory, ResponseTooLarge })!?[]u8 {
    const url = try std.fmt.allocPrint(
        allocator,
        "{s}?name={s}&type={s}",
        .{ doh_endpoint, host, record_type },
    );
    defer allocator.free(url);

    const result = transport.fetch(.{
        .url = url,
        .accept = "application/dns-json",
        .max_response_size = max_dns_response_size,
        .on_redirect = .refuse,
    }) catch |err| switch (err) {
        error.OutOfMemory => |e| return e,
        error.ResponseTooLarge => |e| return e,
        else => return error.IdentityDnsResolutionFailed,
    };
    defer allocator.free(result.body);

    if (result.status != .ok) return error.IdentityDnsResolutionFailed;

    const parsed = parseDnsResponse(allocator, result.body) catch
        return error.IdentityDnsResolutionFailed;
    defer parsed.deinit();

    return checkAnswers(allocator, parsed.value.Answer orelse return null, saw_address);
}

fn checkAnswers(
    allocator: std.mem.Allocator,
    answers: []const Answer,
    saw_address: *bool,
) (NetworkSafetyError || error{OutOfMemory})!?[]u8 {
    var first_ip4: ?[]u8 = null;
    errdefer if (first_ip4) |ip| allocator.free(ip);

    for (answers) |answer| {
        const data = answer.data orelse continue;
        switch (answer.type) {
            1 => {
                saw_address.* = true;
                _ = std.Io.net.Ip4Address.parse(data, 0) catch return error.IdentityDnsResolutionFailed;
                try checkIdentityHost(data);
                if (first_ip4 == null) first_ip4 = try allocator.dupe(u8, data);
            },
            28 => {
                saw_address.* = true;
                _ = std.Io.net.Ip6Address.parse(data, 0) catch return error.IdentityDnsResolutionFailed;
                try checkIdentityHost(data);
            },
            else => {},
        }
    }
    return first_ip4;
}

fn stripIp6Brackets(host: []const u8) []const u8 {
    if (host.len >= 2 and host[0] == '[' and host[host.len - 1] == ']') {
        return host[1 .. host.len - 1];
    }
    return host;
}

fn stripTrailingDot(host: []const u8) []const u8 {
    if (host.len > 0 and host[host.len - 1] == '.') return host[0 .. host.len - 1];
    return host;
}

fn isNonRoutableIp4(ip: [4]u8) bool {
    const blocked = [_]Ip4Range{
        .{ .network = .{ 0, 0, 0, 0 }, .prefix = 8 },
        .{ .network = .{ 10, 0, 0, 0 }, .prefix = 8 },
        .{ .network = .{ 100, 64, 0, 0 }, .prefix = 10 },
        .{ .network = .{ 127, 0, 0, 0 }, .prefix = 8 },
        .{ .network = .{ 169, 254, 0, 0 }, .prefix = 16 },
        .{ .network = .{ 172, 16, 0, 0 }, .prefix = 12 },
        .{ .network = .{ 192, 0, 0, 0 }, .prefix = 24 },
        .{ .network = .{ 192, 0, 2, 0 }, .prefix = 24 },
        .{ .network = .{ 192, 88, 99, 0 }, .prefix = 24 },
        .{ .network = .{ 192, 168, 0, 0 }, .prefix = 16 },
        .{ .network = .{ 198, 18, 0, 0 }, .prefix = 15 },
        .{ .network = .{ 198, 51, 100, 0 }, .prefix = 24 },
        .{ .network = .{ 203, 0, 113, 0 }, .prefix = 24 },
        .{ .network = .{ 224, 0, 0, 0 }, .prefix = 4 },
        .{ .network = .{ 240, 0, 0, 0 }, .prefix = 4 },
    };
    for (blocked) |range| if (range.contains(ip)) return true;
    return false;
}

const Ip4Range = struct {
    network: [4]u8,
    prefix: u5,

    fn contains(self: Ip4Range, address: [4]u8) bool {
        const network = std.mem.readInt(u32, &self.network, .big);
        const candidate = std.mem.readInt(u32, &address, .big);
        const shift: u5 = @intCast(32 - @as(u6, self.prefix));
        const mask = if (self.prefix == 0) @as(u32, 0) else ~@as(u32, 0) << shift;
        return network & mask == candidate & mask;
    }
};

fn isNonRoutableIp6(ip: [16]u8) bool {
    // IPv4-mapped values inherit the complete IPv4 policy.
    if (ip4FromIp6Mapped(ip)) |ip4| return isNonRoutableIp4(ip4);

    // Identity fetches need globally routed unicast. Exclude the IETF
    // special-purpose block, documentation space, and 6to4 even though they
    // sit inside the broad 2000::/3 global-unicast allocation.
    if (ip[0] & 0xe0 != 0x20) return true;
    if (matchesIp6(ip, .{ 0x20, 0x01 } ++ @as([14]u8, @splat(0)), 23)) return true;
    if (matchesIp6(ip, .{ 0x20, 0x01, 0x0d, 0xb8 } ++ @as([12]u8, @splat(0)), 32)) return true;
    if (matchesIp6(ip, .{ 0x3f, 0xff } ++ @as([14]u8, @splat(0)), 20)) return true;
    if (matchesIp6(ip, .{ 0x20, 0x02 } ++ @as([14]u8, @splat(0)), 16)) return true;
    return false;
}

fn matchesIp6(address: [16]u8, network: [16]u8, prefix: u8) bool {
    const whole_bytes = prefix / 8;
    const remaining = prefix % 8;
    if (!std.mem.eql(u8, address[0..whole_bytes], network[0..whole_bytes])) return false;
    if (remaining == 0) return true;
    const mask: u8 = @as(u8, 0xff) << @intCast(8 - remaining);
    return address[whole_bytes] & mask == network[whole_bytes] & mask;
}

fn ip4FromIp6Mapped(ip: [16]u8) ?[4]u8 {
    for (ip[0..10]) |b| {
        if (b != 0) return null;
    }
    if (ip[10] != 0xff or ip[11] != 0xff) return null;
    return ip[12..16].*;
}

/// Cloudflare DoH includes undeclared fields like `Authority` (empty-answer
/// responses) and `Comment` (DNSSEC zones), so the parse must tolerate them.
fn parseDnsResponse(
    allocator: std.mem.Allocator,
    body: []const u8,
) std.json.ParseError(std.json.Scanner)!std.json.Parsed(DnsResponse) {
    return std.json.parseFromSlice(
        DnsResponse,
        allocator,
        body,
        .{ .ignore_unknown_fields = true },
    );
}

const DnsResponse = struct {
    Status: i32,
    TC: bool = false,
    RD: bool = false,
    RA: bool = false,
    AD: bool = false,
    CD: bool = false,
    Question: ?[]Question = null,
    Answer: ?[]Answer = null,
};

const Question = struct {
    name: []const u8,
    type: i32,
};

const Answer = struct {
    name: []const u8,
    type: i32,
    TTL: i32,
    data: ?[]const u8 = null,
};

test "identity host rejects obvious non-routable hosts" {
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("localhost"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("localhost."));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("127.0.0.1"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("10.1.2.3"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("172.16.0.1"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("192.168.1.1"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("169.254.1.1"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("[::1]"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("::ffff:127.0.0.1"));
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityHost("fc00::1"));
    try checkIdentityHost("example.com");
    try checkIdentityHost("8.8.8.8");
}

test "identity host rejects every special-purpose destination class" {
    for ([_][]const u8{
        "0.0.0.1",
        "100.100.100.200",
        "192.0.0.1",
        "192.0.2.1",
        "192.88.99.1",
        "198.18.0.1",
        "198.51.100.1",
        "203.0.113.1",
        "224.0.0.1",
        "255.255.255.255",
        "2001::1",
        "2001:db8::1",
        "3fff::1",
        "3fff:fff::1",
        "2002:7f00:1::",
        "::ffff:100.100.100.200",
    }) |host| try std.testing.expectError(
        error.UnsafeIdentityHost,
        checkIdentityHost(host),
    );
    try checkIdentityHost("1.1.1.1");
    try checkIdentityHost("2606:4700:4700::1111");
    try checkIdentityHost("3fff:1000::1");
}

test "identity url check rejects literal localhost" {
    try std.testing.expectError(error.UnsafeIdentityHost, checkIdentityUrl("https://127.0.0.1/.well-known/did.json"));
}

test "identity dns answers reject non-routable addresses" {
    const json =
        \\{
        \\  "Status": 0,
        \\  "Answer": [
        \\    {"name": "evil.example.", "type": 1, "TTL": 60, "data": "127.0.0.1"}
        \\  ]
        \\}
    ;

    const parsed = try parseDnsResponse(std.testing.allocator, json);
    defer parsed.deinit();

    var saw_address = false;
    try std.testing.expectError(error.UnsafeIdentityHost, checkAnswers(std.testing.allocator, parsed.value.Answer.?, &saw_address));
    try std.testing.expect(saw_address);
}

test "dns address answers must be literals of their record type" {
    const Case = struct { record: i32, data: []const u8 };
    for ([_]Case{
        .{ .record = 1, .data = "localhost.localdomain" },
        .{ .record = 1, .data = "internal.example" },
        .{ .record = 1, .data = "2606:4700::1111" },
        .{ .record = 28, .data = "internal.example" },
        .{ .record = 28, .data = "34.1.2.3" },
    }) |case| {
        const answers = [_]Answer{.{ .name = "evil.example.", .type = case.record, .TTL = 60, .data = case.data }};
        var saw_address = false;
        try std.testing.expectError(error.IdentityDnsResolutionFailed, checkAnswers(std.testing.allocator, &answers, &saw_address));
    }

    const answers = [_]Answer{
        .{ .name = "ok.example.", .type = 5, .TTL = 60, .data = "alias.example." },
        .{ .name = "ok.example.", .type = 1, .TTL = 60, .data = "34.1.2.3" },
    };
    var saw_address = false;
    const dial = (try checkAnswers(std.testing.allocator, &answers, &saw_address)).?;
    defer std.testing.allocator.free(dial);
    try std.testing.expectEqualStrings("34.1.2.3", dial);
}

test "dns response parse tolerates Cloudflare Authority and Comment fields" {
    // real Cloudflare DoH body for an AAAA query with no answer: includes an
    // `Authority` field that `DnsResponse` doesn't declare (regression for
    // strict parse breaking well-known resolution of IPv4-only hosts).
    const json =
        \\{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,
        \\ "Question":[{"name":"tarzandra.selfhosted.social","type":28}],
        \\ "Authority":[{"name":"selfhosted.social","type":6,"TTL":1800,
        \\   "data":"drew.ns.cloudflare.com. dns.cloudflare.com. 2409940511 10000 2400 604800 1800"}],
        \\ "Comment":["EDE(10): RRSIGs Missing for DNSKEY at., id = 1253"]}
    ;

    const parsed = try parseDnsResponse(std.testing.allocator, json);
    defer parsed.deinit();

    try std.testing.expect(parsed.value.Answer == null);
}