diff --git a/go.mod b/go.mod index 9e04cdf..fac9fcd 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module podux go 1.25.5 require ( - github.com/fatedier/frp v0.68.0 + github.com/fatedier/frp v0.67.0 github.com/pelletier/go-toml/v2 v2.2.0 github.com/pocketbase/dbx v1.11.0 github.com/pocketbase/pocketbase v0.35.0 @@ -26,6 +26,7 @@ require ( github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect github.com/golang-jwt/jwt/v5 v5.3.0 // indirect github.com/golang/snappy v0.0.4 // indirect + github.com/google/gopacket v1.1.19 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/mux v1.8.1 // indirect github.com/hashicorp/yamux v0.1.1 // indirect diff --git a/go.sum b/go.sum index 3d0a66a..e1e1afe 100644 --- a/go.sum +++ b/go.sum @@ -27,8 +27,6 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatedier/frp v0.67.0 h1:w6xHLkruAJcq+fZP9VOiY6w/FBy/wB1aPqA4frs98K8= github.com/fatedier/frp v0.67.0/go.mod h1:0Q3mAI0c9WtAsgMQpTQhinWTKa2Qp121YWsqaFu41Zg= -github.com/fatedier/frp v0.68.0 h1:woKC31EpgCLQDirRAOAUgHP3IRxLu2mBHS6zGpcw7tw= -github.com/fatedier/frp v0.68.0/go.mod h1:qFdez6Z+RDqoqF1xJhh48+IW91SVQ+pNWnrmcl43Wjs= github.com/fatedier/golib v0.5.1 h1:hcKAnaw5mdI/1KWRGejxR+i1Hn/NvbY5UsMKDr7o13M= github.com/fatedier/golib v0.5.1/go.mod h1:W6kIYkIFxHsTzbgqg5piCxIiDo4LzwgTY6R5W8l9NFQ= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= @@ -69,6 +67,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8= +github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo= github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d h1:KJIErDwbSHjnp/SGzE5ed8Aol7JsKiI5X7yWKAtzhM0= github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -165,6 +165,7 @@ go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= @@ -181,6 +182,8 @@ golang.org/x/image v0.34.0/go.mod h1:2RNFBZRB+vnwwFil8GkMdRvrJOFd1AzdZI6vOY+eJVU golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= @@ -251,11 +254,13 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3 golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg= golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= diff --git a/internal/application/scanner/service.go b/internal/application/scanner/service.go new file mode 100644 index 0000000..32dac35 --- /dev/null +++ b/internal/application/scanner/service.go @@ -0,0 +1,570 @@ +package scanner + +import ( + "bufio" + "context" + "errors" + "net" + "os" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/google/gopacket" + "github.com/google/gopacket/afpacket" + "github.com/google/gopacket/layers" +) + +// Device represents a discovered LAN host. +type Device struct { + IP string `json:"ip"` + MAC string `json:"mac"` + Hostname string `json:"hostname"` + Interface string `json:"interface"` +} + +// LocalNetwork describes one scannable subnet on this host. +type LocalNetwork struct { + Interface string `json:"interface"` + CIDR string `json:"cidr"` + Hosts int `json:"hosts"` +} + +// PortResult is the result of scanning a single TCP port. +type PortResult struct { + Port int `json:"port"` + Open bool `json:"open"` + Service string `json:"service"` + Done bool `json:"done,omitempty"` // signals end-of-stream +} + +// wellKnownPorts maps port numbers to service names. +var wellKnownPorts = map[int]string{ + 21: "FTP", + 22: "SSH", + 23: "Telnet", + 25: "SMTP", + 53: "DNS", + 80: "HTTP", + 110: "POP3", + 143: "IMAP", + 443: "HTTPS", + 445: "SMB", + 1433: "MSSQL", + 1521: "Oracle", + 3306: "MySQL", + 3389: "RDP", + 5432: "PostgreSQL", + 5900: "VNC", + 6379: "Redis", + 8080: "HTTP-Alt", + 8443: "HTTPS-Alt", + 8888: "HTTP-Dev", + 9200: "Elasticsearch", + 11211: "Memcached", + 27017: "MongoDB", +} + +// CommonPorts is the default port list for port scanning. +var CommonPorts = func() []int { + ports := make([]int, 0, len(wellKnownPorts)) + for p := range wellKnownPorts { + ports = append(ports, p) + } + return ports +}() + +// hostProbePorts are the ports tried when checking whether a host is alive +// without ARP (TCP fallback mode). +var hostProbePorts = []int{22, 80, 443, 445, 3389, 8080, 8443} + +// maxPrefixLen is the smallest prefix we will scan (/20 = 4094 hosts max). +// Subnets larger than this (e.g. Docker /16) are skipped automatically. +const maxPrefixLen = 20 + +// Service provides LAN discovery and port-scan capabilities. +type Service struct{} + +func NewService() *Service { return &Service{} } + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +// GetLocalNetworks returns the subnets that will be scanned. +func (s *Service) GetLocalNetworks() []LocalNetwork { + var out []LocalNetwork + for _, iface := range upInterfaces() { + addrs, _ := iface.Addrs() + for _, addr := range addrs { + ipNet, ok := addr.(*net.IPNet) + if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() { + continue + } + ones, _ := ipNet.Mask.Size() + if ones < maxPrefixLen { + continue + } + hosts := (1 << (32 - ones)) - 2 + out = append(out, LocalNetwork{ + Interface: iface.Name, + CIDR: ipNet.String(), + Hosts: hosts, + }) + } + } + return out +} + +// DiscoverDevices scans local subnets for active hosts. +// It first attempts a gopacket/afpacket ARP sweep (requires CAP_NET_RAW). +// If that is unavailable it falls back to TCP-connect probing + reading the +// kernel ARP cache from /proc/net/arp. +func (s *Service) DiscoverDevices(ctx context.Context) ([]Device, error) { + ifaces := upInterfaces() + if len(ifaces) == 0 { + return []Device{}, nil + } + + // Try ARP sweep on first suitable interface; if permission denied use TCP. + devices, err := s.arpDiscover(ctx, ifaces) + if err != nil { + if isPermissionDenied(err) { + return s.tcpDiscover(ctx, ifaces) + } + return nil, err + } + return devices, nil +} + +// ScanPorts does a concurrent TCP-connect scan on ip for ports. +// Results are written to ch; the caller must close ch after this returns. +func (s *Service) ScanPorts(ctx context.Context, ip string, ports []int, ch chan<- PortResult) { + const concurrency = 200 + sem := make(chan struct{}, concurrency) + var wg sync.WaitGroup + + for _, port := range ports { + if ctx.Err() != nil { + break + } + sem <- struct{}{} + wg.Add(1) + go func(p int) { + defer wg.Done() + defer func() { <-sem }() + + addr := net.JoinHostPort(ip, strconv.Itoa(p)) + conn, err := net.DialTimeout("tcp", addr, 500*time.Millisecond) + open := err == nil + if conn != nil { + conn.Close() + } + + result := PortResult{Port: p, Open: open} + if open { + result.Service = wellKnownPorts[p] + } + select { + case ch <- result: + case <-ctx.Done(): + } + }(port) + } + wg.Wait() +} + +// --------------------------------------------------------------------------- +// ARP-based discovery (gopacket + afpacket, needs CAP_NET_RAW) +// --------------------------------------------------------------------------- + +func (s *Service) arpDiscover(ctx context.Context, ifaces []net.Interface) ([]Device, error) { + var ( + mu sync.Mutex + wg sync.WaitGroup + devices = make([]Device, 0) + seen = map[string]bool{} + lastErr error + ) + + for _, iface := range ifaces { + if len(iface.HardwareAddr) == 0 { + continue + } + addrs, _ := iface.Addrs() + for _, addr := range addrs { + ipNet, ok := addr.(*net.IPNet) + if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() { + continue + } + ones, _ := ipNet.Mask.Size() + if ones < maxPrefixLen { + continue // skip huge subnets like Docker /16 + } + + wg.Add(1) + go func(iface net.Interface, ip net.IP, network *net.IPNet) { + defer wg.Done() + found, err := arpSweep(ctx, iface, ip, network) + if err != nil { + mu.Lock() + lastErr = err + mu.Unlock() + return + } + mu.Lock() + for _, d := range found { + if !seen[d.IP] { + seen[d.IP] = true + devices = append(devices, d) + } + } + mu.Unlock() + }(iface, ipNet.IP, ipNet) + } + } + + wg.Wait() + + if len(devices) == 0 && lastErr != nil { + return nil, lastErr + } + return devices, nil +} + +func arpSweep(ctx context.Context, iface net.Interface, src net.IP, network *net.IPNet) ([]Device, error) { + handle, err := afpacket.NewTPacket( + afpacket.OptInterface(iface.Name), + afpacket.OptBlockTimeout(5*time.Millisecond), + ) + if err != nil { + return nil, err + } + + sweepCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + results := make(chan Device, 512) + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + captureARP(sweepCtx, handle, results) + close(results) + }() + + sendARP(sweepCtx, handle, iface, src, network) + + <-sweepCtx.Done() + handle.Close() + wg.Wait() + + selfIP := src.String() + var devices []Device + seen := map[string]bool{selfIP: true} + for d := range results { + if seen[d.IP] { + continue + } + seen[d.IP] = true + d.Interface = iface.Name + if names, err := net.LookupAddr(d.IP); err == nil && len(names) > 0 { + d.Hostname = strings.TrimSuffix(names[0], ".") + } + devices = append(devices, d) + } + return devices, nil +} + +func captureARP(ctx context.Context, handle *afpacket.TPacket, out chan<- Device) { + pktSrc := gopacket.NewPacketSource(handle, layers.LinkTypeEthernet) + pktSrc.NoCopy = true + for { + select { + case <-ctx.Done(): + return + default: + } + pkt, err := pktSrc.NextPacket() + if err != nil { + if ctx.Err() != nil { + return + } + continue + } + arpLayer := pkt.Layer(layers.LayerTypeARP) + if arpLayer == nil { + continue + } + arp := arpLayer.(*layers.ARP) + if arp.Operation != layers.ARPReply { + continue + } + ip := net.IP(arp.SourceProtAddress).String() + mac := net.HardwareAddr(arp.SourceHwAddress).String() + select { + case out <- Device{IP: ip, MAC: mac}: + default: + } + } +} + +func sendARP(ctx context.Context, handle *afpacket.TPacket, iface net.Interface, src net.IP, network *net.IPNet) { + eth := layers.Ethernet{ + SrcMAC: iface.HardwareAddr, + DstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, + EthernetType: layers.EthernetTypeARP, + } + arp := layers.ARP{ + AddrType: layers.LinkTypeEthernet, + Protocol: layers.EthernetTypeIPv4, + HwAddressSize: 6, + ProtAddressSize: 4, + Operation: layers.ARPRequest, + SourceHwAddress: []byte(iface.HardwareAddr), + SourceProtAddress: []byte(src.To4()), + DstHwAddress: []byte{0, 0, 0, 0, 0, 0}, + } + buf := gopacket.NewSerializeBuffer() + opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true} + + for ip := cloneIP(network.IP.Mask(network.Mask)); network.Contains(ip); incrementIP(ip) { + select { + case <-ctx.Done(): + return + default: + } + target := make(net.IP, 4) + copy(target, ip.To4()) + arp.DstProtAddress = target + if err := gopacket.SerializeLayers(buf, opts, ð, &arp); err != nil { + continue + } + _ = handle.WritePacketData(buf.Bytes()) + time.Sleep(500 * time.Microsecond) + } +} + +// --------------------------------------------------------------------------- +// TCP-based host discovery fallback (no special privileges required) +// --------------------------------------------------------------------------- + +// tcpDiscover probes each host in every local subnet using TCP connect. +// A host is "alive" if any probe port responds (open or connection refused). +// After the sweep it enriches results with MAC addresses from /proc/net/arp. +func (s *Service) tcpDiscover(ctx context.Context, ifaces []net.Interface) ([]Device, error) { + type result struct { + ip string + iface string + } + + resultCh := make(chan result, 512) + var sweepWg sync.WaitGroup + + const hostConcurrency = 100 + + for _, iface := range ifaces { + addrs, _ := iface.Addrs() + for _, addr := range addrs { + ipNet, ok := addr.(*net.IPNet) + if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() { + continue + } + ones, _ := ipNet.Mask.Size() + if ones < maxPrefixLen { + continue + } + + // Enumerate all host addresses in this subnet. + var ips []string + selfIP := ipNet.IP.String() + for ip := cloneIP(ipNet.IP.Mask(ipNet.Mask)); ipNet.Contains(ip); incrementIP(ip) { + candidate := ip.String() + if candidate == selfIP { + continue + } + ips = append(ips, candidate) + } + + sweepWg.Add(1) + go func(ifaceName string, ips []string) { + defer sweepWg.Done() + sem := make(chan struct{}, hostConcurrency) + var wg sync.WaitGroup + for _, ip := range ips { + if ctx.Err() != nil { + break + } + sem <- struct{}{} + wg.Add(1) + go func(ip string) { + defer wg.Done() + defer func() { <-sem }() + if isHostAlive(ctx, ip) { + select { + case resultCh <- result{ip: ip, iface: ifaceName}: + case <-ctx.Done(): + } + } + }(ip) + } + wg.Wait() + }(iface.Name, ips) + } + } + + // Close resultCh once all sweeps complete. + go func() { + sweepWg.Wait() + close(resultCh) + }() + + // Collect results. + arpCache := readARPCache() + devices := make([]Device, 0) + seen := map[string]bool{} + + for r := range resultCh { + if seen[r.ip] { + continue + } + seen[r.ip] = true + d := Device{IP: r.ip, Interface: r.iface} + if mac, ok := arpCache[r.ip]; ok { + d.MAC = mac + } + if names, err := net.LookupAddr(r.ip); err == nil && len(names) > 0 { + d.Hostname = strings.TrimSuffix(names[0], ".") + } + devices = append(devices, d) + } + return devices, nil +} + +// isHostAlive returns true if the host has any TCP port open or actively +// refusing connections (which proves the host is up). +func isHostAlive(ctx context.Context, ip string) bool { + ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + + found := make(chan struct{}, 1) + var wg sync.WaitGroup + for _, port := range hostProbePorts { + wg.Add(1) + go func(p int) { + defer wg.Done() + addr := net.JoinHostPort(ip, strconv.Itoa(p)) + d := net.Dialer{} + conn, err := d.DialContext(ctx, "tcp", addr) + if conn != nil { + conn.Close() + } + if err == nil || isConnRefused(err) { + select { + case found <- struct{}{}: + default: + } + cancel() + } + }(port) + } + wg.Wait() + select { + case <-found: + return true + default: + return false + } +} + +// isConnRefused checks whether err is ECONNREFUSED (host alive, port closed). +func isConnRefused(err error) bool { + if err == nil { + return false + } + var opErr *net.OpError + if !errors.As(err, &opErr) { + return false + } + var syscallErr *os.SyscallError + if !errors.As(opErr.Err, &syscallErr) { + return false + } + errno, ok := syscallErr.Err.(syscall.Errno) + return ok && errno == syscall.ECONNREFUSED +} + +// readARPCache parses /proc/net/arp and returns an ip→mac map. +func readARPCache() map[string]string { + f, err := os.Open("/proc/net/arp") + if err != nil { + return map[string]string{} + } + defer f.Close() + + cache := map[string]string{} + scanner := bufio.NewScanner(f) + scanner.Scan() // skip header line + for scanner.Scan() { + fields := strings.Fields(scanner.Text()) + if len(fields) < 4 { + continue + } + ip := fields[0] + mac := fields[3] + if mac == "00:00:00:00:00:00" { + continue + } + cache[ip] = mac + } + return cache +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +func upInterfaces() []net.Interface { + ifaces, err := net.Interfaces() + if err != nil { + return nil + } + var out []net.Interface + for _, iface := range ifaces { + if iface.Flags&net.FlagLoopback != 0 { + continue + } + if iface.Flags&net.FlagUp == 0 { + continue + } + out = append(out, iface) + } + return out +} + +func isPermissionDenied(err error) bool { + if err == nil { + return false + } + s := strings.ToLower(err.Error()) + return strings.Contains(s, "permission denied") || + strings.Contains(s, "operation not permitted") +} + +func cloneIP(ip net.IP) net.IP { + clone := make(net.IP, len(ip)) + copy(clone, ip) + return clone +} + +func incrementIP(ip net.IP) { + for i := len(ip) - 1; i >= 0; i-- { + ip[i]++ + if ip[i] != 0 { + break + } + } +} diff --git a/internal/interfaces/http/scanner_handler.go b/internal/interfaces/http/scanner_handler.go new file mode 100644 index 0000000..2071372 --- /dev/null +++ b/internal/interfaces/http/scanner_handler.go @@ -0,0 +1,131 @@ +package httphandler + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "strconv" + "strings" + + "podux/internal/application/scanner" + "podux/pkg/response" + + "github.com/pocketbase/pocketbase/core" +) + +type ScannerHandler struct { + app core.App + service *scanner.Service +} + +func NewScannerHandler(app core.App, service *scanner.Service) *ScannerHandler { + return &ScannerHandler{app: app, service: service} +} + +func (h *ScannerHandler) RegisterHandlers(e *core.ServeEvent) { + // GET /api/scanner/interfaces + // Returns local networks that will be scanned. + e.Router.GET("/api/scanner/interfaces", requireAuth(func(e *core.RequestEvent) error { + return e.JSON(200, h.service.GetLocalNetworks()) + }, h.app)) + + // GET /api/scanner/discover + // ARP-sweep local network, returns discovered hosts. + e.Router.GET("/api/scanner/discover", requireAuth(func(e *core.RequestEvent) error { + ctx := e.Request.Context() + devices, err := h.service.DiscoverDevices(ctx) + if err != nil { + h.app.Logger().Error("LAN discovery failed", "error", err) + return e.JSON(500, response.Error(err)) + } + return e.JSON(200, devices) + }, h.app)) + + // GET /api/scanner/ports/stream?ip=[&ports=] + // Streams port-scan results as Server-Sent Events. + e.Router.GET("/api/scanner/ports/stream", requireAuth(func(e *core.RequestEvent) error { + q := e.Request.URL.Query() + ip := q.Get("ip") + if ip == "" { + return e.JSON(400, response.Error(fmt.Errorf("ip is required"))) + } + if net.ParseIP(ip) == nil { + return e.JSON(400, response.Error(fmt.Errorf("invalid ip address"))) + } + + var ports []int + switch { + case q.Get("full") == "true": + ports = allPorts() + case q.Get("ports") != "": + ports = parsePortList(q.Get("ports")) + default: + ports = scanner.CommonPorts + } + + w := e.Response + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + + flusher, ok := w.(http.Flusher) + if !ok { + return e.JSON(500, response.Error(fmt.Errorf("streaming not supported"))) + } + + ctx, cancel := context.WithCancel(e.Request.Context()) + defer cancel() + + results := make(chan scanner.PortResult, 128) + + go func() { + defer close(results) + h.service.ScanPorts(ctx, ip, ports, results) + }() + + for res := range results { + data, err := json.Marshal(res) + if err != nil { + continue + } + fmt.Fprintf(w, "data: %s\n\n", data) + flusher.Flush() + } + + // Signal completion + done, _ := json.Marshal(scanner.PortResult{Done: true}) + fmt.Fprintf(w, "data: %s\n\n", done) + flusher.Flush() + + return nil + }, h.app)) +} + +// allPorts returns every valid TCP port (1-65535). +func allPorts() []int { + ports := make([]int, 65535) + for i := range ports { + ports[i] = i + 1 + } + return ports +} + +// parsePortList parses a comma-separated list of port numbers. +func parsePortList(s string) []int { + if s == "" { + return nil + } + var ports []int + for _, part := range strings.Split(s, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + if n, err := strconv.Atoi(part); err == nil && n > 0 && n <= 65535 { + ports = append(ports, n) + } + } + return ports +} diff --git a/main.go b/main.go index 5ae75d1..4bee53f 100644 --- a/main.go +++ b/main.go @@ -11,6 +11,7 @@ import ( "podux/internal/application/importer" "podux/internal/application/monitoring" "podux/internal/application/proxy" + "podux/internal/application/scanner" "podux/internal/application/server" "podux/internal/application/system" "podux/internal/application/version" @@ -51,11 +52,13 @@ func main() { networkMonitorService := monitoring.NewMonitorService(app, geoService, metricsService) importService := importer.NewService(app) versionService := version.NewService(app) + scannerService := scanner.NewService() //githubService := github.NewService(app) // HTTP Handlers //githubHandler := httphandler.NewGithubHandler(app, githubService) frpcHandler := httphandler.NewFrpcHandler(app, frpcService) + scannerHandler := httphandler.NewScannerHandler(app, scannerService) versionHandler := httphandler.NewVersionHandler(app, versionService) dashboardHandler := httphandler.NewDashboardHandler(dashboardService) systemHandler := httphandler.NewSystemHandler(app, settingsService) @@ -100,6 +103,7 @@ func main() { systemHandler.RegisterHandlers(e) importHandler.RegisterHandlers(e) serverHandler.RegisterHandlers(e) + scannerHandler.RegisterHandlers(e) // Serve static files from embedded FS content, err := fs.Sub(pbPublicDir, "pb_public") diff --git a/site/src/App.tsx b/site/src/App.tsx index c14ed88..dfce0b9 100644 --- a/site/src/App.tsx +++ b/site/src/App.tsx @@ -32,6 +32,9 @@ const ServerFormPage = lazy(() => const ServerLogPage = lazy(() => import("./pages/ServerLog/ServerLogPage").then((m) => ({ default: m.ServerLogPage })) ); +const ScannerPage = lazy(() => + import("./pages/Scanner").then((m) => ({ default: m.ScannerPage })) +); function AuthenticatedLayout() { console.log("AuthenticatedLayout rendered"); @@ -77,6 +80,7 @@ function App() { } /> } /> } /> + } /> {/* } /> */} diff --git a/site/src/layouts/MainLayout.tsx b/site/src/layouts/MainLayout.tsx index 09a1400..b25005b 100644 --- a/site/src/layouts/MainLayout.tsx +++ b/site/src/layouts/MainLayout.tsx @@ -62,6 +62,11 @@ const navItems = [ path: "/proxies", icon: , }, + { + labelKey: "nav.scanner", + path: "/scanner", + icon: , + }, ]; const mobileBottomNavItems = navItems; diff --git a/site/src/locales/en.json b/site/src/locales/en.json index bbf43b0..87e2ed9 100644 --- a/site/src/locales/en.json +++ b/site/src/locales/en.json @@ -40,7 +40,8 @@ "logout": "Logout", "pbAdmin": "Admin Panel", "version": "Version", - "import": "Import" + "import": "Import", + "scanner": "Scanner" }, "auth": { "login": "Login", @@ -487,5 +488,38 @@ "setupFailed": "Failed to initialize system. Please try again.", "settingsCreateFailed": "Failed to initialize system settings" } + }, + "scanner": { + "title": "LAN Scanner", + "description": "Discover devices on your local network and scan their open ports", + "step1Title": "Step 1 — Device Discovery", + "step1Desc": "Scan your local network for active hosts using ARP. Requires root / CAP_NET_RAW on the server.", + "discovering": "Scanning...", + "discoverBtn": "Start Discovery", + "devicesFound": "{{count}} device(s) found", + "hosts": "hosts", + "ipAddress": "IP Address", + "macAddress": "MAC Address", + "hostname": "Hostname", + "iface": "Interface", + "scanPorts": "Scan Ports", + "scanTarget": "Target", + "startScan": "Start Port Scan", + "stop": "Stop", + "mode": "Mode", + "modeCommon": "Common", + "modeCustom": "Custom", + "modeFull": "All ports", + "customPorts": "Custom ports", + "customPortsPlaceholder": "e.g. 22,80,443,8080", + "customPortsHint": "Comma-separated port numbers", + "fullScanWarning": "Scanning all 65535 ports will take several minutes. The results will stream in real time.", + "scanned": "Scanned", + "openPorts": "Open", + "complete": "Done", + "port": "Port", + "status": "Status", + "service": "Service", + "open": "Open" } } \ No newline at end of file diff --git a/site/src/locales/zh.json b/site/src/locales/zh.json index c36411c..d0e27b6 100644 --- a/site/src/locales/zh.json +++ b/site/src/locales/zh.json @@ -40,7 +40,8 @@ "logout": "退出登录", "pbAdmin": "后台管理", "version": "版本", - "import": "导入" + "import": "导入", + "scanner": "局域网扫描" }, "auth": { "login": "登录", @@ -487,5 +488,38 @@ "setupFailed": "系统初始化失败。请重试。", "settingsCreateFailed": "初始化系统设置失败" } + }, + "scanner": { + "title": "局域网扫描", + "description": "发现局域网内的在线设备并扫描其开放端口", + "step1Title": "第一步 — 设备发现", + "step1Desc": "使用 ARP 扫描本地网络中的活跃主机。服务器需要 root 权限或 CAP_NET_RAW 能力。", + "discovering": "扫描中...", + "discoverBtn": "开始发现", + "devicesFound": "发现 {{count}} 台设备", + "hosts": "台主机", + "ipAddress": "IP 地址", + "macAddress": "MAC 地址", + "hostname": "主机名", + "iface": "网口", + "scanPorts": "扫描端口", + "scanTarget": "目标", + "startScan": "开始端口扫描", + "stop": "停止", + "mode": "模式", + "modeCommon": "常用端口", + "modeCustom": "自定义", + "modeFull": "全部端口", + "customPorts": "自定义端口", + "customPortsPlaceholder": "例如 22,80,443,8080", + "customPortsHint": "用逗号分隔端口号", + "fullScanWarning": "扫描全部 65535 个端口将耗时数分钟,结果会实时流式显示。", + "scanned": "已扫描", + "openPorts": "开放", + "complete": "完成", + "port": "端口", + "status": "状态", + "service": "服务", + "open": "开放" } } \ No newline at end of file diff --git a/site/src/pages/Scanner/ScannerPage.view.tsx b/site/src/pages/Scanner/ScannerPage.view.tsx new file mode 100644 index 0000000..2786e84 --- /dev/null +++ b/site/src/pages/Scanner/ScannerPage.view.tsx @@ -0,0 +1,407 @@ +import { + Badge, + Box, + Button, + Card, + Callout, + Flex, + Spinner, + Table, + Text, + TextField, + SegmentedControl, + Progress, +} from "@radix-ui/themes"; +import { useState, useEffect } from "react"; +import { Icon } from "@iconify/react"; +import { motion, AnimatePresence } from "framer-motion"; +import { useTranslation } from "react-i18next"; +import { PageHeader } from "../../components/PageHeader"; +import type { Device, LocalNetwork, PortResult, ScanMode, ScanStep } from "./useScanner"; + +interface ScannerViewProps { + step: ScanStep; + discovering: boolean; + devices: Device[]; + localNetworks: LocalNetwork[]; + selectedDevice: Device | null; + scanning: boolean; + portResults: PortResult[]; + scanDone: boolean; + error: string | null; + scanMode: ScanMode; + setScanMode: (m: ScanMode) => void; + customPorts: string; + setCustomPorts: (v: string) => void; + totalPorts: number; + discoverDevices: () => void; + selectDevice: (device: Device) => void; + startPortScan: () => void; + stopScan: () => void; + backToDiscover: () => void; +} + +export function ScannerView({ + step, + discovering, + devices, + localNetworks, + selectedDevice, + scanning, + portResults, + scanDone, + error, + scanMode, + setScanMode, + customPorts, + setCustomPorts, + totalPorts, + discoverDevices, + selectDevice, + startPortScan, + stopScan, + backToDiscover, +}: ScannerViewProps) { + const { t } = useTranslation(); + const [mounted, setMounted] = useState(false); + + useEffect(() => { + const timer = setTimeout(() => setMounted(true), 100); + return () => clearTimeout(timer); + }, []); + + const openPorts = portResults.filter((r) => r.open); + const scannedCount = portResults.length; + const progressPct = totalPorts > 0 ? Math.round((scannedCount / totalPorts) * 100) : 0; + + return ( + + + + + {error && ( + + + + + + {error} + + + )} + + + {/* ── Step 1: Device Discovery ── */} + {step === "discover" && ( + + + + + + + {t("scanner.step1Title")} + + {t("scanner.step1Desc")} + + {localNetworks.length > 0 && ( + + {localNetworks.map((n) => ( + + + {n.interface} · {n.cidr} · {n.hosts} {t("scanner.hosts")} + + ))} + + )} + + + + + + + {devices.length > 0 && ( + + + + + + + + {t("scanner.devicesFound", { count: devices.length })} + + + + {devices.length} {t("scanner.hosts")} + + + + + + + {t("scanner.ipAddress")} + {t("scanner.macAddress")} + {t("scanner.hostname")} + {t("scanner.iface")} + {t("common.actions")} + + + + {devices.map((device) => ( + + + + + + {device.ip} + + + + + + {device.mac || "—"} + + + + {device.hostname || "—"} + + + {device.interface || "—"} + + + + + + ))} + + + + + + )} + + + + )} + + {/* ── Step 2: Port Scanner ── */} + {step === "scan" && selectedDevice && ( + + + {/* Target + controls */} + + + {/* Row 1: back / target / start-stop */} + + + + + + + {t("scanner.scanTarget")}: {selectedDevice.ip} + + {selectedDevice.hostname && ( + {selectedDevice.hostname} + )} + + + + + {scanning ? ( + + ) : ( + + )} + + + + {/* Row 2: mode selector */} + + + {t("scanner.mode")}: + + setScanMode(v as ScanMode)} + disabled={scanning} + size="2" + > + + + + {t("scanner.modeCommon")} + + + + + + {t("scanner.modeCustom")} + + + + + + {t("scanner.modeFull")} + + + + + + {/* Row 3: custom ports input (only when mode=custom) */} + {scanMode === "custom" && ( + + + setCustomPorts(e.target.value)} + disabled={scanning} + /> + + {t("scanner.customPortsHint")} + + )} + + {/* Row 4: full-scan warning */} + {scanMode === "full" && ( + + + + + {t("scanner.fullScanWarning")} + + )} + + + + {/* Progress */} + {(scanning || scannedCount > 0) && ( + + + + {scanning && } + + {t("scanner.scanned")}: {scannedCount} + {totalPorts > 0 && ` / ${totalPorts}`} + + + + {t("scanner.openPorts")}: {openPorts.length} + + {scanDone && ( + + + {t("scanner.complete")} + + )} + + {totalPorts > 0 && ( + {progressPct}% + )} + + + {totalPorts > 0 && ( + + )} + + )} + + {/* Results */} + + {openPorts.length > 0 && ( + + + + + + {t("scanner.port")} + {t("scanner.status")} + {t("scanner.service")} + + + + {[...openPorts] + .sort((a, b) => a.port - b.port) + .map((r) => ( + + + + {r.port} + + + + + + {t("scanner.open")} + + + + {r.service || "—"} + + + ))} + + + + + )} + + + + )} + + ); +} diff --git a/site/src/pages/Scanner/index.tsx b/site/src/pages/Scanner/index.tsx new file mode 100644 index 0000000..9dabfa9 --- /dev/null +++ b/site/src/pages/Scanner/index.tsx @@ -0,0 +1,9 @@ +import { useScanner } from "./useScanner"; +import { ScannerView } from "./ScannerPage.view"; + +export function ScannerPage() { + const state = useScanner(); + return ; +} + +export default ScannerPage; diff --git a/site/src/pages/Scanner/useScanner.ts b/site/src/pages/Scanner/useScanner.ts new file mode 100644 index 0000000..4c727f7 --- /dev/null +++ b/site/src/pages/Scanner/useScanner.ts @@ -0,0 +1,161 @@ +import { useState, useRef, useCallback } from "react"; +import { apiGet } from "../../lib/api"; +import pb from "../../lib/pocketbase"; + +export interface Device { + ip: string; + mac: string; + hostname: string; + interface: string; +} + +export interface LocalNetwork { + interface: string; + cidr: string; + hosts: number; +} + +export interface PortResult { + port: number; + open: boolean; + service: string; + done?: boolean; +} + +export type ScanStep = "discover" | "scan"; +export type ScanMode = "common" | "custom" | "full"; + +const COMMON_PORT_COUNT = 23; // mirrors wellKnownPorts in service.go +const FULL_PORT_COUNT = 65535; + +export function useScanner() { + const [step, setStep] = useState("discover"); + const [discovering, setDiscovering] = useState(false); + const [devices, setDevices] = useState([]); + const [localNetworks, setLocalNetworks] = useState([]); + const [selectedDevice, setSelectedDevice] = useState(null); + const [scanning, setScanning] = useState(false); + const [portResults, setPortResults] = useState([]); + const [scanDone, setScanDone] = useState(false); + const [error, setError] = useState(null); + const [scanMode, setScanMode] = useState("common"); + const [customPorts, setCustomPorts] = useState(""); + const [totalPorts, setTotalPorts] = useState(0); + const esRef = useRef(null); + + const discoverDevices = useCallback(async () => { + setDiscovering(true); + setDevices([]); + setError(null); + try { + const [netRes, discoverRes] = await Promise.all([ + apiGet("/api/scanner/interfaces"), + apiGet("/api/scanner/discover"), + ]); + if (netRes.ok) { + const nets: LocalNetwork[] = await netRes.json(); + setLocalNetworks(nets ?? []); + } + if (!discoverRes.ok) { + const body = await discoverRes.json().catch(() => ({})); + throw new Error(body.error || `HTTP ${discoverRes.status}`); + } + const data: Device[] = await discoverRes.json(); + setDevices(data ?? []); + } catch (e: unknown) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setDiscovering(false); + } + }, []); + + const selectDevice = useCallback((device: Device) => { + setSelectedDevice(device); + setPortResults([]); + setScanDone(false); + setStep("scan"); + }, []); + + const startPortScan = useCallback(() => { + if (!selectedDevice) return; + esRef.current?.close(); + + setPortResults([]); + setScanDone(false); + setScanning(true); + setError(null); + + const token = pb.authStore.token; + const params = new URLSearchParams({ ip: selectedDevice.ip, token }); + + let total = COMMON_PORT_COUNT; + if (scanMode === "full") { + params.set("full", "true"); + total = FULL_PORT_COUNT; + } else if (scanMode === "custom" && customPorts.trim()) { + params.set("ports", customPorts.trim()); + total = customPorts.split(",").filter((p) => p.trim()).length; + } + setTotalPorts(total); + + const es = new EventSource(`/api/scanner/ports/stream?${params.toString()}`); + esRef.current = es; + + es.onmessage = (ev) => { + try { + const result: PortResult = JSON.parse(ev.data); + if (result.done) { + setScanDone(true); + setScanning(false); + es.close(); + return; + } + setPortResults((prev) => [...prev, result]); + } catch { + /* ignore */ + } + }; + + es.onerror = () => { + setScanning(false); + setScanDone(true); + es.close(); + }; + }, [selectedDevice, scanMode, customPorts]); + + const stopScan = useCallback(() => { + esRef.current?.close(); + setScanning(false); + setScanDone(true); + }, []); + + const backToDiscover = useCallback(() => { + stopScan(); + setStep("discover"); + setSelectedDevice(null); + setPortResults([]); + setScanDone(false); + }, [stopScan]); + + return { + step, + discovering, + devices, + localNetworks, + selectedDevice, + scanning, + portResults, + scanDone, + error, + scanMode, + setScanMode, + customPorts, + setCustomPorts, + totalPorts, + discoverDevices, + selectDevice, + startPortScan, + stopScan, + backToDiscover, + }; +}