445 lines
15 KiB
Zig
445 lines
15 KiB
Zig
//! NAT-PMP (NAT Port Mapping Protocol) Implementation
|
|
//!
|
|
//! RFC 6886 - A simple protocol for requesting port mappings from NAT gateways.
|
|
//! Much simpler than UPnP IGD (2-packet UDP exchange vs 42 packets).
|
|
//!
|
|
//! Usage:
|
|
//! ```zig
|
|
//! var nat = try NatPmp.init(allocator);
|
|
//! defer nat.deinit();
|
|
//!
|
|
//! // Discover external address
|
|
//! const external_ip = try nat.getExternalAddress();
|
|
//!
|
|
//! // Request a UDP port mapping
|
|
//! const mapping = try nat.mapPort(.udp, 18000, 18000, 3600);
|
|
//! // Now external_ip:mapping.external_port maps to our internal port
|
|
//! ```
|
|
|
|
const std = @import("std");
|
|
const builtin = @import("builtin");
|
|
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
|
|
const posix = std.posix;
|
|
const Allocator = std.mem.Allocator;
|
|
|
|
/// NAT-PMP protocol port (gateway listens here)
|
|
const NAT_PMP_PORT: u16 = 5351;
|
|
|
|
/// NAT-PMP protocol version
|
|
const VERSION: u8 = 0;
|
|
|
|
/// Opcodes
|
|
const Opcode = enum(u8) {
|
|
external_address = 0,
|
|
map_udp = 1,
|
|
map_tcp = 2,
|
|
};
|
|
|
|
/// Result codes
|
|
pub const ResultCode = enum(u16) {
|
|
success = 0,
|
|
unsupported_version = 1,
|
|
not_authorized = 2,
|
|
network_failure = 3,
|
|
out_of_resources = 4,
|
|
unsupported_opcode = 5,
|
|
_,
|
|
|
|
pub fn isSuccess(self: ResultCode) bool {
|
|
return self == .success;
|
|
}
|
|
|
|
pub fn toString(self: ResultCode) []const u8 {
|
|
return switch (self) {
|
|
.success => "Success",
|
|
.unsupported_version => "Unsupported Version",
|
|
.not_authorized => "Not Authorized/Refused",
|
|
.network_failure => "Network Failure",
|
|
.out_of_resources => "Out of Resources",
|
|
.unsupported_opcode => "Unsupported Opcode",
|
|
_ => "Unknown Error",
|
|
};
|
|
}
|
|
};
|
|
|
|
/// Protocol type for port mapping
|
|
pub const Protocol = enum(u8) {
|
|
udp = 1,
|
|
tcp = 2,
|
|
};
|
|
|
|
/// Port mapping result
|
|
pub const PortMapping = struct {
|
|
internal_port: u16,
|
|
external_port: u16,
|
|
lifetime_seconds: u32,
|
|
external_ip: [4]u8,
|
|
};
|
|
|
|
/// NAT-PMP client
|
|
pub const NatPmp = struct {
|
|
allocator: Allocator,
|
|
gateway_ip: [4]u8,
|
|
socket: ?posix.socket_t,
|
|
/// Seconds since epoch from gateway (for detecting reboots)
|
|
gateway_epoch: u32,
|
|
|
|
pub fn init(allocator: Allocator) !NatPmp {
|
|
const gateway = try discoverGateway();
|
|
|
|
return .{
|
|
.allocator = allocator,
|
|
.gateway_ip = gateway,
|
|
.socket = null,
|
|
.gateway_epoch = 0,
|
|
};
|
|
}
|
|
|
|
pub fn initWithGateway(allocator: Allocator, gateway_ip: [4]u8) NatPmp {
|
|
return .{
|
|
.allocator = allocator,
|
|
.gateway_ip = gateway_ip,
|
|
.socket = null,
|
|
.gateway_epoch = 0,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *NatPmp) void {
|
|
if (self.socket) |sock| {
|
|
posix.close(sock);
|
|
self.socket = null;
|
|
}
|
|
}
|
|
|
|
/// Get the external (public) IP address from the NAT gateway
|
|
pub fn getExternalAddress(self: *NatPmp) !?[4]u8 {
|
|
const sock = try self.getSocket();
|
|
|
|
// Build request: [version=0, opcode=0]
|
|
const request = [_]u8{ VERSION, @intFromEnum(Opcode.external_address) };
|
|
|
|
// Send to gateway
|
|
const gateway_addr = std.net.Address.initIp4(self.gateway_ip, NAT_PMP_PORT);
|
|
_ = posix.sendto(sock, &request, 0, &gateway_addr.any, gateway_addr.getOsSockLen()) catch |err| {
|
|
std.log.warn("NAT-PMP: Failed to send external address request: {}", .{err});
|
|
return null;
|
|
};
|
|
|
|
// Receive response (12 bytes)
|
|
var response: [12]u8 = undefined;
|
|
var src_addr: posix.sockaddr.storage = undefined;
|
|
var src_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
|
|
|
|
// Set timeout
|
|
const timeout = posix.timeval{ .sec = 3, .usec = 0 };
|
|
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
|
|
|
|
const recv_len = posix.recvfrom(sock, &response, 0, @ptrCast(&src_addr), &src_len) catch |err| {
|
|
std.log.debug("NAT-PMP: No response from gateway ({})", .{err});
|
|
return null;
|
|
};
|
|
|
|
// SECURITY: Verify response came from our gateway (prevents LAN spoofing)
|
|
if (!verifySourceAddress(&src_addr, self.gateway_ip)) {
|
|
std.log.warn("NAT-PMP: Response from unexpected source, ignoring (possible spoofing)", .{});
|
|
return null;
|
|
}
|
|
|
|
if (recv_len < 12) {
|
|
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
|
return null;
|
|
}
|
|
|
|
// Parse response
|
|
const version = response[0];
|
|
const opcode = response[1];
|
|
const result_code: ResultCode = @enumFromInt(std.mem.readInt(u16, response[2..4], .big));
|
|
const epoch = std.mem.readInt(u32, response[4..8], .big);
|
|
const external_ip = response[8..12].*;
|
|
|
|
if (version != VERSION) {
|
|
std.log.warn("NAT-PMP: Unexpected version {}", .{version});
|
|
return null;
|
|
}
|
|
|
|
if (opcode != 128 + @intFromEnum(Opcode.external_address)) {
|
|
std.log.warn("NAT-PMP: Unexpected opcode {}", .{opcode});
|
|
return null;
|
|
}
|
|
|
|
if (!result_code.isSuccess()) {
|
|
std.log.warn("NAT-PMP: Gateway returned error: {s}", .{result_code.toString()});
|
|
return null;
|
|
}
|
|
|
|
// Check for gateway reboot (epoch reset)
|
|
if (self.gateway_epoch != 0 and epoch < self.gateway_epoch) {
|
|
std.log.info("NAT-PMP: Gateway rebooted, mappings may be lost", .{});
|
|
}
|
|
self.gateway_epoch = epoch;
|
|
|
|
std.log.info("NAT-PMP: External address is {d}.{d}.{d}.{d}", .{
|
|
external_ip[0], external_ip[1], external_ip[2], external_ip[3],
|
|
});
|
|
|
|
return external_ip;
|
|
}
|
|
|
|
/// Request a port mapping from the NAT gateway
|
|
pub fn mapPort(
|
|
self: *NatPmp,
|
|
protocol: Protocol,
|
|
internal_port: u16,
|
|
suggested_external_port: u16,
|
|
lifetime_seconds: u32,
|
|
) !?PortMapping {
|
|
const sock = try self.getSocket();
|
|
|
|
// Build request (12 bytes)
|
|
var request: [12]u8 = undefined;
|
|
request[0] = VERSION;
|
|
request[1] = @intFromEnum(protocol);
|
|
request[2] = 0; // Reserved
|
|
request[3] = 0; // Reserved
|
|
std.mem.writeInt(u16, request[4..6], internal_port, .big);
|
|
std.mem.writeInt(u16, request[6..8], suggested_external_port, .big);
|
|
std.mem.writeInt(u32, request[8..12], lifetime_seconds, .big);
|
|
|
|
// Send to gateway
|
|
const gateway_addr = std.net.Address.initIp4(self.gateway_ip, NAT_PMP_PORT);
|
|
_ = posix.sendto(sock, &request, 0, &gateway_addr.any, gateway_addr.getOsSockLen()) catch |err| {
|
|
std.log.warn("NAT-PMP: Failed to send map request: {}", .{err});
|
|
return null;
|
|
};
|
|
|
|
// Receive response (16 bytes)
|
|
var response: [16]u8 = undefined;
|
|
var src_addr: posix.sockaddr.storage = undefined;
|
|
var src_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
|
|
|
|
const timeout = posix.timeval{ .sec = 3, .usec = 0 };
|
|
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
|
|
|
|
const recv_len = posix.recvfrom(sock, &response, 0, @ptrCast(&src_addr), &src_len) catch |err| {
|
|
std.log.debug("NAT-PMP: No response from gateway ({})", .{err});
|
|
return null;
|
|
};
|
|
|
|
// SECURITY: Verify response came from our gateway (prevents LAN spoofing)
|
|
if (!verifySourceAddress(&src_addr, self.gateway_ip)) {
|
|
std.log.warn("NAT-PMP: Response from unexpected source, ignoring (possible spoofing)", .{});
|
|
return null;
|
|
}
|
|
|
|
if (recv_len < 16) {
|
|
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
|
return null;
|
|
}
|
|
|
|
// Parse response
|
|
const version = response[0];
|
|
const opcode = response[1];
|
|
const result_code: ResultCode = @enumFromInt(std.mem.readInt(u16, response[2..4], .big));
|
|
const epoch = std.mem.readInt(u32, response[4..8], .big);
|
|
const resp_internal_port = std.mem.readInt(u16, response[8..10], .big);
|
|
const mapped_external_port = std.mem.readInt(u16, response[10..12], .big);
|
|
const actual_lifetime = std.mem.readInt(u32, response[12..16], .big);
|
|
|
|
if (version != VERSION) {
|
|
std.log.warn("NAT-PMP: Unexpected version {}", .{version});
|
|
return null;
|
|
}
|
|
|
|
const expected_opcode = 128 + @intFromEnum(protocol);
|
|
if (opcode != expected_opcode) {
|
|
std.log.warn("NAT-PMP: Unexpected opcode {} (expected {})", .{ opcode, expected_opcode });
|
|
return null;
|
|
}
|
|
|
|
if (!result_code.isSuccess()) {
|
|
std.log.warn("NAT-PMP: Gateway returned error: {s}", .{result_code.toString()});
|
|
return null;
|
|
}
|
|
|
|
self.gateway_epoch = epoch;
|
|
|
|
// Get external IP (need to query separately or use cached)
|
|
const external_ip: [4]u8 = blk: {
|
|
const maybe_ip = self.getExternalAddress() catch null;
|
|
break :blk maybe_ip orelse [_]u8{ 0, 0, 0, 0 };
|
|
};
|
|
|
|
std.log.info("NAT-PMP: Mapped {s} port {d} -> {d}.{d}.{d}.{d}:{d} (lifetime: {d}s)", .{
|
|
if (protocol == .udp) "UDP" else "TCP",
|
|
resp_internal_port,
|
|
external_ip[0],
|
|
external_ip[1],
|
|
external_ip[2],
|
|
external_ip[3],
|
|
mapped_external_port,
|
|
actual_lifetime,
|
|
});
|
|
|
|
return PortMapping{
|
|
.internal_port = resp_internal_port,
|
|
.external_port = mapped_external_port,
|
|
.lifetime_seconds = actual_lifetime,
|
|
.external_ip = external_ip,
|
|
};
|
|
}
|
|
|
|
/// Delete a port mapping (set lifetime to 0)
|
|
pub fn unmapPort(self: *NatPmp, protocol: Protocol, internal_port: u16) !void {
|
|
_ = try self.mapPort(protocol, internal_port, 0, 0);
|
|
}
|
|
|
|
/// Check if NAT-PMP is available on this network
|
|
pub fn isAvailable(self: *NatPmp) bool {
|
|
const result = self.getExternalAddress() catch return false;
|
|
return result != null;
|
|
}
|
|
|
|
fn getSocket(self: *NatPmp) !posix.socket_t {
|
|
if (self.socket) |sock| {
|
|
return sock;
|
|
}
|
|
|
|
const sock = try posix.socket(posix.AF.INET, posix.SOCK.DGRAM, 0);
|
|
self.socket = sock;
|
|
return sock;
|
|
}
|
|
};
|
|
|
|
/// Verify that a received UDP response came from the expected gateway IP.
|
|
/// Prevents LAN-based spoofing of NAT-PMP responses.
|
|
fn verifySourceAddress(src: *const posix.sockaddr.storage, expected_ip: [4]u8) bool {
|
|
if (src.family != posix.AF.INET) return false;
|
|
const in_addr: *const posix.sockaddr.in = @ptrCast(src);
|
|
const src_ip: [4]u8 = @bitCast(in_addr.addr);
|
|
return std.mem.eql(u8, &src_ip, &expected_ip);
|
|
}
|
|
|
|
/// Discover the default gateway IP address
|
|
pub fn discoverGateway() ![4]u8 {
|
|
if (is_wasm) return error.UnsupportedPlatform;
|
|
|
|
// Platform-specific gateway discovery
|
|
if (@import("builtin").os.tag == .macos or @import("builtin").os.tag == .ios) {
|
|
return discoverGatewayDarwin();
|
|
} else if (@import("builtin").os.tag == .linux) {
|
|
return discoverGatewayLinux();
|
|
} else {
|
|
return error.UnsupportedPlatform;
|
|
}
|
|
}
|
|
|
|
fn discoverGatewayDarwin() ![4]u8 {
|
|
// On macOS, use route command or read from sysctl
|
|
// For now, try common gateway addresses
|
|
const common_gateways = [_][4]u8{
|
|
.{ 192, 168, 1, 1 },
|
|
.{ 192, 168, 0, 1 },
|
|
.{ 10, 0, 0, 1 },
|
|
.{ 172, 16, 0, 1 },
|
|
};
|
|
|
|
for (common_gateways) |gw| {
|
|
// Try to reach the gateway
|
|
const sock = posix.socket(posix.AF.INET, posix.SOCK.DGRAM, 0) catch continue;
|
|
defer posix.close(sock);
|
|
|
|
const addr = std.net.Address.initIp4(gw, NAT_PMP_PORT);
|
|
|
|
// Non-blocking connect just to check reachability
|
|
const timeout = posix.timeval{ .sec = 1, .usec = 0 };
|
|
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.SNDTIMEO, std.mem.asBytes(&timeout)) catch {};
|
|
|
|
// Send a probe
|
|
const probe = [_]u8{ 0, 0 }; // External address request
|
|
_ = posix.sendto(sock, &probe, 0, &addr.any, addr.getOsSockLen()) catch continue;
|
|
|
|
// Try to receive
|
|
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
|
|
|
|
var response: [16]u8 = undefined;
|
|
var src_addr: posix.sockaddr.storage = undefined;
|
|
var src_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
|
|
|
|
if (posix.recvfrom(sock, &response, 0, @ptrCast(&src_addr), &src_len)) |len| {
|
|
if (len >= 12 and response[0] == 0 and response[1] == 128) {
|
|
std.log.info("NAT-PMP: Found gateway at {d}.{d}.{d}.{d}", .{ gw[0], gw[1], gw[2], gw[3] });
|
|
return gw;
|
|
}
|
|
} else |_| {
|
|
continue;
|
|
}
|
|
}
|
|
|
|
// No gateway responded — return error instead of guessing
|
|
std.log.warn("NAT-PMP: No gateway responded to probes, gateway discovery failed", .{});
|
|
return error.GatewayNotFound;
|
|
}
|
|
|
|
fn discoverGatewayLinux() ![4]u8 {
|
|
// On Linux, read /proc/net/route
|
|
const file = std.fs.openFileAbsolute("/proc/net/route", .{}) catch {
|
|
std.log.warn("NAT-PMP: Cannot open /proc/net/route, gateway discovery failed", .{});
|
|
return error.GatewayNotFound;
|
|
};
|
|
defer file.close();
|
|
|
|
var buf: [4096]u8 = undefined;
|
|
const bytes_read = file.readAll(&buf) catch return error.GatewayNotFound;
|
|
|
|
var lines = std.mem.splitScalar(u8, buf[0..bytes_read], '\n');
|
|
_ = lines.next(); // Skip header
|
|
|
|
while (lines.next()) |line| {
|
|
var fields = std.mem.splitScalar(u8, line, '\t');
|
|
_ = fields.next(); // Interface name
|
|
const dest = fields.next() orelse continue;
|
|
const gateway = fields.next() orelse continue;
|
|
|
|
// Check if destination is 0.0.0.0 (default route)
|
|
if (std.mem.eql(u8, dest, "00000000")) {
|
|
// Parse gateway (hex, little-endian on x86)
|
|
const gw_int = std.fmt.parseInt(u32, gateway, 16) catch continue;
|
|
return .{
|
|
@truncate(gw_int),
|
|
@truncate(gw_int >> 8),
|
|
@truncate(gw_int >> 16),
|
|
@truncate(gw_int >> 24),
|
|
};
|
|
}
|
|
}
|
|
|
|
std.log.warn("NAT-PMP: No default route found in /proc/net/route, gateway discovery failed", .{});
|
|
return error.GatewayNotFound;
|
|
}
|
|
|
|
// Tests
|
|
test "NatPmp packet format" {
|
|
// External address request
|
|
const request = [_]u8{ 0, 0 };
|
|
try std.testing.expectEqual(@as(u8, 0), request[0]); // Version
|
|
try std.testing.expectEqual(@as(u8, 0), request[1]); // Opcode
|
|
|
|
// Port mapping request
|
|
var map_request: [12]u8 = undefined;
|
|
map_request[0] = 0; // Version
|
|
map_request[1] = 1; // Opcode (UDP)
|
|
map_request[2] = 0; // Reserved
|
|
map_request[3] = 0; // Reserved
|
|
std.mem.writeInt(u16, map_request[4..6], 8080, .big);
|
|
std.mem.writeInt(u16, map_request[6..8], 8080, .big);
|
|
std.mem.writeInt(u32, map_request[8..12], 3600, .big);
|
|
|
|
try std.testing.expectEqual(@as(u16, 8080), std.mem.readInt(u16, map_request[4..6], .big));
|
|
}
|
|
|
|
test "ResultCode" {
|
|
try std.testing.expect(ResultCode.success.isSuccess());
|
|
try std.testing.expect(!ResultCode.not_authorized.isSuccess());
|
|
try std.testing.expectEqualStrings("Success", ResultCode.success.toString());
|
|
}
|