package scanner import ( "context" "encoding/binary" "math/rand/v2" "net" "net/netip" "os" "strings" "sync" "time" "golang.org/x/net/dns/dnsmessage" ) // reverseDNS looks up PTR records via the system resolver. func reverseDNS(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string { var mu sync.Mutex res := make(map[netip.Addr]string) sem := make(chan struct{}, 32) var wg sync.WaitGroup for _, ip := range ips { sem <- struct{}{} wg.Add(1) go func(ip netip.Addr) { defer func() { <-sem; wg.Done() }() lctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() names, err := net.DefaultResolver.LookupAddr(lctx, ip.String()) if err != nil || len(names) == 0 { return } mu.Lock() res[ip] = cleanHostname(names[0]) mu.Unlock() }(ip) } wg.Wait() return res } // mdnsReverse asks every host directly (unicast to port 5353) for its own // name. Apple devices and Linux machines running Avahi answer these queries. func mdnsReverse(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string { conn, err := net.ListenUDP("udp4", nil) if err != nil { return nil } defer conn.Close() context.AfterFunc(ctx, func() { conn.Close() }) for _, ip := range ips { q, err := question(reverseName(ip), dnsmessage.TypePTR) if err != nil { continue } if b, err := buildQuery(uint16(rand.N(0xffff)+1), q); err == nil { conn.WriteToUDPAddrPort(b, netip.AddrPortFrom(ip, 5353)) } } res := make(map[netip.Addr]string) conn.SetReadDeadline(time.Now().Add(timeout)) buf := make([]byte, 9000) for len(res) < len(ips) { n, from, err := conn.ReadFromUDPAddrPort(buf) if err != nil { break } for _, rr := range parseRecords(buf[:n]) { ptr, ok := rr.Body.(*dnsmessage.PTRResource) if !ok { continue } ip, ok := parseReverseName(rr.Header.Name.String()) if !ok { ip = from.Addr().Unmap() } res[ip] = cleanHostname(ptr.PTR.String()) } } return res } // netbiosNames sends NetBIOS node status requests (UDP 137), which Windows // machines and Samba servers answer with their computer name. func netbiosNames(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string { conn, err := net.ListenUDP("udp4", nil) if err != nil { return nil } defer conn.Close() context.AfterFunc(ctx, func() { conn.Close() }) for _, ip := range ips { conn.WriteToUDPAddrPort(nbstatRequest(uint16(rand.N(0xffff))), netip.AddrPortFrom(ip, 137)) } res := make(map[netip.Addr]string) conn.SetReadDeadline(time.Now().Add(timeout)) buf := make([]byte, 1500) for len(res) < len(ips) { n, from, err := conn.ReadFromUDPAddrPort(buf) if err != nil { break } if name, ok := parseNBStat(buf[:n]); ok { res[from.Addr().Unmap()] = name } } return res } func nbstatRequest(id uint16) []byte { b := []byte{byte(id >> 8), byte(id), 0, 0, 0, 1, 0, 0, 0, 0, 0, 0} // The wildcard name "*" padded to 16 bytes, first-level encoded. b = append(b, 0x20) name := [16]byte{'*'} for _, c := range name { b = append(b, 'A'+c>>4, 'A'+c&0x0f) } return append(b, 0, 0x00, 0x21, 0x00, 0x01) // NBSTAT, IN } // parseNBStat extracts the unique workstation name from a node status response. func parseNBStat(b []byte) (string, bool) { if len(b) < 12 || b[2]&0x80 == 0 { return "", false } qd := int(binary.BigEndian.Uint16(b[4:6])) an := int(binary.BigEndian.Uint16(b[6:8])) off := 12 for range qd { off = skipDNSName(b, off) + 4 } if an == 0 { return "", false } off = skipDNSName(b, off) if off+10 > len(b) || binary.BigEndian.Uint16(b[off:]) != 0x21 { return "", false } off += 10 if off >= len(b) { return "", false } num := int(b[off]) off++ for i := 0; i < num && off+18 <= len(b); i++ { name := strings.TrimRight(string(b[off:off+15]), " \x00") suffix := b[off+15] group := binary.BigEndian.Uint16(b[off+16:])&0x8000 != 0 off += 18 if suffix == 0x00 && !group && name != "" { return name, true } } return "", false } func skipDNSName(b []byte, off int) int { for off < len(b) { l := int(b[off]) switch { case l == 0: return off + 1 case l&0xc0 == 0xc0: return off + 2 } off += 1 + l } return len(b) } func localHostname() string { h, err := os.Hostname() if err != nil { return "" } return cleanHostname(h) }