diff --git a/build.zig b/build.zig index 4f4eaef..2d2dc05 100644 --- a/build.zig +++ b/build.zig @@ -35,6 +35,7 @@ pub fn build(b: *std.Build) void { "src/output.zig", "src/ports.zig", "src/sigs.zig", + "src/scripts.zig", }; for (test_modules) |mod| { diff --git a/src/banner.zig b/src/banner.zig index b8b21ef..97b9048 100644 --- a/src/banner.zig +++ b/src/banner.zig @@ -80,6 +80,13 @@ pub fn detect(ip: u32, port: u16) ServiceInfo { .amqp => probeAmqp(ip, port), .rdp => probeRdp(ip, port), .smb => probeSmb(ip, port), + .dns => probeDns(ip, port), + .kerberos => probeKerberos(ip, port), + .msrpc => probeMsrpc(ip, port), + .netbios => probeNetbios(ip, port), + .ldap => probeLdap(ip, port), + .xmpp => probeXmpp(ip, port), + .socks => probeSocks(ip, port), .generic => probeGeneric(ip, port), }; } @@ -158,13 +165,20 @@ const Protocol = enum { amqp, rdp, smb, + dns, + kerberos, + msrpc, + netbios, + ldap, + xmpp, + socks, generic, }; fn classifyPort(port: u16) Protocol { return switch (port) { - 80, 3000, 5000, 8000, 8080, 8888, 9090 => .http, - 443, 465, 636, 990, 992, 993, 995, 8443 => .tls, + 80, 3000, 5000, 7070, 8000, 8080, 8888, 9090 => .http, + 443, 465, 636, 990, 992, 993, 995, 3269, 7443, 8443, 9091 => .tls, 22, 2222 => .ssh, 21 => .ftp, 25, 587 => .smtp, @@ -177,6 +191,13 @@ fn classifyPort(port: u16) Protocol { 5672 => .amqp, 3389 => .rdp, 445 => .smb, + 53 => .dns, + 88, 464 => .kerberos, + 135, 593 => .msrpc, + 139 => .netbios, + 389, 3268 => .ldap, + 5222, 5269 => .xmpp, + 1080, 7777 => .socks, else => .generic, }; } @@ -618,6 +639,12 @@ fn probeTls(ip: u32, port: u16) ServiceInfo { info.setVersion(ver); } + // Label the underlying protocol based on ALPN or well-known TLS port + const underlying = guessUnderlyingService(port, alpn_str); + if (underlying.len > 0) { + info.setName(underlying); + } + return info; } @@ -906,6 +933,484 @@ fn probeSmb(ip: u32, port: u16) ServiceInfo { return info; } +fn probeDns(ip: u32, port: u16) ServiceInfo { + var info = ServiceInfo{}; + const fd = openSocket(ip, port) orelse return info; + defer std.posix.close(fd); + + // DNS version.bind TXT CH query over TCP (2-byte length prefix + DNS packet) + const dns_payload = [_]u8{ + // DNS header + 0x13, 0x37, // Transaction ID + 0x00, 0x00, // Flags: standard query + 0x00, 0x01, // Questions: 1 + 0x00, 0x00, // Answer RRs + 0x00, 0x00, // Authority RRs + 0x00, 0x00, // Additional RRs + // Question: version.bind CH TXT + 0x07, 'v', + 'e', 'r', + 's', 'i', + 'o', 'n', + 0x04, 'b', + 'i', 'n', + 'd', + 0x00, // root label + 0x00, 0x10, // Type: TXT + 0x00, 0x03, // Class: CH + }; + const tcp_len: u16 = dns_payload.len; + const dns_query = [2]u8{ @intCast(tcp_len >> 8), @intCast(tcp_len & 0xFF) } ++ dns_payload; + _ = std.posix.write(fd, &dns_query) catch return info; + + var buf: [512]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return info; + // TCP DNS response: 2-byte length prefix + DNS message + if (n < 14) return info; + + // Skip 2-byte TCP length prefix + const dns_data = buf[2..n]; + if (dns_data.len < 12) return info; + + // Check transaction ID matches + if (dns_data[0] != 0x13 or dns_data[1] != 0x37) return info; + + // Check QR bit (response flag) + const flags = (@as(u16, dns_data[2]) << 8) | @as(u16, dns_data[3]); + if ((flags & 0x8000) == 0) return info; + + info.setName("DNS"); + + // Check answer count + const ancount = (@as(u16, dns_data[6]) << 8) | @as(u16, dns_data[7]); + if (ancount == 0) return info; + + // Skip question section to find answers (starts at offset 12) + var pos: usize = 12; + while (pos < dns_data.len) { + const label_len = dns_data[pos]; + if (label_len == 0) { + pos += 1; + break; + } + if ((label_len & 0xC0) == 0xC0) { + pos += 2; + break; + } + pos += 1 + @as(usize, label_len); + } + pos += 4; // skip QTYPE and QCLASS + + // Parse first answer - skip name (may be compressed pointer) + if (pos >= dns_data.len) return info; + if ((dns_data[pos] & 0xC0) == 0xC0) { + pos += 2; + } else { + while (pos < dns_data.len) { + const label_len = dns_data[pos]; + if (label_len == 0) { + pos += 1; + break; + } + pos += 1 + @as(usize, label_len); + } + } + + if (pos + 10 > dns_data.len) return info; + // TYPE(2) + CLASS(2) + TTL(4) + RDLENGTH(2) + const rtype = (@as(u16, dns_data[pos]) << 8) | @as(u16, dns_data[pos + 1]); + pos += 8; // skip TYPE, CLASS, TTL + const rdlen = (@as(u16, dns_data[pos]) << 8) | @as(u16, dns_data[pos + 1]); + pos += 2; + + if (rtype == 0x0010 and rdlen > 1 and pos + @as(usize, rdlen) <= dns_data.len) { + // TXT record: first byte is text length + const txt_len = dns_data[pos]; + if (txt_len > 0 and pos + 1 + @as(usize, txt_len) <= dns_data.len) { + const txt = dns_data[pos + 1 .. pos + 1 + @as(usize, txt_len)]; + info.setVersion(txt); + } + } + + return info; +} + +fn probeKerberos(ip: u32, port: u16) ServiceInfo { + var info = ServiceInfo{}; + const fd = openSocket(ip, port) orelse return info; + defer std.posix.close(fd); + + // Minimal Kerberos AS-REQ with dummy realm "X" + const as_req = [_]u8{ + // TCP length prefix (4 bytes big-endian) + 0x00, 0x00, 0x00, 0x49, // 73 bytes + // APPLICATION[10] (AS-REQ) + 0x6A, 0x47, 0x30, 0x45, + // pvno: INTEGER 5 + 0xA1, 0x03, 0x02, 0x01, + 0x05, + // msg-type: INTEGER 10 (AS-REQ) + 0xA2, 0x03, 0x02, + 0x01, 0x0A, + // req-body: context[4] SEQUENCE + 0xA4, 0x39, + 0x30, 0x37, + // kdc-options: BIT STRING (all zero) + 0xA0, 0x07, + 0x03, 0x05, 0x00, 0x00, + 0x00, 0x00, 0x00, + // cname: name-type=1, name-string={""} + 0xA1, + 0x0D, 0x30, 0x0B, 0xA0, + 0x03, 0x02, 0x01, 0x01, + 0xA1, 0x04, 0x30, 0x02, + 0x1B, 0x00, + // realm: GeneralString "X" + 0xA2, 0x03, + 0x1B, 0x01, 0x58, + // till: GeneralizedTime "20370101000000Z" + 0xA5, + 0x11, 0x18, 0x0F, 0x32, + 0x30, 0x33, 0x37, 0x30, + 0x31, 0x30, 0x31, 0x30, + 0x30, 0x30, 0x30, 0x30, + 0x30, 0x5A, + // etype: SEQUENCE { 18 (aes256-cts) } + 0xA8, 0x05, + 0x30, 0x03, 0x02, 0x01, + 0x12, + }; + _ = std.posix.write(fd, &as_req) catch return info; + + var buf: [512]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return info; + if (n < 5) return info; + + // Response: 4-byte TCP length prefix + Kerberos message + // APPLICATION[30] (KRB_ERROR) = 0x7E, APPLICATION[11] (AS_REP) = 0x6B + if (buf[4] == 0x7E or buf[4] == 0x6B) { + info.setName("Kerberos"); + // Try to extract realm from KRB_ERROR response + if (buf[4] == 0x7E and n > 20) { + extractKerberosRealm(buf[4..n], &info); + } + } + + return info; +} + +fn extractKerberosRealm(data: []const u8, info: *ServiceInfo) void { + // Scan for GeneralString tags (0x1B) with plausible realm content + var i: usize = 0; + while (i + 2 < data.len) { + if (data[i] == 0x1B) { + const str_len = data[i + 1]; + if (str_len > 1 and str_len < 64 and i + 2 + @as(usize, str_len) <= data.len) { + const candidate = data[i + 2 .. i + 2 + @as(usize, str_len)]; + if (isLikelyRealm(candidate)) { + info.setExtra(candidate); + return; + } + } + } + i += 1; + } +} + +fn isLikelyRealm(s: []const u8) bool { + if (s.len == 0) return false; + var has_upper = false; + for (s) |c| { + if (c >= 'A' and c <= 'Z') { + has_upper = true; + } else if (c == '.' or c == '-') { + // domain-style separators OK + } else if (c >= 'a' and c <= 'z') { + // lowercase OK + } else if (c >= '0' and c <= '9') { + // digits OK + } else { + return false; + } + } + return has_upper; +} + +fn probeMsrpc(ip: u32, port: u16) ServiceInfo { + var info = ServiceInfo{}; + const fd = openSocket(ip, port) orelse return info; + defer std.posix.close(fd); + + // DCE/RPC Bind to endpoint mapper (72 bytes) + const rpc_bind = [_]u8{ + 0x05, 0x00, // version 5.0 + 0x0B, // packet type: bind + 0x03, // flags: first+last frag + 0x10, 0x00, 0x00, 0x00, // data representation (little-endian, ASCII, IEEE) + 0x48, 0x00, // frag length (72) + 0x00, 0x00, // auth length + 0x01, 0x00, 0x00, 0x00, // call ID + 0xD8, 0x10, // max xmit frag + 0xD8, 0x10, // max recv frag + 0x00, 0x00, 0x00, 0x00, // assoc group + 0x01, 0x00, 0x00, 0x00, // num ctx items = 1 + 0x00, 0x00, // context ID + 0x01, 0x00, // num transfer syntaxes + // Abstract syntax: EPM (e1af8308-5d1f-11c9-91a4-08002b14a0fa v3.0) + 0x08, 0x83, + 0xAF, 0xE1, + 0x1F, 0x5D, + 0xC9, 0x11, + 0x91, 0xA4, + 0x08, 0x00, + 0x2B, 0x14, + 0xA0, 0xFA, + 0x03, 0x00, + 0x00, 0x00, + // Transfer syntax: NDR (8a885d04-1ceb-11c9-9fe8-08002b104860 v2.0) + 0x04, 0x5D, + 0x88, 0x8A, + 0xEB, 0x1C, + 0xC9, 0x11, + 0x9F, 0xE8, + 0x08, 0x00, + 0x2B, 0x10, + 0x48, 0x60, + 0x02, 0x00, + 0x00, 0x00, + }; + _ = std.posix.write(fd, &rpc_bind) catch return info; + + var buf: [256]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return info; + if (n < 3) return info; + + // Check: DCE/RPC version 5, packet type 0x0C (bind_ack) + if (buf[0] == 0x05 and buf[2] == 0x0C) { + info.setName("MSRPC"); + info.setExtra("Microsoft Windows RPC"); + } + + return info; +} + +fn probeNetbios(ip: u32, port: u16) ServiceInfo { + var info = ServiceInfo{}; + const fd = openSocket(ip, port) orelse return info; + defer std.posix.close(fd); + + // NetBIOS Session Request + // Called name: *SMBSERVER (encoded), Calling name: spaces (encoded) + const nbss = [_]u8{ + 0x81, // session request type + 0x00, // flags + 0x00, 0x44, // length = 68 (called 34 + calling 34) + // Called name: *SMBSERVER padded with spaces, first-level encoded + 0x20, // name length (32 encoded bytes follow) + 0x43, 0x4B, // * (0x2A) + 0x46, 0x44, // S (0x53) + 0x45, 0x4E, // M (0x4D) + 0x45, 0x43, // B (0x42) + 0x46, 0x44, // S (0x53) + 0x45, 0x46, // E (0x45) + 0x46, 0x43, // R (0x52) + 0x46, 0x47, // V (0x56) + 0x45, 0x46, // E (0x45) + 0x46, 0x43, // R (0x52) + 0x43, 0x41, // SP (0x20) + 0x43, 0x41, // SP + 0x43, 0x41, // SP + 0x43, 0x41, // SP + 0x43, 0x41, // SP + 0x43, 0x41, // SP + 0x00, // scope (null) + // Calling name: all spaces, first-level encoded + 0x20, // name length + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x43, + 0x41, + 0x00, // scope (null) + }; + _ = std.posix.write(fd, &nbss) catch return info; + + var buf: [64]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return info; + if (n < 1) return info; + + if (buf[0] == 0x82) { + info.setName("NetBIOS-SSN"); + info.setExtra("session established"); + } else if (buf[0] == 0x83) { + info.setName("NetBIOS-SSN"); + info.setExtra("session refused"); + } + + return info; +} + +fn probeLdap(ip: u32, port: u16) ServiceInfo { + var info = ServiceInfo{}; + const fd = openSocket(ip, port) orelse return info; + defer std.posix.close(fd); + + // LDAP SearchRequest for rootDSE (anonymous bind, base scope, objectClass=*) + const ldap_search = [_]u8{ + 0x30, 0x25, // SEQUENCE len=37 + 0x02, 0x01, 0x01, // MessageID = 1 + 0x63, 0x20, // APPLICATION[3] SearchRequest len=32 + 0x04, 0x00, // baseObject = "" + 0x0A, 0x01, 0x00, // scope = base + 0x0A, 0x01, 0x00, // derefAliases = never + 0x02, 0x01, 0x00, // sizeLimit = 0 + 0x02, 0x01, 0x00, // timeLimit = 0 + 0x01, 0x01, 0x00, // typesOnly = false + 0x87, 0x0B, // CONTEXT[7] present filter len=11 + 'o', 'b', + 'j', 'e', + 'c', 't', + 'C', 'l', + 'a', 's', + 's', + 0x30, 0x00, // empty attribute list (return all) + }; + _ = std.posix.write(fd, &ldap_search) catch return info; + + var buf: [2048]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return info; + if (n < 6) return info; + + const data = buf[0..n]; + // Valid LDAP response starts with SEQUENCE (0x30) + if (data[0] != 0x30) return info; + + // Parse BER SEQUENCE: skip tag, then length + var pos: usize = 1; + if (pos >= n) return info; + if ((data[pos] & 0x80) != 0) { + pos += 1 + @as(usize, data[pos] & 0x7F); + } else { + pos += 1; + } + // Skip messageID (tag 0x02 + length byte + value bytes) + if (pos + 2 >= n or data[pos] != 0x02) return info; + pos += 2 + @as(usize, data[pos + 1]); + + if (pos >= n) return info; + + // Check for LDAP response APPLICATION tags + // 0x61=BindResponse, 0x64=SearchResultEntry, 0x65=SearchResultDone + if (data[pos] != 0x64 and data[pos] != 0x65 and data[pos] != 0x61) return info; + + info.setName("LDAP"); + + // Scan for domain components (DC=...) in the response + var dc_start = std.mem.indexOf(u8, data, "DC="); + if (dc_start == null) dc_start = std.mem.indexOf(u8, data, "dc="); + if (dc_start) |dpos| { + var end = dpos; + while (end < data.len and data[end] >= 0x20 and data[end] < 0x7F) { + end += 1; + } + if (end > dpos) { + info.setExtra(data[dpos..end]); + } + } + + return info; +} + +fn probeXmpp(ip: u32, port: u16) ServiceInfo { + var info = ServiceInfo{}; + const fd = openSocket(ip, port) orelse return info; + defer std.posix.close(fd); + + // XMPP stream header (use server namespace for port 5269) + const xmlns: []const u8 = if (port == 5269) "jabber:server" else "jabber:client"; + var req_buf: [256]u8 = undefined; + const request = std.fmt.bufPrint(&req_buf, "", .{xmlns}) catch return info; + _ = std.posix.write(fd, request) catch return info; + + var buf: [2048]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return info; + if (n < 10) return info; + + const data = buf[0..n]; + + if (std.mem.indexOf(u8, data, " "no-auth", + 0x02 => "user/pass required", + 0xFF => "no acceptable methods", + else => "auth-required", + }; + info.setExtra(method_desc); + } else if (buf[0] == 0x04) { + info.setName("SOCKS4"); + } + + return info; +} + fn probeGeneric(ip: u32, port: u16) ServiceInfo { // Phase 1: NULL probe - wait for service to speak first { @@ -943,6 +1448,18 @@ fn probeGeneric(ip: u32, port: u16) ServiceInfo { const pg_info = probePostgresql(ip, port); if (!pg_info.empty()) return pg_info; } + { + const socks_info = probeSocks(ip, port); + if (!socks_info.empty()) return socks_info; + } + { + const dns_info = probeDns(ip, port); + if (!dns_info.empty()) return dns_info; + } + { + const ldap_info = probeLdap(ip, port); + if (!ldap_info.empty()) return ldap_info; + } return ServiceInfo{}; } @@ -1093,9 +1610,16 @@ fn isKnownNonHttpPort(port: u16) bool { 22, 2222 => true, 21 => true, 25, 587 => true, + 53 => true, + 88, 464 => true, 110 => true, + 135, 593 => true, + 139 => true, 143 => true, + 389, 3268 => true, + 1080, 7777 => true, 3306, 33060 => true, + 5222, 5269 => true, 5432...5434 => true, 6379...6399 => true, 6660...6669, 6697 => true, @@ -1315,6 +1839,22 @@ fn isDigit(c: u8) bool { return c >= '0' and c <= '9'; } +fn guessUnderlyingService(port: u16, alpn_str: []const u8) []const u8 { + if (alpn_str.len > 0) { + if (std.mem.eql(u8, alpn_str, "h2") or std.mem.eql(u8, alpn_str, "http/1.1")) return "https"; + } + return switch (port) { + 443, 8443, 7443, 9091 => "https", + 636, 3269 => "ldaps", + 993 => "imaps", + 995 => "pop3s", + 990 => "ftps", + 465 => "smtps", + 992 => "telnets", + else => "", + }; +} + fn formatIp(buf: []u8, ip: u32) []const u8 { const b = [4]u8{ @intCast((ip >> 24) & 0xFF), @@ -1618,3 +2158,85 @@ test "findBsonString - basic" { try std.testing.expect(result != null); try std.testing.expectEqualStrings("7.0.5", result.?); } + +test "classifyPort - new protocol ports" { + try std.testing.expectEqual(Protocol.dns, classifyPort(53)); + try std.testing.expectEqual(Protocol.kerberos, classifyPort(88)); + try std.testing.expectEqual(Protocol.kerberos, classifyPort(464)); + try std.testing.expectEqual(Protocol.msrpc, classifyPort(135)); + try std.testing.expectEqual(Protocol.msrpc, classifyPort(593)); + try std.testing.expectEqual(Protocol.netbios, classifyPort(139)); + try std.testing.expectEqual(Protocol.ldap, classifyPort(389)); + try std.testing.expectEqual(Protocol.ldap, classifyPort(3268)); + try std.testing.expectEqual(Protocol.xmpp, classifyPort(5222)); + try std.testing.expectEqual(Protocol.xmpp, classifyPort(5269)); + try std.testing.expectEqual(Protocol.socks, classifyPort(1080)); + try std.testing.expectEqual(Protocol.socks, classifyPort(7777)); +} + +test "classifyPort - updated tls ports" { + try std.testing.expectEqual(Protocol.tls, classifyPort(3269)); + try std.testing.expectEqual(Protocol.tls, classifyPort(7443)); + try std.testing.expectEqual(Protocol.tls, classifyPort(9091)); +} + +test "classifyPort - updated http ports" { + try std.testing.expectEqual(Protocol.http, classifyPort(7070)); +} + +test "isKnownNonHttpPort - new protocol ports" { + try std.testing.expect(isKnownNonHttpPort(53)); + try std.testing.expect(isKnownNonHttpPort(88)); + try std.testing.expect(isKnownNonHttpPort(135)); + try std.testing.expect(isKnownNonHttpPort(139)); + try std.testing.expect(isKnownNonHttpPort(389)); + try std.testing.expect(isKnownNonHttpPort(464)); + try std.testing.expect(isKnownNonHttpPort(593)); + try std.testing.expect(isKnownNonHttpPort(1080)); + try std.testing.expect(isKnownNonHttpPort(3268)); + try std.testing.expect(isKnownNonHttpPort(5222)); + try std.testing.expect(isKnownNonHttpPort(5269)); + try std.testing.expect(isKnownNonHttpPort(7777)); +} + +test "guessUnderlyingService - ALPN h2" { + const svc = guessUnderlyingService(12345, "h2"); + try std.testing.expectEqualStrings("https", svc); +} + +test "guessUnderlyingService - ALPN http/1.1" { + const svc = guessUnderlyingService(12345, "http/1.1"); + try std.testing.expectEqualStrings("https", svc); +} + +test "guessUnderlyingService - port-based detection" { + try std.testing.expectEqualStrings("https", guessUnderlyingService(443, "")); + try std.testing.expectEqualStrings("https", guessUnderlyingService(8443, "")); + try std.testing.expectEqualStrings("https", guessUnderlyingService(7443, "")); + try std.testing.expectEqualStrings("https", guessUnderlyingService(9091, "")); + try std.testing.expectEqualStrings("ldaps", guessUnderlyingService(636, "")); + try std.testing.expectEqualStrings("ldaps", guessUnderlyingService(3269, "")); + try std.testing.expectEqualStrings("imaps", guessUnderlyingService(993, "")); + try std.testing.expectEqualStrings("pop3s", guessUnderlyingService(995, "")); + try std.testing.expectEqualStrings("ftps", guessUnderlyingService(990, "")); + try std.testing.expectEqualStrings("smtps", guessUnderlyingService(465, "")); + try std.testing.expectEqualStrings("telnets", guessUnderlyingService(992, "")); +} + +test "guessUnderlyingService - unknown port no ALPN" { + const svc = guessUnderlyingService(12345, ""); + try std.testing.expectEqual(@as(usize, 0), svc.len); +} + +test "isLikelyRealm - valid realms" { + try std.testing.expect(isLikelyRealm("EXAMPLE.COM")); + try std.testing.expect(isLikelyRealm("CORP.INTERNAL")); + try std.testing.expect(isLikelyRealm("MYDOMAIN")); +} + +test "isLikelyRealm - invalid strings" { + try std.testing.expect(!isLikelyRealm("")); + try std.testing.expect(!isLikelyRealm("alllowercase")); + try std.testing.expect(!isLikelyRealm("has spaces")); + try std.testing.expect(!isLikelyRealm("bad\x00char")); +} diff --git a/src/data/service-probes b/src/data/service-probes index 6f6b9b9..97652df 100644 --- a/src/data/service-probes +++ b/src/data/service-probes @@ -20,11 +20,26 @@ IMAP|p|* OK |-1 VNC|p|RFB |4 NATS|p|INFO {|-1 Rsync|p|@RSYNCD: |9 +# Databases +CouchDB|p|{"couchdb":|-1 +RethinkDB|c|"success":true|-1 +# VoIP +Asterisk|p|Asterisk Call Manager/|22 +# Gaming +TeamSpeak|p|TS3|3 [http] # Header-based detection Jenkins|c|X-Jenkins:|-1 Kibana|c|kbn-name|-1 +Forgejo|c|X-Forgejo-Version|-1 +Docker Registry|c|Docker-Distribution-Api-Version|-1 +Harbor Registry|c|X-Harbor-Csrf-Token|-1 +Spring Boot|c|X-Application-Context|-1 +IIS|c|X-Powered-By: ASP.NET|-1 +WildFly|c|X-Powered-By: WildFly|-1 +Puma|c|X-Runtime:|-1 +Werkzeug|c|Server: Werkzeug|-1 # Title-based detection - common self-hosted services GitLab|c|GitLab|-1 Grafana|c|<title>Grafana|-1 @@ -54,3 +69,43 @@ Redmine|c|<title>Redmine|-1 Cockpit|c|<title>Cockpit|-1 Webmin|c|<title>Webmin|-1 Pi-hole|c|<title>Pi-hole|-1 +# CI/CD +TeamCity|c|<title>TeamCity|-1 +Drone|c|<title>Drone|-1 +Bamboo|c|<title>Bamboo|-1 +CircleCI|c|<title>CircleCI|-1 +# Monitoring +Datadog|c|<title>Datadog|-1 +Icinga|c|<title>Icinga|-1 +Nagios|c|<title>Nagios|-1 +Cacti|c|<title>Cacti|-1 +LibreNMS|c|<title>LibreNMS|-1 +Uptime Kuma|c|<title>Uptime Kuma|-1 +Checkmk|c|<title>Checkmk|-1 +# Dev tools +Gogs|c|<title>Gogs|-1 +GitBucket|c|<title>GitBucket|-1 +Redash|c|<title>Redash|-1 +Metabase|c|<title>Metabase|-1 +Superset|c|<title>Superset|-1 +Airflow|c|<title>Airflow|-1 +n8n|c|<title>n8n|-1 +# Web servers and proxies +Tomcat|c|<title>Apache Tomcat|-1 +Traefik|c|<title>Traefik|-1 +HAProxy|c|<title>HAProxy|-1 +Nginx Proxy Manager|c|<title>Nginx Proxy Manager|-1 +Openfire|c|Openfire|-1 +Envoy|c|envoy|-1 +Caddy|c|Caddy|-1 +# Security +Wazuh|c|<title>Wazuh|-1 +OSSEC|c|<title>OSSEC|-1 +Snort|c|<title>Snort|-1 +# Storage and registries +Ceph|c|<title>Ceph|-1 +Nexus|c|<title>Nexus|-1 +Artifactory|c|<title>Artifactory|-1 +# Container orchestration +Kubernetes|c|<title>Kubernetes|-1 +Nomad|c|<title>Nomad|-1 diff --git a/src/os.zig b/src/os.zig index 87b06e0..dc09b20 100644 --- a/src/os.zig +++ b/src/os.zig @@ -4,6 +4,12 @@ const tx_mod = @import("tx.zig"); const MAX_WORKERS: usize = 32; const PROBE_TIMEOUT_NS: u64 = 3 * std.time.ns_per_s; +const PROBE_COUNT: usize = 3; +const MAX_PROBE_PKT: usize = 80; + +// --------------------------------------------------------------------------- +// Public types +// --------------------------------------------------------------------------- pub const OsInfo = struct { name_buf: [64]u8 = .{0} ** 64, @@ -28,6 +34,10 @@ pub const OsInfo = struct { } }; +// --------------------------------------------------------------------------- +// Internal types +// --------------------------------------------------------------------------- + const TcpOptions = struct { mss: u16 = 0, wscale: u8 = 0, @@ -36,13 +46,81 @@ const TcpOptions = struct { has_timestamps: bool = false, }; +const TcpProbeResult = struct { + ttl: u8 = 0, + window: u16 = 0, + df: bool = false, + opts: TcpOptions = .{}, +}; + +const IcmpResult = struct { + valid: bool = false, + ttl: u8 = 0, + df: bool = false, + reply_size: u16 = 0, +}; + +// --------------------------------------------------------------------------- +// Probe descriptors +// --------------------------------------------------------------------------- + +// Probe 1 (SEQ/OPS): standard SYN, tiny window +// MSS=1460, WScale=10, SACK, Timestamps(0,0), NOP, EOL +const probe1_opts = [_]u8{ + 0x02, 0x04, 0x05, 0xB4, // MSS = 1460 + 0x03, 0x03, 0x0A, // WScale = 10 + 0x04, 0x02, // SACK Permitted + 0x08, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Timestamps + 0x01, // NOP + 0x00, // EOL +}; + +// Probe 2 (WIN): different MSS, specific window +// MSS=265, NOP, NOP, Timestamps(0,0), NOP, WScale=1, SACK +const probe2_opts = [_]u8{ + 0x02, 0x04, 0x01, 0x09, // MSS = 265 + 0x01, // NOP + 0x01, // NOP + 0x08, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Timestamps + 0x01, // NOP + 0x03, 0x03, 0x01, // WScale = 1 + 0x04, 0x02, // SACK Permitted +}; + +// Probe 3 (ECN): SYN with ECE+CWR flags +// WScale=10, NOP, MSS=1460, SACK, NOP, NOP +const probe3_opts = [_]u8{ + 0x03, 0x03, 0x0A, // WScale = 10 + 0x01, // NOP + 0x02, 0x04, 0x05, 0xB4, // MSS = 1460 + 0x04, 0x02, // SACK Permitted + 0x01, // NOP + 0x01, // NOP +}; + +const ProbeDesc = struct { + window: u16, + flags: u16, + opts: []const u8, +}; + +const probe_descs = [PROBE_COUNT]ProbeDesc{ + .{ .window = 1, .flags = packet.TcpFlags.SYN, .opts = &probe1_opts }, + .{ .window = 63, .flags = packet.TcpFlags.SYN, .opts = &probe2_opts }, + .{ .window = 4, .flags = packet.TcpFlags.SYN | packet.TcpFlags.ECE | packet.TcpFlags.CWR, .opts = &probe3_opts }, +}; + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + pub fn detect(ip: u32, open_port: u16) OsInfo { var info = OsInfo{}; const src_ip = tx_mod.getLocalIp(ip); if (src_ip == 0) return info; - const src_port: u16 = 50000 + @as(u16, @truncate(@as(u64, @bitCast(std.time.milliTimestamp())) % 10000)); + const base_port: u16 = 50000 + @as(u16, @truncate(@as(u64, @bitCast(std.time.milliTimestamp())) % 10000)); const send_fd = openRawSendSocket() catch return info; defer std.posix.close(send_fd); @@ -50,36 +128,50 @@ pub fn detect(ip: u32, open_port: u16) OsInfo { const recv_fd = openRawRecvSocket() catch return info; defer std.posix.close(recv_fd); - setRecvTimeout(recv_fd, 3); - - var tmpl = packet.TcpTemplate.init(src_ip, src_port); - tmpl.patch(ip, open_port, 0x12345678); + setRecvTimeout(recv_fd, 2); const dest = std.posix.sockaddr.in{ .family = std.posix.AF.INET, .port = 0, - .addr = @bitCast(tmpl.buf[16..20].*), + .addr = packet.toNet(u32, ip), }; - _ = std.posix.sendto( - send_fd, - &tmpl.buf, - 0, - @ptrCast(&dest), - @sizeOf(std.posix.sockaddr.in), - ) catch return info; + // Send 3 TCP probes with different options and source ports + for (0..PROBE_COUNT) |i| { + const src_port = base_port +% @as(u16, @intCast(i)); + var pkt_buf: [MAX_PROBE_PKT]u8 = .{0} ** MAX_PROBE_PKT; + const pkt_len = buildSynProbe( + &pkt_buf, + src_ip, + src_port, + ip, + open_port, + 0x12345678 +% @as(u32, @intCast(i)), + probe_descs[i].window, + probe_descs[i].flags, + probe_descs[i].opts, + ); + + _ = std.posix.sendto( + send_fd, + pkt_buf[0..pkt_len], + 0, + @ptrCast(&dest), + @sizeOf(std.posix.sockaddr.in), + ) catch continue; + // Small delay between probes to avoid rate limiting + std.time.sleep(50 * std.time.ns_per_ms); + } + + // Collect TCP probe responses + var probes: [PROBE_COUNT]?TcpProbeResult = .{null} ** PROBE_COUNT; + var received: u8 = 0; var recv_buf: [1540]u8 = undefined; const deadline = std.time.nanoTimestamp() + @as(i128, PROBE_TIMEOUT_NS); - while (std.time.nanoTimestamp() < deadline) { - const n = std.posix.recvfrom( - recv_fd, - &recv_buf, - 0, - null, - null, - ) catch break; + while (std.time.nanoTimestamp() < deadline and received < PROBE_COUNT) { + const n = std.posix.recvfrom(recv_fd, &recv_buf, 0, null, null) catch break; if (n < @sizeOf(packet.Ipv4Header) + @sizeOf(packet.TcpHeader)) continue; @@ -94,13 +186,27 @@ pub fn detect(ip: u32, open_port: u16) OsInfo { const tcp_hdr: *const packet.TcpHeader = @ptrCast(@alignCast(recv_buf[ihl .. ihl + @sizeOf(packet.TcpHeader)])); if (packet.fromNet(u16, tcp_hdr.src_port) != open_port) continue; - if (packet.fromNet(u16, tcp_hdr.dst_port) != src_port) continue; + + const dst_port = packet.fromNet(u16, tcp_hdr.dst_port); + + // Match response to probe by destination port (our source port) + var probe_idx: ?usize = null; + for (0..PROBE_COUNT) |i| { + if (dst_port == base_port +% @as(u16, @intCast(i)) and probes[i] == null) { + probe_idx = i; + break; + } + } + if (probe_idx == null) continue; const flags = packet.parseTcpFlags(tcp_hdr.data_off_flags); if (!packet.isSynAck(flags)) continue; - const resp_ttl = ip_hdr.ttl; - const resp_window = packet.fromNet(u16, tcp_hdr.window); + const idx = probe_idx.?; + + // Validate ACK number matches our SEQ + 1 + const expected_ack = (0x12345678 +% @as(u32, @intCast(idx))) +% 1; + if (packet.fromNet(u32, tcp_hdr.ack_num) != expected_ack) continue; const data_off: usize = @as(usize, (packet.fromNet(u16, tcp_hdr.data_off_flags) >> 12) & 0xF) * 4; var opts = TcpOptions{}; @@ -108,12 +214,24 @@ pub fn detect(ip: u32, open_port: u16) OsInfo { opts = parseTcpOptions(recv_buf[ihl + 20 .. ihl + data_off]); } - sendRst(send_fd, src_ip, src_port, ip, open_port, packet.fromNet(u32, tcp_hdr.ack_num)); + // Send RST to clean up half-open connection + sendRst(send_fd, src_ip, base_port +% @as(u16, @intCast(idx)), ip, open_port, packet.fromNet(u32, tcp_hdr.ack_num)); - fingerprint(&info, resp_ttl, resp_window, opts); - break; + probes[idx] = TcpProbeResult{ + .ttl = ip_hdr.ttl, + .window = packet.fromNet(u16, tcp_hdr.window), + .df = (recv_buf[6] & 0x40) != 0, + .opts = opts, + }; + received += 1; } + // ICMP probe (best effort - failure is acceptable) + const icmp = probeIcmp(ip); + + // Fingerprint using combined probe data + fingerprintMulti(&info, probes, icmp); + return info; } @@ -126,8 +244,8 @@ pub fn detectAll( if (ips.len == 0) return; if (ips.len == 1 or num_workers <= 1) { - for (ips, 0..) |ip, i| { - results[i] = detect(ip, ports[i]); + for (ips, 0..) |target_ip, i| { + results[i] = detect(target_ip, ports[i]); } return; } @@ -168,6 +286,152 @@ pub fn detectAll( } } +// --------------------------------------------------------------------------- +// Packet building +// --------------------------------------------------------------------------- + +fn buildSynProbe( + buf: *[MAX_PROBE_PKT]u8, + src_ip: u32, + src_port: u16, + dst_ip: u32, + dst_port: u16, + seq: u32, + window: u16, + flags: u16, + tcp_opts: []const u8, +) usize { + const opts_padded = (tcp_opts.len + 3) & ~@as(usize, 3); + const tcp_total: usize = 20 + opts_padded; + const pkt_total: usize = 20 + tcp_total; + + @memset(buf, 0); + + // IP header (20 bytes at offset 0) + const ip: *packet.Ipv4Header = @ptrCast(@alignCast(buf[0..@sizeOf(packet.Ipv4Header)])); + ip.ver_ihl = 0x45; + ip.tos = 0; + ip.total_len = packet.toNet(u16, @intCast(pkt_total)); + ip.identification = 0; + ip.flags_frag = packet.toNet(u16, 0x4000); // DF + ip.ttl = 64; + ip.protocol = packet.IPPROTO_TCP; + ip.src_ip = packet.toNet(u32, src_ip); + ip.dst_ip = packet.toNet(u32, dst_ip); + + // TCP header (20 bytes at offset 20) + const tcp: *packet.TcpHeader = @ptrCast(@alignCast(buf[20..][0..@sizeOf(packet.TcpHeader)])); + tcp.src_port = packet.toNet(u16, src_port); + tcp.dst_port = packet.toNet(u16, dst_port); + tcp.seq_num = packet.toNet(u32, seq); + tcp.ack_num = 0; + const data_off_val: u16 = @intCast(tcp_total / 4); + tcp.data_off_flags = packet.toNet(u16, (data_off_val << 12) | flags); + tcp.window = packet.toNet(u16, window); + tcp.urgent = 0; + + // TCP options (at offset 40, zero-padded to 4-byte boundary) + @memcpy(buf[40 .. 40 + tcp_opts.len], tcp_opts); + + // Compute TCP checksum (field must be zero first) + tcp.checksum = 0; + tcp.checksum = packet.tcpChecksum(ip, buf[20 .. 20 + tcp_total]); + + // Compute IP checksum + ip.checksum = 0; + ip.checksum = packet.ipChecksum(buf[0..20]); + + return pkt_total; +} + +// --------------------------------------------------------------------------- +// ICMP probe +// --------------------------------------------------------------------------- + +fn probeIcmp(ip: u32) IcmpResult { + var result = IcmpResult{}; + + const fd = std.posix.socket( + std.posix.AF.INET, + std.posix.SOCK.RAW, + std.posix.IPPROTO.ICMP, + ) catch return result; + defer std.posix.close(fd); + + setRecvTimeout(fd, 2); + + // Build ICMP Echo Request (8 byte header + 56 byte payload) + var pkt: [64]u8 = .{0} ** 64; + pkt[0] = 8; // type: Echo Request + pkt[1] = 0; // code: 0 + // checksum at [2..4] - computed below + pkt[4] = 0x13; + pkt[5] = 0x37; // identifier + pkt[6] = 0x00; + pkt[7] = 0x01; // sequence number + // Payload: 56 bytes of 0x41 ('A') + for (pkt[8..]) |*b| b.* = 0x41; + + // Compute ICMP checksum + var sum: u32 = 0; + var ci: usize = 0; + while (ci + 1 < pkt.len) : (ci += 2) { + sum += @as(u32, pkt[ci]) << 8 | @as(u32, pkt[ci + 1]); + } + sum = (sum >> 16) + (sum & 0xFFFF); + sum += sum >> 16; + const cksum: u16 = @intCast(~sum & 0xFFFF); + pkt[2] = @intCast(cksum >> 8); + pkt[3] = @intCast(cksum & 0xFF); + + const dest = std.posix.sockaddr.in{ + .family = std.posix.AF.INET, + .port = 0, + .addr = packet.toNet(u32, ip), + }; + + _ = std.posix.sendto( + fd, + &pkt, + 0, + @ptrCast(&dest), + @sizeOf(std.posix.sockaddr.in), + ) catch return result; + + var recv_buf: [1540]u8 = undefined; + const icmp_deadline = std.time.nanoTimestamp() + @as(i128, 2 * std.time.ns_per_s); + + while (std.time.nanoTimestamp() < icmp_deadline) { + const n = std.posix.recvfrom(fd, &recv_buf, 0, null, null) catch break; + if (n < 28) continue; // IP header (20 min) + ICMP header (8) + + // Verify source IP matches target + const ip_hdr: *const packet.Ipv4Header = @ptrCast(@alignCast(recv_buf[0..@sizeOf(packet.Ipv4Header)])); + if (packet.fromNet(u32, ip_hdr.src_ip) != ip) continue; + + const ihl: usize = @as(usize, recv_buf[0] & 0x0F) * 4; + if (n < ihl + 8) continue; + + // Must be Echo Reply (type 0) + if (recv_buf[ihl] != 0) continue; + + // Verify our identifier + if (recv_buf[ihl + 4] != 0x13 or recv_buf[ihl + 5] != 0x37) continue; + + result.valid = true; + result.ttl = recv_buf[8]; // TTL from IP header + result.df = (recv_buf[6] & 0x40) != 0; // DF flag + result.reply_size = @intCast(n - ihl); + break; + } + + return result; +} + +// --------------------------------------------------------------------------- +// TCP option parsing +// --------------------------------------------------------------------------- + fn parseTcpOptions(data: []const u8) TcpOptions { var opts = TcpOptions{}; var pos: usize = 0; @@ -211,6 +475,147 @@ fn parseTcpOptions(data: []const u8) TcpOptions { return opts; } +// --------------------------------------------------------------------------- +// Multi-probe fingerprinting +// --------------------------------------------------------------------------- + +fn fingerprintMulti(info: *OsInfo, probes: [PROBE_COUNT]?TcpProbeResult, icmp: IcmpResult) void { + // Determine base TTL from the first valid probe + var valid_count: u8 = 0; + var base_ttl: u16 = 0; + + for (probes) |mp| { + if (mp) |p| { + valid_count += 1; + if (base_ttl == 0) { + base_ttl = if (p.ttl <= 64) 64 else if (p.ttl <= 128) 128 else 255; + } + info.ttl = p.ttl; + } + } + + if (valid_count == 0 and !icmp.valid) return; + + // Fall back to ICMP TTL when no TCP probes succeeded + if (icmp.valid and base_ttl == 0) { + base_ttl = if (icmp.ttl <= 64) 64 else if (icmp.ttl <= 128) 128 else 255; + info.ttl = icmp.ttl; + } + + // ECN probe (probe 3) response: Linux responds, Windows ignores + const has_ecn_response = probes[2] != null; + + // DF bit from ICMP echo reply + const icmp_df = icmp.valid and icmp.df; + + // --------------------------------------------------------------- + // TTL 128 - Windows family + // --------------------------------------------------------------- + if (base_ttl == 128) { + var confidence: u8 = 70; + if (!has_ecn_response) confidence += 10; // Windows ignores ECN + if (icmp_df) confidence += 5; + + if (probes[0]) |p| { + if (p.opts.has_wscale and p.opts.has_sack and p.opts.has_timestamps) { + if (p.window >= 64000 or p.window == 65535) { + setOs(info, "Windows 10/11/Server 2016+", "Windows", @min(confidence + 5, 95)); + } else if (p.window == 8192) { + setOs(info, "Windows 7/Server 2008", "Windows", confidence); + } else { + setOs(info, "Windows", "Windows", confidence); + } + } else if (p.opts.has_sack and !p.opts.has_timestamps) { + setOs(info, "Windows XP/2003", "Windows", confidence); + } else { + setOs(info, "Windows", "Windows", @min(confidence, 75)); + } + } else { + setOs(info, "Windows", "Windows", 60); + } + return; + } + + // --------------------------------------------------------------- + // TTL 64 - Linux, macOS, *BSD + // --------------------------------------------------------------- + if (base_ttl == 64) { + var confidence: u8 = 70; + if (has_ecn_response) confidence += 5; // Linux responds to ECN + + if (probes[0]) |p| { + // OpenBSD: no wscale, has SACK, window 16384 + if (!p.opts.has_wscale and p.opts.has_sack and p.window == 16384) { + setOs(info, "OpenBSD", "BSD", 80); + return; + } + + // macOS: wscale=6, window=65535 + if (p.opts.has_wscale and p.opts.wscale == 6 and p.window == 65535) { + setOs(info, "macOS", "macOS", 80); + return; + } + + if (p.opts.has_wscale and p.opts.has_sack and p.opts.has_timestamps) { + const standard_mss = (p.opts.mss == 1460 or p.opts.mss == 1448 or + p.opts.mss == 1410 or p.opts.mss == 65495 or p.opts.mss == 0); + + if (standard_mss) { + // Linux version detection by window size + if (p.window >= 65000) { + setOs(info, "Linux 5.x/6.x", "Linux", @min(confidence + 10, 95)); + } else if (p.window >= 26000 and p.window <= 32000) { + setOs(info, "Linux 4.x", "Linux", @min(confidence + 5, 90)); + } else if (p.window >= 14000 and p.window <= 15000) { + setOs(info, "Linux 3.x", "Linux", @min(confidence + 5, 90)); + } else if (p.window >= 5000 and p.window <= 6000) { + setOs(info, "Linux 2.6", "Linux", confidence); + } else { + setOs(info, "Linux", "Linux", confidence); + } + } else if (p.opts.mss > 1400) { + setOs(info, "Linux", "Linux", 70); + } else { + setOs(info, "FreeBSD", "BSD", 65); + } + } else if (p.opts.has_sack and p.opts.has_timestamps) { + setOs(info, "Linux", "Linux", 60); + } else if (p.opts.has_sack) { + setOs(info, "Linux", "Linux", 55); + } else { + setOs(info, "Linux/Unix", "Linux", 55); + } + } else { + setOs(info, "Linux/Unix", "Linux", 50); + } + return; + } + + // --------------------------------------------------------------- + // TTL 255 - Network devices, Solaris + // --------------------------------------------------------------- + if (base_ttl == 255) { + if (probes[0]) |p| { + if (p.window == 4128 and p.opts.mss == 536) { + setOs(info, "Cisco IOS", "Cisco", 90); + } else if (p.opts.has_sack and p.opts.has_timestamps and p.opts.mss == 1460) { + setOs(info, "Solaris", "Solaris", 75); + } else { + setOs(info, "Network Device", "Network", 60); + } + } else { + setOs(info, "Network Device", "Network", 50); + } + return; + } + + setOs(info, "Unknown", "Unknown", 30); +} + +// --------------------------------------------------------------------------- +// Legacy single-probe fingerprint (kept for fallback / reference) +// --------------------------------------------------------------------------- + fn fingerprint(info: *OsInfo, ttl: u8, window: u16, opts: TcpOptions) void { info.ttl = ttl; @@ -300,7 +705,6 @@ fn fingerprint(info: *OsInfo, ttl: u8, window: u16, opts: TcpOptions) void { return; } - // TTL alone gives a hint if (base_ttl == 64) { setOs(info, "Linux/Unix", "Linux", 40); return; @@ -309,6 +713,10 @@ fn fingerprint(info: *OsInfo, ttl: u8, window: u16, opts: TcpOptions) void { setOs(info, "Unknown", "Unknown", 30); } +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + fn setOs(info: *OsInfo, os_name: []const u8, os_family: []const u8, confidence: u8) void { info.name_len = OsInfo.setStr(&info.name_buf, os_name); info.family_len = OsInfo.setStr(&info.family_buf, os_family); diff --git a/src/packet.zig b/src/packet.zig index d898e0e..48887b1 100644 --- a/src/packet.zig +++ b/src/packet.zig @@ -1,6 +1,7 @@ const std = @import("std"); pub const ETH_P_IP: u16 = 0x0800; +pub const IPPROTO_ICMP: u8 = 1; pub const IPPROTO_TCP: u8 = 6; pub const Ipv4Header = extern struct { @@ -42,6 +43,8 @@ pub const TcpFlags = struct { pub const PSH: u16 = 0x0008; pub const ACK: u16 = 0x0010; pub const URG: u16 = 0x0020; + pub const ECE: u16 = 0x0040; + pub const CWR: u16 = 0x0080; }; pub const PACKET_SIZE = @sizeOf(Ipv4Header) + @sizeOf(TcpHeader); diff --git a/src/scripts.zig b/src/scripts.zig index ffcb672..0617217 100644 --- a/src/scripts.zig +++ b/src/scripts.zig @@ -1,5 +1,6 @@ const std = @import("std"); const rx_mod = @import("rx.zig"); +const tls_mod = @import("tls.zig"); const SO_RCVTIMEO = 20; const SO_SNDTIMEO = 21; @@ -69,6 +70,12 @@ pub fn runScripts(ip: u32, port: u16, extended: bool) HostScripts { 22, 2222 => scriptSshHostkey(ip, port, &hs), 25, 587 => scriptSmtpCommands(ip, port, &hs), 3306, 33060 => scriptMysqlInfo(ip, port, &hs), + 3389 => scriptRdpNtlm(ip, port, &hs), + 443, 465, 636, 993, 995, 3269, 7443, 8443, 9091 => scriptSslCert(ip, port, &hs), + 445 => scriptSmb2Info(ip, port, &hs), + 389, 3268 => scriptLdapRootdse(ip, port, &hs), + 5222, 5269 => scriptXmppInfo(ip, port, &hs), + 1080, 7777 => scriptSocksAuth(ip, port, &hs), else => { if (extended) { // Try HTTP scripts on non-standard ports too @@ -588,6 +595,403 @@ fn scriptHttpProxy(ip: u32, port: u16, hs: *HostScripts) void { } } +// --------------------------------------------------------------------------- +// Script: rdp-ntlm-info - RDP negotiation protocol info +// --------------------------------------------------------------------------- + +fn scriptRdpNtlm(ip: u32, port: u16, hs: *HostScripts) void { + const fd = openSocket(ip, port) orelse return; + defer std.posix.close(fd); + + // X.224 Connection Request with RDP Negotiation Request (NLA) + const cr = [_]u8{ + 0x03, 0x00, 0x00, 0x13, // TPKT header, length 19 + 0x0E, // X.224 length indicator + 0xE0, // Connection Request + 0x00, 0x00, // dst-ref + 0x00, 0x00, // src-ref + 0x00, // class 0 + // RDP Negotiation Request + 0x01, // type: RDP_NEG_REQ + 0x00, // flags + 0x08, 0x00, // length (LE) + 0x03, 0x00, 0x00, 0x00, // protocols: PROTOCOL_SSL | PROTOCOL_HYBRID + }; + _ = std.posix.write(fd, &cr) catch return; + + var buf: [256]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return; + if (n < 11) return; + // Check for Connection Confirm (0xD0) + if (buf[5] != 0xD0) return; + + var out_buf: [128]u8 = undefined; + var out_len: usize = 0; + + // Parse RDP Negotiation Response (last 8 bytes of X.224 payload) + const x224_len: usize = buf[4]; + if (x224_len >= 14) { + const neg_offset: usize = 5 + x224_len - 8; + if (neg_offset + 8 <= n and neg_offset >= 5) { + const neg_type = buf[neg_offset]; + if (neg_type == 0x02) { // RDP_NEG_RSP + const proto = buf[neg_offset + 4]; + const proto_name: []const u8 = if (proto & 0x02 != 0) + "NLA (CredSSP)" + else if (proto & 0x01 != 0) + "TLS" + else + "Standard RDP Security"; + const written = std.fmt.bufPrint(&out_buf, "Protocol: {s}", .{proto_name}) catch return; + out_len = written.len; + } else if (neg_type == 0x03) { // NEG_FAILURE + const written = std.fmt.bufPrint(&out_buf, "Negotiation failed", .{}) catch return; + out_len = written.len; + } + } + } + + if (out_len == 0) { + const written = std.fmt.bufPrint(&out_buf, "Microsoft Terminal Services", .{}) catch return; + out_len = written.len; + } + + hs.add("rdp-ntlm-info", out_buf[0..out_len]); +} + +// --------------------------------------------------------------------------- +// Script: ssl-cert - TLS certificate info +// --------------------------------------------------------------------------- + +fn scriptSslCert(ip: u32, port: u16, hs: *HostScripts) void { + const tls_info = tls_mod.probe(ip, port); + if (!tls_info.valid) return; + + var out_buf: [256]u8 = undefined; + var out_len: usize = 0; + + const cn = tls_info.subjectCn(); + if (cn.len > 0) { + const written = std.fmt.bufPrint(out_buf[out_len..], "CN={s}", .{cn}) catch return; + out_len += written.len; + } + + const san = tls_info.sans(); + if (san.len > 0) { + const san_trunc = san[0..@min(san.len, 80)]; + const written = std.fmt.bufPrint(out_buf[out_len..], " SAN={s}", .{san_trunc}) catch return; + out_len += written.len; + } + + const issuer = tls_info.issuerCn(); + if (issuer.len > 0) { + const written = std.fmt.bufPrint(out_buf[out_len..], " Issuer={s}", .{issuer}) catch return; + out_len += written.len; + } + + const expiry = tls_info.notAfter(); + if (expiry.len > 0) { + const written = std.fmt.bufPrint(out_buf[out_len..], " Exp={s}", .{expiry}) catch return; + out_len += written.len; + } + + if (out_len > 0) { + hs.add("ssl-cert", out_buf[0..out_len]); + } +} + +// --------------------------------------------------------------------------- +// Script: smb2-security-mode - SMB2 negotiate security info +// --------------------------------------------------------------------------- + +fn scriptSmb2Info(ip: u32, port: u16, hs: *HostScripts) void { + const fd = openSocket(ip, port) orelse return; + defer std.posix.close(fd); + + // SMB2 Negotiate: NetBIOS(4) + SMB2 header(64) + negotiate body + var pkt: [128]u8 = .{0} ** 128; + var pos: usize = 4; // skip NetBIOS header + + // SMB2 header + @memcpy(pkt[pos .. pos + 4], "\xfeSMB"); + pos += 4; + std.mem.writeInt(u16, pkt[pos..][0..2], 64, .little); + pos += 2; // structure size + pos += 2; // credit charge + pos += 4; // status + // command = NEGOTIATE (0) + pos += 2; + std.mem.writeInt(u16, pkt[pos..][0..2], 1, .little); + pos += 2; // credit request + pos += 4; // flags + pos += 4; // next command + pos += 8; // message ID + pos += 4; // reserved + pos += 4; // tree ID + pos += 8; // session ID + pos += 16; // signature + + // Negotiate body + std.mem.writeInt(u16, pkt[pos..][0..2], 36, .little); + pos += 2; // structure size + std.mem.writeInt(u16, pkt[pos..][0..2], 2, .little); + pos += 2; // dialect count + pos += 2; // security mode + pos += 2; // reserved + pos += 4; // capabilities + pos += 16; // client GUID + pos += 8; // negotiate context + // dialects + std.mem.writeInt(u16, pkt[pos..][0..2], 0x0202, .little); + pos += 2; + std.mem.writeInt(u16, pkt[pos..][0..2], 0x0311, .little); + pos += 2; + + // NetBIOS length + const nb_len: u32 = @intCast(pos - 4); + std.mem.writeInt(u32, pkt[0..4], nb_len, .big); + pkt[0] = 0; + + _ = std.posix.write(fd, pkt[0..pos]) catch return; + + var buf: [512]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return; + if (n < 72) return; + if (!std.mem.eql(u8, buf[4..8], "\xfeSMB")) return; + + var out_buf: [128]u8 = undefined; + var out_len: usize = 0; + + // SMB2 NEGOTIATE response: NetBIOS(4) + header(64) + body + // SecurityMode at body offset 2 (after StructureSize) + if (n >= 74) { + const sec_mode = buf[70]; // 4 + 64 + 2 (skip StructureSize) + const signing: []const u8 = if (sec_mode & 0x02 != 0) + "signing enabled and required" + else if (sec_mode & 0x01 != 0) + "signing enabled" + else + "signing not required"; + + // DialectRevision at body offset 4 + const dialect = std.mem.readInt(u16, buf[72..74], .little); + const dialect_str: []const u8 = switch (dialect) { + 0x0202 => "2.0.2", + 0x0210 => "2.1", + 0x0300 => "3.0", + 0x0302 => "3.0.2", + 0x0311 => "3.1.1", + else => "unknown", + }; + + const written = std.fmt.bufPrint(&out_buf, "SMBv{s}: {s}", .{ dialect_str, signing }) catch return; + out_len = written.len; + } + + if (out_len > 0) { + hs.add("smb2-security-mode", out_buf[0..out_len]); + } +} + +// --------------------------------------------------------------------------- +// Script: ldap-rootdse - LDAP rootDSE search +// --------------------------------------------------------------------------- + +fn scriptLdapRootdse(ip: u32, port: u16, hs: *HostScripts) void { + const fd = openSocket(ip, port) orelse return; + defer std.posix.close(fd); + + // LDAP SearchRequest for rootDSE (base scope, filter: objectClass present) + const ldap_search = [_]u8{ + 0x30, 0x25, // SEQUENCE len=37 + 0x02, 0x01, 0x01, // MessageID = 1 + 0x63, 0x20, // APPLICATION[3] SearchRequest len=32 + 0x04, 0x00, // baseObject = "" + 0x0A, 0x01, 0x00, // scope = base + 0x0A, 0x01, 0x00, // derefAliases = never + 0x02, 0x01, 0x00, // sizeLimit = 0 + 0x02, 0x01, 0x00, // timeLimit = 0 + 0x01, 0x01, 0x00, // typesOnly = false + 0x87, 0x0B, // present filter (context tag 7) + 'o', 'b', + 'j', 'e', + 'c', 't', + 'C', 'l', + 'a', 's', + 's', + 0x30, 0x00, // attributes = all + }; + _ = std.posix.write(fd, &ldap_search) catch return; + + var buf: [4096]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return; + if (n < 10) return; + + const data = buf[0..n]; + + var out_buf: [256]u8 = undefined; + var out_len: usize = 0; + + // Look for well-known LDAP attributes in the response + if (findLdapString(data, "defaultNamingContext")) |val| { + const written = std.fmt.bufPrint(&out_buf, "Domain: {s}", .{val}) catch return; + out_len = written.len; + } else if (findLdapString(data, "dnsHostName")) |val| { + const written = std.fmt.bufPrint(&out_buf, "Host: {s}", .{val}) catch return; + out_len = written.len; + } else if (findLdapString(data, "domainFunctionality")) |val| { + const written = std.fmt.bufPrint(&out_buf, "DomainFunc: {s}", .{val}) catch return; + out_len = written.len; + } else { + // Fallback: check if response contains a SearchResultEntry (tag 0x64) + for (data) |b| { + if (b == 0x64) { + hs.add("ldap-rootdse", "LDAP directory service"); + return; + } + } + return; + } + + if (out_len > 0) { + hs.add("ldap-rootdse", out_buf[0..out_len]); + } +} + +/// Find a string value in an LDAP response by attribute name. +/// Searches for the attribute name (case-insensitive), then looks for the next +/// OCTET STRING (tag 0x04) containing a printable value. +fn findLdapString(data: []const u8, attr_name: []const u8) ?[]const u8 { + const pos = findCaseInsensitive(data, attr_name) orelse return null; + var search_start = pos + attr_name.len; + + // Skip past BER overhead to find the value OCTET STRING + while (search_start + 2 < data.len) : (search_start += 1) { + if (data[search_start] == 0x04) { + const vlen: usize = data[search_start + 1]; + if (vlen > 0 and vlen < 128 and search_start + 2 + vlen <= data.len) { + const val = data[search_start + 2 .. search_start + 2 + vlen]; + // Verify it looks like a printable string + var printable = true; + for (val) |c| { + if (c < 0x20 or c > 0x7E) { + printable = false; + break; + } + } + if (printable and val.len > 0) return val; + } + } + } + return null; +} + +// --------------------------------------------------------------------------- +// Script: xmpp-info - XMPP stream features +// --------------------------------------------------------------------------- + +fn scriptXmppInfo(ip: u32, port: u16, hs: *HostScripts) void { + const fd = openSocket(ip, port) orelse return; + defer std.posix.close(fd); + + const ns: []const u8 = if (port == 5269) "jabber:server" else "jabber:client"; + var req_buf: [256]u8 = undefined; + const request = std.fmt.bufPrint(&req_buf, "<?xml version='1.0'?><stream:stream xmlns='{s}' xmlns:stream='http://etherx.jabber.org/streams' to='unknown' version='1.0'>", .{ns}) catch return; + _ = std.posix.write(fd, request) catch return; + + var buf: [4096]u8 = undefined; + var total: usize = 0; + while (total < buf.len) { + const rd = std.posix.read(fd, buf[total..]) catch break; + if (rd == 0) break; + total += rd; + if (total > 50 and findCaseInsensitive(buf[0..total], "</stream:features>") != null) break; + if (total > 50 and findCaseInsensitive(buf[0..total], "</stream:error>") != null) break; + } + if (total == 0) return; + + const data = buf[0..total]; + var out_buf: [256]u8 = undefined; + var out_len: usize = 0; + + // Check for STARTTLS support + if (findCaseInsensitive(data, "<starttls") != null) { + const written = std.fmt.bufPrint(out_buf[out_len..], "STARTTLS ", .{}) catch return; + out_len += written.len; + } + + // Check for auth mechanisms + if (findCaseInsensitive(data, "PLAIN") != null) { + const written = std.fmt.bufPrint(out_buf[out_len..], "AUTH:PLAIN ", .{}) catch return; + out_len += written.len; + } + if (findCaseInsensitive(data, "SCRAM-SHA-1") != null) { + const written = std.fmt.bufPrint(out_buf[out_len..], "AUTH:SCRAM ", .{}) catch return; + out_len += written.len; + } + + // Extract server identity from from= attribute + var from_pos = findCaseInsensitive(data, "from='"); + var delim: u8 = '\''; + if (from_pos == null) { + from_pos = findCaseInsensitive(data, "from=\""); + delim = '"'; + } + if (from_pos) |fpos| { + const start = fpos + 6; + if (start < data.len) { + const end = std.mem.indexOfScalarPos(u8, data, start, delim) orelse @min(start + 64, data.len); + if (end > start) { + const from_val = data[start..end]; + const written = std.fmt.bufPrint(out_buf[out_len..], "server={s}", .{from_val}) catch return; + out_len += written.len; + } + } + } + + if (out_len > 0) { + hs.add("xmpp-info", out_buf[0..out_len]); + } else if (findCaseInsensitive(data, "<stream:stream") != null) { + hs.add("xmpp-info", "XMPP stream"); + } + + _ = std.posix.write(fd, "</stream:stream>") catch {}; +} + +// --------------------------------------------------------------------------- +// Script: socks-auth-info - SOCKS5 authentication methods +// --------------------------------------------------------------------------- + +fn scriptSocksAuth(ip: u32, port: u16, hs: *HostScripts) void { + const fd = openSocket(ip, port) orelse return; + defer std.posix.close(fd); + + // SOCKS5 greeting: version 5, 2 methods (no auth + username/password) + const hello = [_]u8{ + 0x05, // SOCKS5 + 0x02, // 2 methods + 0x00, // no auth + 0x02, // username/password + }; + _ = std.posix.write(fd, &hello) catch return; + + var buf: [4]u8 = undefined; + const n = std.posix.read(fd, &buf) catch return; + if (n < 2) return; + + if (buf[0] == 0x05) { + const auth_str: []const u8 = switch (buf[1]) { + 0x00 => "No authentication", + 0x02 => "Username/password required", + 0xFF => "No acceptable methods", + else => "Unknown method", + }; + hs.add("socks-auth-info", auth_str); + } else if (buf[0] == 0x04) { + hs.add("socks-auth-info", "SOCKS4 (no SOCKS5 support)"); + } +} + // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- @@ -626,3 +1030,100 @@ fn formatIp(buf: []u8, ip: u32) []const u8 { }; return std.fmt.bufPrint(buf, "{d}.{d}.{d}.{d}", .{ b[0], b[1], b[2], b[3] }) catch "?.?.?.?"; } + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +test "HostScripts - add and retrieve" { + var hs = HostScripts{}; + try std.testing.expectEqual(@as(u8, 0), hs.count); + + hs.add("test-script", "test output"); + try std.testing.expectEqual(@as(u8, 1), hs.count); + try std.testing.expectEqualStrings("test-script", hs.results[0].id()); + try std.testing.expectEqualStrings("test output", hs.results[0].output()); +} + +test "HostScripts - max 12 results" { + var hs = HostScripts{}; + for (0..15) |_| { + hs.add("s", "o"); + } + try std.testing.expectEqual(@as(u8, 12), hs.count); +} + +test "findCaseInsensitive - basic match" { + const data = "Hello World"; + try std.testing.expectEqual(@as(?usize, 0), findCaseInsensitive(data, "hello")); + try std.testing.expectEqual(@as(?usize, 6), findCaseInsensitive(data, "WORLD")); + try std.testing.expectEqual(@as(?usize, null), findCaseInsensitive(data, "xyz")); +} + +test "findCaseInsensitive - empty needle" { + const data = "test"; + try std.testing.expectEqual(@as(?usize, 0), findCaseInsensitive(data, "")); +} + +test "findTitle - extracts title" { + const data = "HTTP/1.1 200 OK\r\n\r\n<html><title>My Page"; + const title = findTitle(data); + try std.testing.expect(title != null); + try std.testing.expectEqualStrings("My Page", title.?); +} + +test "findTitle - no title" { + const data = "HTTP/1.1 200 OK\r\n\r\nHello"; + try std.testing.expectEqual(@as(?[]const u8, null), findTitle(data)); +} + +test "findLdapString - finds attribute value" { + // Simulated LDAP response fragment with attribute name followed by OCTET STRING value + // Layout: some BER overhead, then "defaultNamingContext" as text, then 0x04 tag with value + const data = [_]u8{ + 0x30, 0x20, 0x04, 0x15, + 'd', 'e', 'f', 'a', + 'u', 'l', 't', 'N', + 'a', 'm', 'i', 'n', + 'g', 'C', 'o', 'n', + 't', 'e', 'x', 't', + 0x00, 0x31, 0x0F, 0x04, + 0x0D, 'D', 'C', '=', + 't', 'e', 's', 't', + ',', 'D', 'C', '=', + 'c', 'o', + }; + + const result = findLdapString(&data, "defaultNamingContext"); + try std.testing.expect(result != null); + try std.testing.expect(result.?.len > 0); +} + +test "findLdapString - not found" { + const data = [_]u8{ 0x30, 0x05, 0x02, 0x01, 0x01, 0x04, 0x00 }; + const result = findLdapString(&data, "nonExistentAttr"); + try std.testing.expectEqual(@as(?[]const u8, null), result); +} + +test "findLdapString - non-printable value skipped" { + // Attribute name found, but next OCTET STRING contains non-printable bytes + const data = [_]u8{ + 'd', 'n', 's', 'H', 'o', 's', 't', 'N', 'a', 'm', 'e', + 0x04, 0x03, 0x01, 0x02, 0x03, + }; + const result = findLdapString(&data, "dnsHostName"); + try std.testing.expectEqual(@as(?[]const u8, null), result); +} + +test "formatIp - basic" { + var buf: [16]u8 = undefined; + const result = formatIp(&buf, 0xC0A80001); // 192.168.0.1 + try std.testing.expectEqualStrings("192.168.0.1", result); +} + +test "toLower - letters and non-letters" { + try std.testing.expectEqual(@as(u8, 'a'), toLower('A')); + try std.testing.expectEqual(@as(u8, 'z'), toLower('Z')); + try std.testing.expectEqual(@as(u8, 'a'), toLower('a')); + try std.testing.expectEqual(@as(u8, '1'), toLower('1')); +} diff --git a/src/sigs.zig b/src/sigs.zig index 80ddf8a..d193396 100644 --- a/src/sigs.zig +++ b/src/sigs.zig @@ -55,7 +55,7 @@ fn matchAgainst(data: []const u8, sigs: []const Sig) ?Match { // --------------------------------------------------------------------------- fn countSigs(comptime cat: Category) comptime_int { - @setEvalBranchQuota(4000); + @setEvalBranchQuota(20000); var section: Category = .none; var count: usize = 0; var iter = std.mem.splitScalar(u8, probes_raw, '\n'); @@ -141,11 +141,11 @@ fn parseI8(comptime s: []const u8) i8 { // --------------------------------------------------------------------------- test "null probe signature count" { - try std.testing.expect(null_sigs.len == 5); + try std.testing.expect(null_sigs.len == 9); } test "http signature count" { - try std.testing.expect(http_sigs.len >= 30); + try std.testing.expect(http_sigs.len >= 70); } test "matchBanner - POP3" { @@ -214,3 +214,56 @@ test "matchHttp - no match" { const resp = "HTTP/1.1 200 OK\r\n\r\nMy App"; try std.testing.expect(matchHttp(resp) == null); } + +test "matchBanner - CouchDB" { + const m = matchBanner("{\"couchdb\":\"Welcome\",\"version\":\"3.3.2\"}\n") orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("CouchDB", m.name); + try std.testing.expectEqualStrings("", m.version); +} + +test "matchBanner - Asterisk" { + const m = matchBanner("Asterisk Call Manager/6.0.1\r\n") orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("Asterisk", m.name); + try std.testing.expectEqualStrings("6.0.1", m.version); +} + +test "matchBanner - TeamSpeak" { + const m = matchBanner("TS3\r\n") orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("TeamSpeak", m.name); + try std.testing.expectEqualStrings("", m.version); +} + +test "matchBanner - RethinkDB" { + const m = matchBanner("{\"success\":true,\"server\":\"RethinkDB\"}\n") orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("RethinkDB", m.name); +} + +test "matchHttp - Tomcat" { + const resp = "HTTP/1.1 200 OK\r\n\r\nApache Tomcat/10.1.7"; + const m = matchHttp(resp) orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("Tomcat", m.name); +} + +test "matchHttp - Docker Registry header" { + const resp = "HTTP/1.1 200 OK\r\nDocker-Distribution-Api-Version: registry/2.0\r\n\r\n{}"; + const m = matchHttp(resp) orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("Docker Registry", m.name); +} + +test "matchHttp - Spring Boot header" { + const resp = "HTTP/1.1 200 OK\r\nX-Application-Context: myapp\r\n\r\n"; + const m = matchHttp(resp) orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("Spring Boot", m.name); +} + +test "matchHttp - Werkzeug header" { + const resp = "HTTP/1.1 200 OK\r\nServer: Werkzeug/2.3.7 Python/3.11.4\r\n\r\n"; + const m = matchHttp(resp) orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("Werkzeug", m.name); +} + +test "matchHttp - Uptime Kuma title" { + const resp = "HTTP/1.1 200 OK\r\n\r\nUptime Kuma"; + const m = matchHttp(resp) orelse return error.TestExpectedMatch; + try std.testing.expectEqualStrings("Uptime Kuma", m.name); +}