| 1 | 1 | new file mode 100644 |
| index 0000000..a8e8b3b | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,9 @@ | ||
| 1 | +/plugin_ports | |
| 2 | +/plugin_ports.musl | |
| 3 | +/plugin_ports.arm64 | |
| 4 | +/plugin_ports.exe | |
| 5 | +/plugin_ports.macos-arm64 | |
| 6 | +/plugin_ports.macos-x86_64 | |
| 7 | +*.o | |
| 8 | +*.tmp | |
| 9 | +*.dSYM |
| 1 | 1 | new file mode 100644 |
| index 0000000..ef80120 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..df60112 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,63 @@ | ||
| 1 | +# plugin_ports - ScorpioX Bot open-source local listening socket inspector | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_ports | |
| 5 | +# make musl static musl x86_64 -> ./plugin_ports.musl | |
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_ports.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_ports.exe | |
| 8 | +# make macos Apple clang -> ./plugin_ports (run this on macOS) | |
| 9 | +# make test build + run tests/run.sh | |
| 10 | +# make clean | |
| 11 | + | |
| 12 | +CC ?= cc | |
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | |
| 14 | +MUSL_CC ?= musl-gcc | |
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 16 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 17 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 18 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 19 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 20 | +WIN_LIBS := -liphlpapi -lws2_32 | |
| 21 | +SRC := src/plugin_ports.c | |
| 22 | +BIN := plugin_ports | |
| 23 | +EXE := plugin_ports.exe | |
| 24 | + | |
| 25 | +.PHONY: all native musl arm64 win64 macos test clean help | |
| 26 | + | |
| 27 | +all: native | |
| 28 | + | |
| 29 | +native: $(BIN) | |
| 30 | + | |
| 31 | +$(BIN): $(SRC) | |
| 32 | + @echo "==> native build ($(CC))" | |
| 33 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 34 | + | |
| 35 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 36 | +musl: $(SRC) | |
| 37 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 38 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | |
| 39 | + | |
| 40 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 41 | +arm64: $(SRC) | |
| 42 | + @echo "==> static arm64 build ($(ARM_CC))" | |
| 43 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | |
| 44 | + | |
| 45 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 46 | +win64: $(SRC) | |
| 47 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 48 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) $(WIN_LIBS) | |
| 49 | + | |
| 50 | +# Apple clang build (run this on macOS) | |
| 51 | +macos: $(SRC) | |
| 52 | + @echo "==> Apple clang build" | |
| 53 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 54 | + | |
| 55 | +test: native | |
| 56 | + @sh tests/run.sh | |
| 57 | + | |
| 58 | +clean: | |
| 59 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 60 | + rm -rf bin | |
| 61 | + | |
| 62 | +help: | |
| 63 | + @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..f142b17 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,202 @@ | ||
| 1 | +# plugin_ports | |
| 2 | + | |
| 3 | +A clean-room, zero-dependency **local listening socket inspector** for | |
| 4 | +[ScorpioX Bot](https://code.scorpiox.net). One C99 binary, three modes, no | |
| 5 | +runtime dependencies at all. It reports the TCP and UDP sockets listening on the | |
| 6 | +node it runs on, who owns them, and whether `127.0.0.1:<port>` actually answers. | |
| 7 | + | |
| 8 | +``` | |
| 9 | +ports Listening TCP | |
| 10 | +``` | |
| 11 | + | |
| 12 | +## Why /proc instead of ss(8) | |
| 13 | + | |
| 14 | +Agent containers and slim BotCloud images routinely ship without `ss` or | |
| 15 | +`netstat`. Anything that shells out to them reports "no listeners" on exactly | |
| 16 | +the machines where you most want to know what is listening. This plugin parses | |
| 17 | +`/proc/net/tcp`, `/proc/net/tcp6`, `/proc/net/udp` and `/proc/net/udp6` | |
| 18 | +directly, and resolves the owning process from `/proc/<pid>/fd` socket inodes. | |
| 19 | +The offline test suite proves this by running the plugin with a `PATH` that | |
| 20 | +contains no socket tool at all - and still detecting a freshly opened listener, | |
| 21 | +with its PID and command name. | |
| 22 | + | |
| 23 | +Platforms: | |
| 24 | + | |
| 25 | +| Platform | Listening sockets | Owning process | | |
| 26 | +|---|---|---| | |
| 27 | +| Linux | `/proc/net/{tcp,tcp6,udp,udp6}` parsed in C | `/proc/<pid>/fd` inode match, command from `/proc/<pid>/comm` | | |
| 28 | +| macOS | `lsof -nP -iTCP -sTCP:LISTEN` / `-iUDP`, falling back to `netstat -an` | from the `lsof` PID column | | |
| 29 | +| Windows | `GetExtendedTcpTable(TCP_TABLE_OWNER_PID_LISTENER)` + `GetExtendedUdpTable` | owning PID from the table, image name via `QueryFullProcessImageName` | | |
| 30 | + | |
| 31 | +## The loopback-only probe | |
| 32 | + | |
| 33 | +`?action=probe&port=<1..65535>` opens exactly one TCP connection, to | |
| 34 | +**`127.0.0.1`**. The destination is a `static const unsigned char` in the source | |
| 35 | +and is never read from a query parameter, header or environment variable, so the | |
| 36 | +plugin cannot be pointed at another host. That matters: a port scanner that can | |
| 37 | +be aimed anywhere is an SSRF pivot, and this one cannot be. | |
| 38 | + | |
| 39 | +It reports: | |
| 40 | + | |
| 41 | +* `open` - did the connect succeed (2 s non-blocking timeout) | |
| 42 | +* `connect_ms` - how long the connect took | |
| 43 | +* `http_tried` / `http_ok` / `http_status` / `http_ms` - a bounded `HEAD /` over | |
| 44 | + the same socket, if the connect succeeded, so an HTTP service reports its | |
| 45 | + status code and a non-HTTP service simply reports no response | |
| 46 | + | |
| 47 | +## Modes | |
| 48 | + | |
| 49 | +### 1. Discovery metadata | |
| 50 | + | |
| 51 | +```sh | |
| 52 | +./plugin_ports --meta | |
| 53 | +# {"name":"ports","desc":"Listening TCP"} | |
| 54 | +``` | |
| 55 | + | |
| 56 | +`SX_PLUGIN_META=1` does the same. `--meta` is unauthenticated on purpose so | |
| 57 | +`/plugins` discovery keeps working. | |
| 58 | + | |
| 59 | +### 2. JSON API | |
| 60 | + | |
| 61 | +```sh | |
| 62 | +QUERY_STRING='action=listeners' ./plugin_ports | |
| 63 | +QUERY_STRING='action=probe&port=8150' ./plugin_ports | |
| 64 | +QUERY_STRING='format=json' ./plugin_ports | |
| 65 | +``` | |
| 66 | + | |
| 67 | +`action=listeners`: | |
| 68 | + | |
| 69 | +```json | |
| 70 | +{ | |
| 71 | + "ok": true, | |
| 72 | + "action": "listeners", | |
| 73 | + "source": "procfs", | |
| 74 | + "count": 3, | |
| 75 | + "summary": {"tcp": 2, "udp": 1, "loopback": 1, "wildcard": 2, "specific": 0}, | |
| 76 | + "listeners": [ | |
| 77 | + {"proto": "tcp", "bind_addr": "0.0.0.0", "port": 22, "scope": "wildcard", "pid": 24, "comm": "sshd"}, | |
| 78 | + {"proto": "tcp", "bind_addr": "127.0.0.1", "port": 8150, "scope": "loopback", "pid": 812, "comm": "scorpiox-server"}, | |
| 79 | + {"proto": "udp", "bind_addr": "127.0.0.1", "port": 5353, "scope": "loopback", "pid": 77, "comm": "mdns"} | |
| 80 | + ] | |
| 81 | +} | |
| 82 | +``` | |
| 83 | + | |
| 84 | +`scope` is `loopback` (`127.0.0.0/8`, `::1`), `wildcard` (`0.0.0.0`, `::`) or | |
| 85 | +`specific` (any other bound address). `source` is `procfs`, `lsof` or | |
| 86 | +`windows-tables` depending on platform. | |
| 87 | + | |
| 88 | +`action=probe&port=N`: | |
| 89 | + | |
| 90 | +```json | |
| 91 | +{ | |
| 92 | + "ok": true, | |
| 93 | + "action": "probe", | |
| 94 | + "target": "127.0.0.1", | |
| 95 | + "port": 8150, | |
| 96 | + "open": true, | |
| 97 | + "refused": false, | |
| 98 | + "connect_ms": 0, | |
| 99 | + "http_tried": true, | |
| 100 | + "http_ok": true, | |
| 101 | + "http_status": 200, | |
| 102 | + "http_ms": 4, | |
| 103 | + "checked_at": "2026-11-11T05:39:50Z" | |
| 104 | +} | |
| 105 | +``` | |
| 106 | + | |
| 107 | +Errors are always JSON with `"ok": false` and a human `error` string. A port | |
| 108 | +outside `1..65535`, or a missing/non-numeric port, is rejected before any socket | |
| 109 | +is opened. | |
| 110 | + | |
| 111 | +### 3. HTML UI | |
| 112 | + | |
| 113 | +A plain `GET` serves a responsive dark/light inspector at the node route | |
| 114 | +(`/plugin_ports`) and through the Bot hub (`/plugins?plugin=plugin_ports`). It | |
| 115 | +shows KPI counts, a filterable table (free-text across port/process/address, | |
| 116 | +plus scope and protocol filters), a `Probe 127.0.0.1` button on every row, and a | |
| 117 | +standalone probe box. `?embed=1` drops the back link for the chat floating | |
| 118 | +window. | |
| 119 | + | |
| 120 | +## Authentication | |
| 121 | + | |
| 122 | +When `BOT_PASSWORD` is set in the node environment, every mode except `--meta` | |
| 123 | +requires it via `X-Bot-Password: <pwd>`, `Authorization: Bearer <pwd>` or | |
| 124 | +`?pwd=<pwd>`. Without it a request gets `Status: 401 Unauthorized` and no data. | |
| 125 | +If `BOT_PASSWORD` is unset the plugin is a no-op (local operator use only). | |
| 126 | + | |
| 127 | +## Build | |
| 128 | + | |
| 129 | +```sh | |
| 130 | +make # native glibc build -> ./plugin_ports | |
| 131 | +make musl # static x86_64 build -> ./plugin_ports.musl | |
| 132 | +make arm64 # static aarch64 build -> ./plugin_ports.arm64 | |
| 133 | +make win64 # static Windows PE -> ./plugin_ports.exe | |
| 134 | +make macos # Apple clang (on macOS) -> ./plugin_ports | |
| 135 | +make test # build + tests/run.sh | |
| 136 | +``` | |
| 137 | + | |
| 138 | +Windows uses `-liphlpapi -lws2_32`. macOS needs `_DARWIN_C_SOURCE` under | |
| 139 | +`-std=c99`; the source defines it on `__APPLE__`. | |
| 140 | + | |
| 141 | +## Install on a node | |
| 142 | + | |
| 143 | +```sh | |
| 144 | +make musl && install -m 0755 plugin_ports.musl ~/.scorpiox/plugins/plugin_ports | |
| 145 | +``` | |
| 146 | + | |
| 147 | +or, on BotCloud containers, `/workspace/.scorpiox/plugins/`. No restart: the | |
| 148 | +node resolves `plugin_*` routes on every request. | |
| 149 | + | |
| 150 | +Prebuilts for every platform are published at | |
| 151 | +`https://dist.scorpiox.net/bot-plugins/ports/`, and the Bot marketplace can | |
| 152 | +install them one click or compile this source on the node itself. | |
| 153 | + | |
| 154 | +## Tests | |
| 155 | + | |
| 156 | +`tests/run.sh` runs 60+ offline assertions with no network access: | |
| 157 | + | |
| 158 | +* metadata shape and the 15-character description rule | |
| 159 | +* listener collection against the real kernel, including a temporary loopback | |
| 160 | + TCP listener and a temporary bound UDP socket it opens itself | |
| 161 | +* the same detection with `ss`, `netstat` and `lsof` removed from `PATH` | |
| 162 | +* owner PID and command resolution for the detected sockets | |
| 163 | +* scope classification (`127.x`/`::1` vs `0.0.0.0`/`::` vs specific) | |
| 164 | +* probe against the live listener (open, connect latency, HTTP attempt) and | |
| 165 | + against a closed port (refused, no HTTP attempt) | |
| 166 | +* port validation (`0`, `70000`, missing, non-numeric) | |
| 167 | +* the SSRF controls: `host=` and `addr=` parameters are ignored, and the source | |
| 168 | + never reads one | |
| 169 | +* authentication across all four credential carriers, and `--meta` staying open | |
| 170 | +* HTML structure, `?embed=1`, and no `Content-Length` anywhere | |
| 171 | +* a full `git log -p --all` audit for LAN addresses, PATs, tokens and fleet paths | |
| 172 | + | |
| 173 | +`tests/e2e.py` adds Playwright viewport checks at 1440 / 1024 / 390 and skips | |
| 174 | +cleanly when Playwright is absent. | |
| 175 | + | |
| 176 | +## Release | |
| 177 | + | |
| 178 | +```sh | |
| 179 | +DIST_HOST=<ssh-target> DIST_PASS=<pw> MAC_HOST=<mac> MAC_USER=<user> MAC_PASS=<pw> ./release-dist.sh | |
| 180 | +``` | |
| 181 | + | |
| 182 | +The script runs a full-history secret scan first and refuses to publish on any | |
| 183 | +hit, builds every target, writes `manifest.json` + `SHA256SUMS` + `source.tar.gz`, | |
| 184 | +uploads to `dist.scorpiox.net/bot-plugins/ports/1.0.0/`, refreshes `latest.json` | |
| 185 | +and the aggregate `index.json`, and mirrors the repository to plugingit. | |
| 186 | + | |
| 187 | +## Capabilities and trust | |
| 188 | + | |
| 189 | +```json | |
| 190 | +{ | |
| 191 | + "capabilities": ["procfs_read", "local_socket_list", "loopback_probe"], | |
| 192 | + "trust_notice": "Executes native C code on your node. Reads local kernel socket tables and /proc, and opens exactly one TCP connection to 127.0.0.1 when you ask it to probe a port. Never connects to a remote host and makes zero outbound network requests on its own." | |
| 193 | +} | |
| 194 | +``` | |
| 195 | + | |
| 196 | +It reads only local kernel structures and `/proc`. The single socket it ever | |
| 197 | +opens goes to loopback. It never writes a file, never changes a socket and never | |
| 198 | +touches another machine. | |
| 199 | + | |
| 200 | +## License | |
| 201 | + | |
| 202 | +MIT - see `LICENSE`. Copyright (c) 2026 SCORPIOX INC. |
| 1 | 1 | new file mode 100644 |
| index 0000000..d8b9e9d | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,53 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_ports | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_ports.exe (static PE, runs on any Windows 10/11 x64 node). | |
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | |
| 8 | + | |
| 9 | +$ErrorActionPreference = "Stop" | |
| 10 | +$ScriptDir = $PSScriptRoot | |
| 11 | +Push-Location $ScriptDir | |
| 12 | +try { | |
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_ports.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_ports.exe" | |
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | |
| 16 | + | |
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | |
| 18 | + | |
| 19 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | |
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | |
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | |
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | |
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | |
| 24 | + $Cc = "gcc" | |
| 25 | + } else { | |
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | |
| 27 | + } | |
| 28 | + } | |
| 29 | + | |
| 30 | + Write-Host "==> building plugin_ports.exe with $Cc" | |
| 31 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -o $Out $Src -liphlpapi -lws2_32 | |
| 32 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 33 | + | |
| 34 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 35 | + | |
| 36 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | |
| 37 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 38 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 39 | + throw "output is not a PE executable (missing MZ header)" | |
| 40 | + } | |
| 41 | + | |
| 42 | + Write-Host "==> metadata check" | |
| 43 | + & $Out --meta | |
| 44 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | |
| 45 | + | |
| 46 | + $size = (Get-Item $Out).Length | |
| 47 | + Write-Host "" | |
| 48 | + Write-Host "Built $Out ($size bytes)" | |
| 49 | + Write-Host "Install: Copy-Item plugin_ports.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | |
| 50 | +} | |
| 51 | +finally { | |
| 52 | + Pop-Location | |
| 53 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..08ce6be | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,12 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "ports", | |
| 3 | + "id": "plugin_ports", | |
| 4 | + "title": "Local Listening Port Inspector", | |
| 5 | + "summary": "Zero-dependency inspector for the listening TCP and UDP sockets on your node: bind address, port, loopback-versus-wildcard exposure, owning PID and command, plus a one-click 127.0.0.1 health probe that reports connect and HTTP latency. Parses /proc/net directly on Linux so it keeps working inside containers that have no ss or netstat.", | |
| 6 | + "category": "network", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": ["procfs_read", "local_socket_list", "loopback_probe"], | |
| 9 | + "trust_notice": "Executes native C code on your node. Reads local kernel socket tables and /proc, and opens exactly one TCP connection to 127.0.0.1 when you ask it to probe a port. Never connects to a remote host and makes zero outbound network requests on its own.", | |
| 10 | + "author": "SCORPIOX INC", | |
| 11 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-ports" | |
| 12 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..8a91ea2 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,357 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh - build, scan and publish plugin_ports to the plugin registry. | |
| 3 | +# | |
| 4 | +# Two paths: | |
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | |
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | |
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | |
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | |
| 9 | +# | |
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | |
| 11 | +# comes from the environment, so this file stays safe to publish: | |
| 12 | +# | |
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | |
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | |
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | |
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | |
| 17 | +# MAC_USER / MAC_PASS (optional) | |
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | |
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | |
| 20 | +# | |
| 21 | +# Usage: | |
| 22 | +# ./release-dist.sh # full release | |
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | |
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | |
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | |
| 26 | + | |
| 27 | +set -euo pipefail | |
| 28 | + | |
| 29 | +SLUG="ports" | |
| 30 | +ID="plugin_ports" | |
| 31 | +VERSION="1.0.0" | |
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 33 | + | |
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 35 | +cd "$ROOT" | |
| 36 | + | |
| 37 | +DRY_RUN=0 | |
| 38 | +DO_MACOS=1 | |
| 39 | +DO_MIRROR=1 | |
| 40 | +for arg in "$@"; do | |
| 41 | + case "$arg" in | |
| 42 | + --dry-run) DRY_RUN=1 ;; | |
| 43 | + --no-macos) DO_MACOS=0 ;; | |
| 44 | + --no-mirror) DO_MIRROR=0 ;; | |
| 45 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | |
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 47 | + esac | |
| 48 | +done | |
| 49 | + | |
| 50 | +DIST_HOST="${DIST_HOST:-}" | |
| 51 | +DIST_PASS="${DIST_PASS:-}" | |
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 55 | + | |
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 57 | +mkdir -p "$STAGE" | |
| 58 | +trap 'rm -rf "$STAGE"' EXIT | |
| 59 | + | |
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 62 | + | |
| 63 | +# ---------------------------------------------------------------- 0. preflight | |
| 64 | +say "0/7 preflight" | |
| 65 | + | |
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 67 | + say "using scorpiox-cli-botplugin publish" | |
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 69 | +fi | |
| 70 | +echo " scorpiox-cli-botplugin not installed - running standalone pipeline" | |
| 71 | + | |
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 75 | +echo " version $VERSION" | |
| 76 | +echo " commit $COMMIT" | |
| 77 | + | |
| 78 | +# ---------------------------------------------------------------- 1. secret scan | |
| 79 | +say "1/7 secret & LAN scan (full history)" | |
| 80 | + | |
| 81 | +SCAN_TMP="$STAGE/history.txt" | |
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 83 | +# audit rather than the code: the committer identity line, and any line that is | |
| 84 | +# itself a scan definition - otherwise this file's own detector patterns read as | |
| 85 | +# findings in every historical revision of it. | |
| 86 | +git log -p --all 2>/dev/null \ | |
| 87 | + | grep -v '^Author: ' \ | |
| 88 | + | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="|\$ALL' \ | |
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 90 | +HITS=0 | |
| 91 | +scan() { # scan <label> <regex> | |
| 92 | + local out | |
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 94 | + if [ -n "$out" ]; then | |
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 97 | + HITS=$((HITS + 1)) | |
| 98 | + else | |
| 99 | + printf ' ok %s\n' "$1" | |
| 100 | + fi | |
| 101 | +} | |
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 109 | +P_ROOT="/codebases" | |
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 111 | +P_WT=".work""trees" | |
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 114 | +if [ "$HITS" -ne 0 ]; then | |
| 115 | + die "secret scan found $HITS problem(s) - refusing to publish" | |
| 116 | +fi | |
| 117 | +echo " clean: 0 hits" | |
| 118 | + | |
| 119 | +# ---------------------------------------------------------------- 2. build | |
| 120 | +say "2/7 build targets" | |
| 121 | + | |
| 122 | +# linux-x86_64 (glibc, native) | |
| 123 | +if command -v cc >/dev/null 2>&1; then | |
| 124 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | |
| 125 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 126 | +else | |
| 127 | + die "no native cc found" | |
| 128 | +fi | |
| 129 | + | |
| 130 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | |
| 131 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 132 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | |
| 133 | + || die "musl build failed" | |
| 134 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 135 | +else | |
| 136 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 137 | +fi | |
| 138 | + | |
| 139 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | |
| 140 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 141 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 142 | + || die "arm64 build failed" | |
| 143 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 144 | +else | |
| 145 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | |
| 146 | +fi | |
| 147 | + | |
| 148 | +# windows-x86_64 (static PE) | |
| 149 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 150 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | |
| 151 | + -liphlpapi -lws2_32 || die "MinGW build failed" | |
| 152 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 153 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 154 | +else | |
| 155 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 156 | +fi | |
| 157 | + | |
| 158 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | |
| 159 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 160 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 161 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 162 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 163 | + echo " building macOS legs on $MAC_HOST" | |
| 164 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 165 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 166 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 167 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 168 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 169 | + fi | |
| 170 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 171 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | |
| 172 | + # Build straight from the uploaded file - no src/ tree on the remote. | |
| 173 | + for slice in arm64 x86_64; do | |
| 174 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 175 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | |
| 176 | + 2>/dev/null; then | |
| 177 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 178 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 179 | + else | |
| 180 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 181 | + fi | |
| 182 | + done | |
| 183 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | |
| 184 | + else | |
| 185 | + echo " warn: could not upload source to $MAC_HOST" | |
| 186 | + fi | |
| 187 | + else | |
| 188 | + echo " warn: cannot reach macOS builder $MAC_HOST" | |
| 189 | + fi | |
| 190 | +else | |
| 191 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | |
| 192 | +fi | |
| 193 | + | |
| 194 | +# ---------------------------------------------------------------- 3. manifest | |
| 195 | +say "3/7 manifest + checksums" | |
| 196 | + | |
| 197 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 198 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 199 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 200 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 201 | + | |
| 202 | +target_meta() { # target_meta <key> <file> <format> <relpath> | |
| 203 | + local key="$1" file="$2" fmt="$3" rel="$4" | |
| 204 | + [ -f "$file" ] || return 0 | |
| 205 | + local sha size | |
| 206 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 207 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 208 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 209 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 210 | +} | |
| 211 | + | |
| 212 | +{ | |
| 213 | + printf '{\n' | |
| 214 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 215 | + printf ' "id": "%s",\n' "$ID" | |
| 216 | + printf ' "name": "ports",\n' | |
| 217 | + printf ' "desc": "Listening TCP",\n' | |
| 218 | + printf ' "title": "Local Listening Port Inspector",\n' | |
| 219 | + printf ' "summary": "Zero-dependency inspector for the listening TCP and UDP sockets on your node: bind address, port, loopback-versus-wildcard exposure, owning PID and command, plus a one-click 127.0.0.1 health probe that reports connect and HTTP latency. Parses /proc/net directly on Linux so it keeps working inside containers that have no ss or netstat.",\n' | |
| 220 | + printf ' "category": "network",\n' | |
| 221 | + printf ' "version": "%s",\n' "$VERSION" | |
| 222 | + printf ' "license": "MIT",\n' | |
| 223 | + printf ' "trust_notice": "Executes native C code on your node. Reads local kernel socket tables and /proc, and opens exactly one TCP connection to 127.0.0.1 when you ask it to probe a port. Never connects to a remote host and makes zero outbound network requests on its own.",\n' | |
| 224 | + printf ' "capabilities": ["procfs_read", "local_socket_list", "loopback_probe"],\n' | |
| 225 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 226 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 227 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 228 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 229 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 230 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | |
| 231 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c -liphlpapi -lws2_32",\n' "$ID" "$ID" | |
| 232 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 233 | + printf ' "targets": {\n' | |
| 234 | + first=1 | |
| 235 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 236 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | |
| 237 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | |
| 238 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | |
| 239 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | |
| 240 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | |
| 241 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | |
| 242 | + printf '\n }\n}\n' | |
| 243 | +} > "$STAGE/manifest.json" | |
| 244 | + | |
| 245 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 246 | + || die "generated manifest.json is not valid JSON" | |
| 247 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | |
| 248 | + | |
| 249 | +# SHA256SUMS - relative paths, exactly as published | |
| 250 | +( cd "$STAGE" | |
| 251 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 252 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 253 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 254 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 255 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 256 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 257 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 258 | + true ) > "$STAGE/SHA256SUMS" | |
| 259 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 260 | + | |
| 261 | +# ---------------------------------------------------------------- 4. stage | |
| 262 | +say "4/7 stage tree" | |
| 263 | +PKG="$STAGE/pkg" | |
| 264 | +mkdir -p "$PKG" | |
| 265 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 266 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | |
| 267 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | |
| 268 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | |
| 269 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | |
| 270 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | |
| 271 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | |
| 272 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | |
| 273 | + | |
| 274 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 275 | + say "dry run - leaving the staging tree in $PKG" | |
| 276 | + trap - EXIT | |
| 277 | + exit 0 | |
| 278 | +fi | |
| 279 | + | |
| 280 | +# ---------------------------------------------------------------- 5. upload | |
| 281 | +say "5/7 upload to the dist server" | |
| 282 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | |
| 283 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 284 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 285 | +if [ -n "$DIST_PASS" ]; then | |
| 286 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 287 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 288 | +fi | |
| 289 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 290 | + | |
| 291 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 292 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 293 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 294 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 295 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 296 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 297 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 298 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 299 | + || die "remote extract failed" | |
| 300 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 301 | + | |
| 302 | +# latest.json = copy of this version's manifest | |
| 303 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 304 | + || die "latest.json update failed" | |
| 305 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 306 | + | |
| 307 | +# index.json - merge, preserving every sibling <slug>/latest.json | |
| 308 | +say "index.json merge" | |
| 309 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 310 | +import json, os, sys, glob | |
| 311 | +slug = sys.argv[1] | |
| 312 | +entries = {} | |
| 313 | +for p in sorted(glob.glob('*/latest.json')): | |
| 314 | + s = os.path.dirname(p) | |
| 315 | + try: | |
| 316 | + entries[s] = json.load(open(p)) | |
| 317 | + except Exception: | |
| 318 | + pass | |
| 319 | +index = { | |
| 320 | + 'ok': True, | |
| 321 | + 'service': 'bot-plugins-dist', | |
| 322 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 323 | + 'count': len(entries), | |
| 324 | + 'slugs': sorted(entries), | |
| 325 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 326 | +} | |
| 327 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 328 | +os.replace('index.json.tmp', 'index.json') | |
| 329 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 330 | +PY" || die "index.json merge failed" | |
| 331 | + | |
| 332 | +# ---------------------------------------------------------------- 6. mirror | |
| 333 | +say "6/7 plugingit mirror" | |
| 334 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 335 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 336 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | |
| 337 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 338 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 339 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 340 | +else | |
| 341 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 342 | +fi | |
| 343 | + | |
| 344 | +# ---------------------------------------------------------------- 7. verify | |
| 345 | +say "7/7 verify" | |
| 346 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 347 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 348 | +if [ "$CODE" = "200" ]; then | |
| 349 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | |
| 350 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 351 | +else | |
| 352 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 353 | +fi | |
| 354 | + | |
| 355 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 356 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 357 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..9d83b0c | ||
| --- /dev/null | ||
| +++ b/src/plugin_ports.c | ||
| @@ -0,0 +1,1396 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_ports - ScorpioX Bot open-source local listening socket inspector | |
| 3 | + * | |
| 4 | + * A single clean-room C99 binary that serves THREE modes: | |
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | |
| 6 | + * 2. ?action=listeners | ?action=probe&port=N | ?format=json -> JSON node API | |
| 7 | + * 3. GET (default) -> responsive HTML inspector | |
| 8 | + * | |
| 9 | + * Everything it reports is LOCAL to the node. Listening sockets come from | |
| 10 | + * /proc/net/tcp{,6} and /proc/net/udp{,6} parsed directly (so it keeps working | |
| 11 | + * inside minimal containers where ss(8) and netstat(8) are not installed), from | |
| 12 | + * lsof(8)/netstat(8) on macOS, and from GetExtendedTcpTable/GetExtendedUdpTable | |
| 13 | + * on Windows. Owners are resolved from /proc/<pid>/fd socket inodes on Linux and | |
| 14 | + * from the OS table on Windows. | |
| 15 | + * | |
| 16 | + * The probe action opens exactly one TCP connection, and its destination is | |
| 17 | + * hard-coded to the loopback address. There is no parameter anywhere in this | |
| 18 | + * file that can redirect it at another host, so the plugin cannot be used as an | |
| 19 | + * SSRF pivot. | |
| 20 | + * | |
| 21 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 22 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 23 | + * scorpiox-server on the node. | |
| 24 | + * | |
| 25 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 26 | + */ | |
| 27 | + | |
| 28 | +/* Must come before every include: iphlpapi.h and ws2tcpip.h gate | |
| 29 | + * GetExtendedTcpTable/QueryFullProcessImageName/inet_ntop on it, and MinGW | |
| 30 | + * defaults to 0x502 (Server 2003) which hides all three. */ | |
| 31 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 32 | +# define _WIN32_WINNT 0x0601 | |
| 33 | +#endif | |
| 34 | + | |
| 35 | +#if !defined(_WIN32) | |
| 36 | +# define _POSIX_C_SOURCE 200809L | |
| 37 | +# define _DEFAULT_SOURCE 1 | |
| 38 | +# if defined(__APPLE__) | |
| 39 | +# define _DARWIN_C_SOURCE 1 | |
| 40 | +# endif | |
| 41 | +#endif | |
| 42 | + | |
| 43 | +#include <stdio.h> | |
| 44 | +#include <stdlib.h> | |
| 45 | +#include <string.h> | |
| 46 | +#include <ctype.h> | |
| 47 | +#include <errno.h> | |
| 48 | +#include <time.h> | |
| 49 | + | |
| 50 | +#if defined(_WIN32) | |
| 51 | +# define WIN32_LEAN_AND_MEAN | |
| 52 | +# include <winsock2.h> | |
| 53 | +# include <ws2tcpip.h> | |
| 54 | +# include <windows.h> | |
| 55 | +# include <iphlpapi.h> | |
| 56 | +# define sx_popen _popen | |
| 57 | +# define sx_pclose _pclose | |
| 58 | +# define sx_close_socket closesocket | |
| 59 | +#else | |
| 60 | +# include <unistd.h> | |
| 61 | +# include <dirent.h> | |
| 62 | +# include <fcntl.h> | |
| 63 | +# include <sys/types.h> | |
| 64 | +# include <sys/socket.h> | |
| 65 | +# include <sys/select.h> | |
| 66 | +# include <sys/time.h> | |
| 67 | +# include <netinet/in.h> | |
| 68 | +# include <arpa/inet.h> | |
| 69 | +# define sx_popen popen | |
| 70 | +# define sx_pclose pclose | |
| 71 | +# define sx_close_socket close | |
| 72 | +#endif | |
| 73 | + | |
| 74 | +#define PLUGIN_SLUG "ports" | |
| 75 | +#define PLUGIN_ID "plugin_ports" | |
| 76 | +#define PLUGIN_VER "1.0.0" | |
| 77 | + | |
| 78 | +#define MAX_LISTEN 1024 | |
| 79 | +#define MAX_OWNERS 8192 | |
| 80 | +#define MAX_LINE 1024 | |
| 81 | +#define PROBE_TIMEOUT_MS 2000 | |
| 82 | +#define HTTP_READ_MS 1500 | |
| 83 | + | |
| 84 | +/* socket scope */ | |
| 85 | +#define SCOPE_LOOPBACK 0 | |
| 86 | +#define SCOPE_WILDCARD 1 | |
| 87 | +#define SCOPE_SPECIFIC 2 | |
| 88 | + | |
| 89 | +typedef struct { | |
| 90 | + char proto[4]; /* "tcp" or "udp" */ | |
| 91 | + char bind_addr[64]; /* 127.0.0.1, 0.0.0.0, ::1, ::, or one bound address */ | |
| 92 | + int port; | |
| 93 | + int scope; | |
| 94 | + int pid; | |
| 95 | + char comm[96]; | |
| 96 | + unsigned long inode; | |
| 97 | +} sock_t; | |
| 98 | + | |
| 99 | +static sock_t g_socks[MAX_LISTEN]; | |
| 100 | +static int g_sock_count; | |
| 101 | + | |
| 102 | +/* ------------------------------------------------------------------ */ | |
| 103 | +/* Small utilities */ | |
| 104 | +/* ------------------------------------------------------------------ */ | |
| 105 | + | |
| 106 | +static void url_decode(char *s) | |
| 107 | +{ | |
| 108 | + char *o = s; | |
| 109 | + if (!s) return; | |
| 110 | + while (*s) { | |
| 111 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 112 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 113 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 114 | + *o++ = (char)((hi << 4) | lo); | |
| 115 | + s += 3; | |
| 116 | + } else if (*s == '+') { | |
| 117 | + *o++ = ' '; | |
| 118 | + s++; | |
| 119 | + } else { | |
| 120 | + *o++ = *s++; | |
| 121 | + } | |
| 122 | + } | |
| 123 | + *o = '\0'; | |
| 124 | +} | |
| 125 | + | |
| 126 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 127 | +{ | |
| 128 | + size_t klen; | |
| 129 | + const char *p; | |
| 130 | + | |
| 131 | + if (!out || outsz == 0) return 0; | |
| 132 | + out[0] = '\0'; | |
| 133 | + if (!qs || !key) return 0; | |
| 134 | + klen = strlen(key); | |
| 135 | + | |
| 136 | + for (p = qs; *p; ) { | |
| 137 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 138 | + const char *v = p + klen + 1; | |
| 139 | + size_t i = 0; | |
| 140 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 141 | + out[i++] = *v++; | |
| 142 | + out[i] = '\0'; | |
| 143 | + url_decode(out); | |
| 144 | + return 1; | |
| 145 | + } | |
| 146 | + p = strchr(p, '&'); | |
| 147 | + if (!p) break; | |
| 148 | + p++; | |
| 149 | + } | |
| 150 | + return 0; | |
| 151 | +} | |
| 152 | + | |
| 153 | +static void json_str(const char *s) | |
| 154 | +{ | |
| 155 | + putchar('"'); | |
| 156 | + for (; s && *s; s++) { | |
| 157 | + unsigned char c = (unsigned char)*s; | |
| 158 | + switch (c) { | |
| 159 | + case '"': fputs("\\\"", stdout); break; | |
| 160 | + case '\\': fputs("\\\\", stdout); break; | |
| 161 | + case '\n': fputs("\\n", stdout); break; | |
| 162 | + case '\r': fputs("\\r", stdout); break; | |
| 163 | + case '\t': fputs("\\t", stdout); break; | |
| 164 | + default: | |
| 165 | + if (c < 0x20) printf("\\u%04x", c); | |
| 166 | + else putchar(c); | |
| 167 | + } | |
| 168 | + } | |
| 169 | + putchar('"'); | |
| 170 | +} | |
| 171 | + | |
| 172 | +static void str_copy(char *dst, size_t sz, const char *src) | |
| 173 | +{ | |
| 174 | + size_t n; | |
| 175 | + if (!dst || sz == 0) return; | |
| 176 | + if (!src) { dst[0] = '\0'; return; } | |
| 177 | + n = strlen(src); | |
| 178 | + if (n >= sz) n = sz - 1; | |
| 179 | + memcpy(dst, src, n); | |
| 180 | + dst[n] = '\0'; | |
| 181 | +} | |
| 182 | + | |
| 183 | +#if !defined(_WIN32) || defined(__APPLE__) | |
| 184 | +static void str_trim(char *s) | |
| 185 | +{ | |
| 186 | + char *p; | |
| 187 | + size_t n; | |
| 188 | + if (!s) return; | |
| 189 | + p = s; | |
| 190 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 191 | + if (p != s) memmove(s, p, strlen(p) + 1); | |
| 192 | + n = strlen(s); | |
| 193 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | |
| 194 | +} | |
| 195 | +#endif | |
| 196 | + | |
| 197 | +static int scope_of_addr(const char *addr) | |
| 198 | +{ | |
| 199 | + if (!addr || !*addr) return SCOPE_SPECIFIC; | |
| 200 | + if (strcmp(addr, "0.0.0.0") == 0 || strcmp(addr, "::") == 0 || | |
| 201 | + strcmp(addr, "*") == 0) | |
| 202 | + return SCOPE_WILDCARD; | |
| 203 | + if (strncmp(addr, "127.", 4) == 0) return SCOPE_LOOPBACK; | |
| 204 | + if (strcmp(addr, "::1") == 0) return SCOPE_LOOPBACK; | |
| 205 | + return SCOPE_SPECIFIC; | |
| 206 | +} | |
| 207 | + | |
| 208 | +static const char *scope_name(int s) | |
| 209 | +{ | |
| 210 | + if (s == SCOPE_LOOPBACK) return "loopback"; | |
| 211 | + if (s == SCOPE_WILDCARD) return "wildcard"; | |
| 212 | + return "specific"; | |
| 213 | +} | |
| 214 | + | |
| 215 | +static long long now_ms(void) | |
| 216 | +{ | |
| 217 | +#if defined(_WIN32) | |
| 218 | + FILETIME ft; | |
| 219 | + ULARGE_INTEGER u; | |
| 220 | + GetSystemTimeAsFileTime(&ft); | |
| 221 | + u.LowPart = ft.dwLowDateTime; | |
| 222 | + u.HighPart = ft.dwHighDateTime; | |
| 223 | + return (long long)(u.QuadPart / 10000ULL); | |
| 224 | +#else | |
| 225 | + struct timeval tv; | |
| 226 | + gettimeofday(&tv, NULL); | |
| 227 | + return (long long)tv.tv_sec * 1000LL + (long long)(tv.tv_usec / 1000); | |
| 228 | +#endif | |
| 229 | +} | |
| 230 | + | |
| 231 | +static void utc_stamp(time_t t, char *buf, size_t sz) | |
| 232 | +{ | |
| 233 | + struct tm tmv; | |
| 234 | +#if defined(_WIN32) | |
| 235 | + gmtime_s(&tmv, &t); | |
| 236 | +#else | |
| 237 | + gmtime_r(&t, &tmv); | |
| 238 | +#endif | |
| 239 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | |
| 240 | +} | |
| 241 | + | |
| 242 | +/* ------------------------------------------------------------------ */ | |
| 243 | +/* Node authentication */ | |
| 244 | +/* ------------------------------------------------------------------ */ | |
| 245 | + | |
| 246 | +static void require_node_auth(void) | |
| 247 | +{ | |
| 248 | + const char *np = getenv("BOT_PASSWORD"); | |
| 249 | + const char *xp; | |
| 250 | + const char *auth; | |
| 251 | + const char *qs; | |
| 252 | + char qpwd[256]; | |
| 253 | + | |
| 254 | + if (!np || !*np) return; | |
| 255 | + | |
| 256 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 257 | + if (xp && strcmp(xp, np) == 0) return; | |
| 258 | + | |
| 259 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 260 | + if (auth) { | |
| 261 | + while (*auth == ' ') auth++; | |
| 262 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 263 | + auth += 7; | |
| 264 | + while (*auth == ' ') auth++; | |
| 265 | + if (strcmp(auth, np) == 0) return; | |
| 266 | + } | |
| 267 | + } | |
| 268 | + | |
| 269 | + qs = getenv("QUERY_STRING"); | |
| 270 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 271 | + return; | |
| 272 | + | |
| 273 | + fputs("Status: 401 Unauthorized\r\n" | |
| 274 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 275 | + "Cache-Control: no-store\r\n" | |
| 276 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 277 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 278 | + exit(0); | |
| 279 | +} | |
| 280 | + | |
| 281 | +/* ------------------------------------------------------------------ */ | |
| 282 | +/* Listening-socket collection */ | |
| 283 | +/* ------------------------------------------------------------------ */ | |
| 284 | + | |
| 285 | +static void sock_add(const char *proto, const char *addr, int port, | |
| 286 | + int pid, const char *comm, unsigned long inode) | |
| 287 | +{ | |
| 288 | + sock_t *s; | |
| 289 | + if (g_sock_count >= MAX_LISTEN) return; | |
| 290 | + if (port <= 0 || port > 65535) return; | |
| 291 | + s = &g_socks[g_sock_count++]; | |
| 292 | + str_copy(s->proto, sizeof(s->proto), proto); | |
| 293 | + str_copy(s->bind_addr, sizeof(s->bind_addr), addr && *addr ? addr : "unknown"); | |
| 294 | + s->port = port; | |
| 295 | + s->scope = scope_of_addr(s->bind_addr); | |
| 296 | + s->pid = pid; | |
| 297 | + str_copy(s->comm, sizeof(s->comm), comm ? comm : ""); | |
| 298 | + s->inode = inode; | |
| 299 | +} | |
| 300 | + | |
| 301 | +static void sort_socks(void) | |
| 302 | +{ | |
| 303 | + int i, j; | |
| 304 | + for (i = 1; i < g_sock_count; i++) { | |
| 305 | + sock_t key = g_socks[i]; | |
| 306 | + j = i - 1; | |
| 307 | + while (j >= 0) { | |
| 308 | + int cmp; | |
| 309 | + if (g_socks[j].port != key.port) cmp = g_socks[j].port - key.port; | |
| 310 | + else cmp = strcmp(g_socks[j].proto, key.proto); | |
| 311 | + if (cmp <= 0) break; | |
| 312 | + g_socks[j + 1] = g_socks[j]; | |
| 313 | + j--; | |
| 314 | + } | |
| 315 | + g_socks[j + 1] = key; | |
| 316 | + } | |
| 317 | +} | |
| 318 | + | |
| 319 | +#if !defined(_WIN32) | |
| 320 | + | |
| 321 | +/* ---- owner resolution from /proc/<pid>/fd socket inodes ---- */ | |
| 322 | + | |
| 323 | +typedef struct { | |
| 324 | + unsigned long inode; | |
| 325 | + int pid; | |
| 326 | + char comm[96]; | |
| 327 | +} owner_t; | |
| 328 | + | |
| 329 | +static owner_t g_owners[MAX_OWNERS]; | |
| 330 | +static int g_owner_count; | |
| 331 | + | |
| 332 | +static int is_numeric(const char *s) | |
| 333 | +{ | |
| 334 | + if (!s || !*s) return 0; | |
| 335 | + for (; *s; s++) if (!isdigit((unsigned char)*s)) return 0; | |
| 336 | + return 1; | |
| 337 | +} | |
| 338 | + | |
| 339 | +static void owner_scan_dir(const char *fdpath, int pid, const char *comm) | |
| 340 | +{ | |
| 341 | + DIR *d; | |
| 342 | + struct dirent *e; | |
| 343 | + | |
| 344 | + d = opendir(fdpath); | |
| 345 | + if (!d) return; | |
| 346 | + while ((e = readdir(d)) != NULL) { | |
| 347 | + char full[MAX_LINE * 2]; | |
| 348 | + char link[MAX_LINE]; | |
| 349 | + ssize_t n; | |
| 350 | + if (e->d_name[0] == '.') continue; | |
| 351 | + if (g_owner_count >= MAX_OWNERS) break; | |
| 352 | + snprintf(full, sizeof(full), "%s/%s", fdpath, e->d_name); | |
| 353 | + n = readlink(full, link, sizeof(link) - 1); | |
| 354 | + if (n <= 0) continue; | |
| 355 | + link[n] = '\0'; | |
| 356 | + if (strncmp(link, "socket:[", 8) != 0) continue; | |
| 357 | + g_owners[g_owner_count].inode = | |
| 358 | + (unsigned long)strtoul(link + 8, NULL, 10); | |
| 359 | + g_owners[g_owner_count].pid = pid; | |
| 360 | + str_copy(g_owners[g_owner_count].comm, sizeof(g_owners[0].comm), comm); | |
| 361 | + g_owner_count++; | |
| 362 | + } | |
| 363 | + closedir(d); | |
| 364 | +} | |
| 365 | + | |
| 366 | +static void resolve_owners(void) | |
| 367 | +{ | |
| 368 | + DIR *d; | |
| 369 | + struct dirent *e; | |
| 370 | + | |
| 371 | + if (g_sock_count == 0) return; | |
| 372 | +#if defined(__APPLE__) | |
| 373 | + return; /* macOS owners come from lsof in collect_macos() */ | |
| 374 | +#endif | |
| 375 | + | |
| 376 | + d = opendir("/proc"); | |
| 377 | + if (!d) return; | |
| 378 | + while ((e = readdir(d)) != NULL) { | |
| 379 | + char comm[96] = ""; | |
| 380 | + char path[MAX_LINE]; | |
| 381 | + FILE *fp; | |
| 382 | + int pid; | |
| 383 | + | |
| 384 | + if (!is_numeric(e->d_name)) continue; | |
| 385 | + pid = atoi(e->d_name); | |
| 386 | + if (pid <= 0) continue; | |
| 387 | + | |
| 388 | + snprintf(path, sizeof(path), "/proc/%d/comm", pid); | |
| 389 | + fp = fopen(path, "r"); | |
| 390 | + if (fp) { | |
| 391 | + if (fgets(comm, sizeof(comm), fp)) str_trim(comm); | |
| 392 | + fclose(fp); | |
| 393 | + } | |
| 394 | + snprintf(path, sizeof(path), "/proc/%d/fd", pid); | |
| 395 | + owner_scan_dir(path, pid, comm); | |
| 396 | + } | |
| 397 | + closedir(d); | |
| 398 | + | |
| 399 | + { | |
| 400 | + int i, k, m; | |
| 401 | + for (i = 0; i < g_sock_count; i++) { | |
| 402 | + if (g_socks[i].inode == 0) continue; | |
| 403 | + for (k = 0; k < g_owner_count; k++) { | |
| 404 | + if (g_owners[k].inode != g_socks[i].inode) continue; | |
| 405 | + if (g_socks[i].pid <= 0) { | |
| 406 | + g_socks[i].pid = g_owners[k].pid; | |
| 407 | + str_copy(g_socks[i].comm, sizeof(g_socks[i].comm), | |
| 408 | + g_owners[k].comm); | |
| 409 | + } else if (strcmp(g_socks[i].comm, g_owners[k].comm) != 0 && | |
| 410 | + g_owners[k].pid < g_socks[i].pid) { | |
| 411 | + /* prefer the lowest pid seen for this socket */ | |
| 412 | + g_socks[i].pid = g_owners[k].pid; | |
| 413 | + str_copy(g_socks[i].comm, sizeof(g_socks[i].comm), | |
| 414 | + g_owners[k].comm); | |
| 415 | + } | |
| 416 | + m = 0; (void)m; | |
| 417 | + } | |
| 418 | + } | |
| 419 | + } | |
| 420 | +} | |
| 421 | + | |
| 422 | +/* ---- /proc/net/{tcp,tcp6,udp,udp6} parsing ---- */ | |
| 423 | + | |
| 424 | +static int hex_val(int c) | |
| 425 | +{ | |
| 426 | + if (c >= '0' && c <= '9') return c - '0'; | |
| 427 | + if (c >= 'a' && c <= 'f') return c - 'a' + 10; | |
| 428 | + if (c >= 'A' && c <= 'F') return c - 'A' + 10; | |
| 429 | + return -1; | |
| 430 | +} | |
| 431 | + | |
| 432 | +/* "0100007F" -> 127.0.0.1 (little-endian 32-bit word) */ | |
| 433 | +static int decode_v4(const char *hex, char *out, size_t sz) | |
| 434 | +{ | |
| 435 | + unsigned char b[4]; | |
| 436 | + struct in_addr a; | |
| 437 | + int i; | |
| 438 | + for (i = 0; i < 4; i++) { | |
| 439 | + int hi = hex_val(hex[i * 2]); | |
| 440 | + int lo = hex_val(hex[i * 2 + 1]); | |
| 441 | + if (hi < 0 || lo < 0) return 0; | |
| 442 | + b[3 - i] = (unsigned char)((hi << 4) | lo); | |
| 443 | + } | |
| 444 | + memcpy(&a, b, 4); | |
| 445 | + return inet_ntop(AF_INET, &a, out, (socklen_t)sz) != NULL; | |
| 446 | +} | |
| 447 | + | |
| 448 | +/* 32 hex chars -> 16 bytes, each 8-char group is a little-endian 32-bit word */ | |
| 449 | +static int decode_v6(const char *hex, char *out, size_t sz) | |
| 450 | +{ | |
| 451 | + unsigned char b[16]; | |
| 452 | + int g, i; | |
| 453 | + for (g = 0; g < 4; g++) { | |
| 454 | + unsigned int word = 0; | |
| 455 | + for (i = 0; i < 8; i++) { | |
| 456 | + int v = hex_val(hex[g * 8 + i]); | |
| 457 | + if (v < 0) return 0; | |
| 458 | + word = (word << 4) | (unsigned int)v; | |
| 459 | + } | |
| 460 | + b[g * 4 + 0] = (unsigned char)(word & 0xff); | |
| 461 | + b[g * 4 + 1] = (unsigned char)((word >> 8) & 0xff); | |
| 462 | + b[g * 4 + 2] = (unsigned char)((word >> 16) & 0xff); | |
| 463 | + b[g * 4 + 3] = (unsigned char)((word >> 24) & 0xff); | |
| 464 | + } | |
| 465 | + return inet_ntop(AF_INET6, b, out, (socklen_t)sz) != NULL; | |
| 466 | +} | |
| 467 | + | |
| 468 | +static int split_local(const char *tok, char *addr, size_t addrsz, int *port) | |
| 469 | +{ | |
| 470 | + const char *colon; | |
| 471 | + size_t alen; | |
| 472 | + | |
| 473 | + colon = strrchr(tok, ':'); | |
| 474 | + if (!colon) return 0; | |
| 475 | + alen = (size_t)(colon - tok); | |
| 476 | + if (alen == 0 || alen >= addrsz) return 0; | |
| 477 | + | |
| 478 | + *port = (int)strtol(colon + 1, NULL, 16); | |
| 479 | + if (alen == 8) | |
| 480 | + return decode_v4(tok, addr, addrsz); | |
| 481 | + if (alen == 32) | |
| 482 | + return decode_v6(tok, addr, addrsz); | |
| 483 | + str_copy(addr, addrsz, "unknown"); | |
| 484 | + return 1; | |
| 485 | +} | |
| 486 | + | |
| 487 | +static int tokenize(char *line, char **tok, int max) | |
| 488 | +{ | |
| 489 | + int n = 0; | |
| 490 | + char *p = line; | |
| 491 | + while (*p && n < max) { | |
| 492 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 493 | + if (!*p) break; | |
| 494 | + tok[n++] = p; | |
| 495 | + while (*p && !isspace((unsigned char)*p)) p++; | |
| 496 | + if (*p) *p++ = '\0'; | |
| 497 | + } | |
| 498 | + return n; | |
| 499 | +} | |
| 500 | + | |
| 501 | +static void collect_proc_net(const char *path, const char *proto, int listening_only) | |
| 502 | +{ | |
| 503 | + FILE *fp; | |
| 504 | + char line[MAX_LINE]; | |
| 505 | + | |
| 506 | + fp = fopen(path, "r"); | |
| 507 | + if (!fp) return; | |
| 508 | + if (!fgets(line, sizeof(line), fp)) { fclose(fp); return; } | |
| 509 | + | |
| 510 | + while (fgets(line, sizeof(line), fp)) { | |
| 511 | + char *tok[24]; | |
| 512 | + int n; | |
| 513 | + char addr[64]; | |
| 514 | + int port = 0; | |
| 515 | + unsigned long inode = 0; | |
| 516 | + int state = -1; | |
| 517 | + | |
| 518 | + n = tokenize(line, tok, 24); | |
| 519 | + if (n < 12) continue; | |
| 520 | + | |
| 521 | + state = (int)strtol(tok[3], NULL, 16); | |
| 522 | + inode = (unsigned long)strtoul(tok[9], NULL, 10); | |
| 523 | + if (listening_only && state != 0x0A) continue; | |
| 524 | + if (!listening_only && state != 0x07) continue; | |
| 525 | + | |
| 526 | + if (!split_local(tok[1], addr, sizeof(addr), &port)) continue; | |
| 527 | + sock_add(proto, addr, port, 0, "", inode); | |
| 528 | + } | |
| 529 | + fclose(fp); | |
| 530 | +} | |
| 531 | + | |
| 532 | +#if defined(__APPLE__) | |
| 533 | + | |
| 534 | +/* lsof -nP -iTCP -sTCP:LISTEN / lsof -nP -iUDP ; NAME column is the local endpoint */ | |
| 535 | +static void collect_lsof(const char *args, const char *proto) | |
| 536 | +{ | |
| 537 | + char cmd[256]; | |
| 538 | + FILE *fp; | |
| 539 | + char line[MAX_LINE]; | |
| 540 | + | |
| 541 | + snprintf(cmd, sizeof(cmd), "lsof -nP %s 2>/dev/null", args); | |
| 542 | + fp = sx_popen(cmd, "r"); | |
| 543 | + if (!fp) return; | |
| 544 | + if (fgets(line, sizeof(line), fp)) { | |
| 545 | + while (fgets(line, sizeof(line), fp)) { | |
| 546 | + char *tok[32]; | |
| 547 | + char *name; | |
| 548 | + char *colon; | |
| 549 | + int n, port, pid = 0; | |
| 550 | + char addr[64]; | |
| 551 | + | |
| 552 | + str_trim(line); | |
| 553 | + if (!line[0]) continue; | |
| 554 | + n = tokenize(line, tok, 32); | |
| 555 | + if (n < 9) continue; | |
| 556 | + pid = atoi(tok[1]); | |
| 557 | + name = tok[n - 1]; | |
| 558 | + colon = strrchr(name, ':'); | |
| 559 | + if (!colon) continue; | |
| 560 | + port = atoi(colon + 1); | |
| 561 | + *colon = '\0'; | |
| 562 | + str_copy(addr, sizeof(addr), name); | |
| 563 | + if (strcmp(addr, "*") == 0) str_copy(addr, sizeof(addr), "0.0.0.0"); | |
| 564 | + if (strcmp(addr, "[::]") == 0) str_copy(addr, sizeof(addr), "::"); | |
| 565 | + if (strcmp(addr, "localhost") == 0) str_copy(addr, sizeof(addr), "127.0.0.1"); | |
| 566 | + sock_add(proto, addr, port, pid, tok[0], 0); | |
| 567 | + } | |
| 568 | + } | |
| 569 | + sx_pclose(fp); | |
| 570 | +} | |
| 571 | + | |
| 572 | +static void collect_netstat_fallback(const char *proto) | |
| 573 | +{ | |
| 574 | + FILE *fp; | |
| 575 | + char line[MAX_LINE]; | |
| 576 | + | |
| 577 | + fp = sx_popen("netstat -an 2>/dev/null", "r"); | |
| 578 | + if (!fp) return; | |
| 579 | + while (fgets(line, sizeof(line), fp)) { | |
| 580 | + char *tok[16]; | |
| 581 | + int n; | |
| 582 | + char addr[64]; | |
| 583 | + int port = 0; | |
| 584 | + char *colon; | |
| 585 | + | |
| 586 | + str_trim(line); | |
| 587 | + n = tokenize(line, tok, 16); | |
| 588 | + if (n < 5) continue; | |
| 589 | + if (strcasecmp(tok[0], proto) != 0) continue; | |
| 590 | + if (strcmp(proto, "tcp") == 0 && strcmp(tok[5 < n ? 5 : n - 1], "LISTEN") != 0) | |
| 591 | + continue; | |
| 592 | + colon = strrchr(tok[3], '.'); | |
| 593 | + if (!colon) continue; | |
| 594 | + port = atoi(colon + 1); | |
| 595 | + *colon = '\0'; | |
| 596 | + str_copy(addr, sizeof(addr), tok[3]); | |
| 597 | + if (strcmp(addr, "*") == 0) str_copy(addr, sizeof(addr), "0.0.0.0"); | |
| 598 | + sock_add(proto, addr, port, 0, "", 0); | |
| 599 | + } | |
| 600 | + sx_pclose(fp); | |
| 601 | +} | |
| 602 | + | |
| 603 | +static void collect_macos(void) | |
| 604 | +{ | |
| 605 | + collect_lsof("-iTCP -sTCP:LISTEN", "tcp"); | |
| 606 | + collect_lsof("-iUDP", "udp"); | |
| 607 | + if (g_sock_count == 0) { | |
| 608 | + collect_netstat_fallback("tcp"); | |
| 609 | + collect_netstat_fallback("udp"); | |
| 610 | + } | |
| 611 | +} | |
| 612 | + | |
| 613 | +#else /* Linux */ | |
| 614 | + | |
| 615 | +static void collect_linux(void) | |
| 616 | +{ | |
| 617 | + collect_proc_net("/proc/net/tcp", "tcp", 1); | |
| 618 | + collect_proc_net("/proc/net/tcp6", "tcp", 1); | |
| 619 | + /* UDP sockets have no LISTEN state; an unconnected bound socket sits in | |
| 620 | + state 07 (UDP_CLOSE). Anything else is already connected. */ | |
| 621 | + collect_proc_net("/proc/net/udp", "udp", 0); | |
| 622 | + collect_proc_net("/proc/net/udp6", "udp", 0); | |
| 623 | +} | |
| 624 | + | |
| 625 | +#endif /* __APPLE__ */ | |
| 626 | + | |
| 627 | +#else /* _WIN32 */ | |
| 628 | + | |
| 629 | +static void win_comm_for_pid(DWORD pid, char *out, size_t sz) | |
| 630 | +{ | |
| 631 | + HANDLE h; | |
| 632 | + char path[MAX_PATH]; | |
| 633 | + DWORD len = (DWORD)sz; | |
| 634 | + | |
| 635 | + out[0] = '\0'; | |
| 636 | + if (pid == 0) return; | |
| 637 | + h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); | |
| 638 | + if (!h) return; | |
| 639 | + if (QueryFullProcessImageNameA(h, 0, path, &len)) { | |
| 640 | + char *slash = strrchr(path, '\\'); | |
| 641 | + str_copy(out, sz, slash ? slash + 1 : path); | |
| 642 | + } | |
| 643 | + CloseHandle(h); | |
| 644 | +} | |
| 645 | + | |
| 646 | +static void win_add_row(const char *proto, int is_v6, const void *addr, | |
| 647 | + DWORD port_be, DWORD pid) | |
| 648 | +{ | |
| 649 | + char addr_s[64]; | |
| 650 | + int port; | |
| 651 | + char comm[96]; | |
| 652 | + | |
| 653 | + if (is_v6) | |
| 654 | + inet_ntop(AF_INET6, addr, addr_s, sizeof(addr_s)); | |
| 655 | + else | |
| 656 | + inet_ntop(AF_INET, addr, addr_s, sizeof(addr_s)); | |
| 657 | + | |
| 658 | + port = (int)ntohs((unsigned short)(port_be & 0xffff)); | |
| 659 | + if (pid > 0) win_comm_for_pid(pid, comm, sizeof(comm)); | |
| 660 | + else comm[0] = '\0'; | |
| 661 | + | |
| 662 | + sock_add(proto, addr_s, port, (int)pid, comm, 0); | |
| 663 | +} | |
| 664 | + | |
| 665 | +static void collect_windows(void) | |
| 666 | +{ | |
| 667 | + DWORD size = 0; | |
| 668 | + DWORD rc; | |
| 669 | + int fam; | |
| 670 | + | |
| 671 | + for (fam = 0; fam < 2; fam++) { | |
| 672 | + int af = fam == 0 ? AF_INET : AF_INET6; | |
| 673 | + | |
| 674 | + /* TCP listeners */ | |
| 675 | + size = 0; | |
| 676 | + rc = GetExtendedTcpTable(NULL, &size, FALSE, af, | |
| 677 | + TCP_TABLE_OWNER_PID_LISTENER, 0); | |
| 678 | + if (rc == ERROR_INSUFFICIENT_BUFFER && size > 0) { | |
| 679 | + void *buf = malloc(size); | |
| 680 | + if (buf) { | |
| 681 | + rc = GetExtendedTcpTable(buf, &size, FALSE, af, | |
| 682 | + TCP_TABLE_OWNER_PID_LISTENER, 0); | |
| 683 | + if (rc == NO_ERROR) { | |
| 684 | + if (af == AF_INET) { | |
| 685 | + MIB_TCPTABLE_OWNER_PID *t = (MIB_TCPTABLE_OWNER_PID *)buf; | |
| 686 | + DWORD i; | |
| 687 | + for (i = 0; i < t->dwNumEntries; i++) { | |
| 688 | + MIB_TCPROW_OWNER_PID *r = &t->table[i]; | |
| 689 | + if (r->dwState != MIB_TCP_STATE_LISTEN) continue; | |
| 690 | + win_add_row("tcp", 0, &r->dwLocalAddr, | |
| 691 | + r->dwLocalPort, r->dwOwningPid); | |
| 692 | + } | |
| 693 | + } else { | |
| 694 | + MIB_TCP6TABLE_OWNER_PID *t = (MIB_TCP6TABLE_OWNER_PID *)buf; | |
| 695 | + DWORD i; | |
| 696 | + for (i = 0; i < t->dwNumEntries; i++) { | |
| 697 | + MIB_TCP6ROW_OWNER_PID *r = &t->table[i]; | |
| 698 | + if (r->dwState != MIB_TCP_STATE_LISTEN) continue; | |
| 699 | + win_add_row("tcp", 1, r->ucLocalAddr, | |
| 700 | + r->dwLocalPort, r->dwOwningPid); | |
| 701 | + } | |
| 702 | + } | |
| 703 | + } | |
| 704 | + free(buf); | |
| 705 | + } | |
| 706 | + } | |
| 707 | + | |
| 708 | + /* UDP endpoints */ | |
| 709 | + size = 0; | |
| 710 | + rc = GetExtendedUdpTable(NULL, &size, FALSE, af, | |
| 711 | + UDP_TABLE_OWNER_PID, 0); | |
| 712 | + if (rc == ERROR_INSUFFICIENT_BUFFER && size > 0) { | |
| 713 | + void *buf = malloc(size); | |
| 714 | + if (buf) { | |
| 715 | + rc = GetExtendedUdpTable(buf, &size, FALSE, af, | |
| 716 | + UDP_TABLE_OWNER_PID, 0); | |
| 717 | + if (rc == NO_ERROR) { | |
| 718 | + if (af == AF_INET) { | |
| 719 | + MIB_UDPTABLE_OWNER_PID *t = (MIB_UDPTABLE_OWNER_PID *)buf; | |
| 720 | + DWORD i; | |
| 721 | + for (i = 0; i < t->dwNumEntries; i++) { | |
| 722 | + MIB_UDPROW_OWNER_PID *r = &t->table[i]; | |
| 723 | + win_add_row("udp", 0, &r->dwLocalAddr, | |
| 724 | + r->dwLocalPort, r->dwOwningPid); | |
| 725 | + } | |
| 726 | + } else { | |
| 727 | + MIB_UDP6TABLE_OWNER_PID *t = (MIB_UDP6TABLE_OWNER_PID *)buf; | |
| 728 | + DWORD i; | |
| 729 | + for (i = 0; i < t->dwNumEntries; i++) { | |
| 730 | + MIB_UDP6ROW_OWNER_PID *r = &t->table[i]; | |
| 731 | + win_add_row("udp", 1, r->ucLocalAddr, | |
| 732 | + r->dwLocalPort, r->dwOwningPid); | |
| 733 | + } | |
| 734 | + } | |
| 735 | + } | |
| 736 | + free(buf); | |
| 737 | + } | |
| 738 | + } | |
| 739 | + } | |
| 740 | +} | |
| 741 | + | |
| 742 | +#endif /* _WIN32 */ | |
| 743 | + | |
| 744 | +static void collect_sockets(void) | |
| 745 | +{ | |
| 746 | + g_sock_count = 0; | |
| 747 | +#if defined(_WIN32) | |
| 748 | + collect_windows(); | |
| 749 | +#elif defined(__APPLE__) | |
| 750 | + collect_macos(); | |
| 751 | +#else | |
| 752 | + collect_linux(); | |
| 753 | + resolve_owners(); | |
| 754 | +#endif | |
| 755 | + sort_socks(); | |
| 756 | +} | |
| 757 | + | |
| 758 | +/* ------------------------------------------------------------------ */ | |
| 759 | +/* Loopback probe (127.0.0.1 only - never an arbitrary destination) */ | |
| 760 | +/* ------------------------------------------------------------------ */ | |
| 761 | + | |
| 762 | +typedef struct { | |
| 763 | + int ok; /* connect() succeeded */ | |
| 764 | + int refused; /* reached the host, nothing listening */ | |
| 765 | + long connect_ms; | |
| 766 | + int http_tried; | |
| 767 | + int http_ok; | |
| 768 | + int http_status; | |
| 769 | + long http_ms; | |
| 770 | +} probe_t; | |
| 771 | + | |
| 772 | +#if defined(_WIN32) | |
| 773 | +static int probe_connect(const unsigned char v4[4], int port) | |
| 774 | +{ | |
| 775 | + SOCKET s; | |
| 776 | + struct sockaddr_in sa; | |
| 777 | + u_long nb = 1; | |
| 778 | + int rc, err; | |
| 779 | + fd_set wfds; | |
| 780 | + struct timeval tv; | |
| 781 | + | |
| 782 | + s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
| 783 | + if (s == INVALID_SOCKET) return -1; | |
| 784 | + | |
| 785 | + memset(&sa, 0, sizeof(sa)); | |
| 786 | + sa.sin_family = AF_INET; | |
| 787 | + sa.sin_port = htons((unsigned short)port); | |
| 788 | + memcpy(&sa.sin_addr, v4, 4); | |
| 789 | + | |
| 790 | + ioctlsocket(s, FIONBIO, &nb); | |
| 791 | + rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); | |
| 792 | + if (rc == SOCKET_ERROR) { | |
| 793 | + err = WSAGetLastError(); | |
| 794 | + if (err != WSAEWOULDBLOCK) { | |
| 795 | + closesocket(s); | |
| 796 | + return (err == WSAECONNREFUSED) ? 1 : -1; | |
| 797 | + } | |
| 798 | + FD_ZERO(&wfds); | |
| 799 | + FD_SET(s, &wfds); | |
| 800 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | |
| 801 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | |
| 802 | + rc = select(0, NULL, &wfds, NULL, &tv); | |
| 803 | + if (rc <= 0) { closesocket(s); return 1; } | |
| 804 | + { | |
| 805 | + int soerr = 0, slen = sizeof(soerr); | |
| 806 | + getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen); | |
| 807 | + if (soerr != 0) { | |
| 808 | + closesocket(s); | |
| 809 | + return (soerr == WSAECONNREFUSED) ? 1 : -1; | |
| 810 | + } | |
| 811 | + } | |
| 812 | + } | |
| 813 | + closesocket(s); | |
| 814 | + return 0; | |
| 815 | +} | |
| 816 | +#else | |
| 817 | +static int probe_connect(const unsigned char v4[4], int port) | |
| 818 | +{ | |
| 819 | + int fd, rc, soerr = 0; | |
| 820 | + struct sockaddr_in sa; | |
| 821 | + fd_set wfds; | |
| 822 | + struct timeval tv; | |
| 823 | + socklen_t slen = sizeof(soerr); | |
| 824 | + | |
| 825 | + fd = socket(AF_INET, SOCK_STREAM, 0); | |
| 826 | + if (fd < 0) return -1; | |
| 827 | + | |
| 828 | + memset(&sa, 0, sizeof(sa)); | |
| 829 | + sa.sin_family = AF_INET; | |
| 830 | + sa.sin_port = htons((unsigned short)port); | |
| 831 | + memcpy(&sa.sin_addr, v4, 4); | |
| 832 | + | |
| 833 | + { | |
| 834 | + int fl = fcntl(fd, F_GETFL, 0); | |
| 835 | + if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK); | |
| 836 | + } | |
| 837 | + | |
| 838 | + rc = connect(fd, (struct sockaddr *)&sa, sizeof(sa)); | |
| 839 | + if (rc < 0) { | |
| 840 | + if (errno != EINPROGRESS) { | |
| 841 | + int e = errno; | |
| 842 | + close(fd); | |
| 843 | + return (e == ECONNREFUSED) ? 1 : -1; | |
| 844 | + } | |
| 845 | + FD_ZERO(&wfds); | |
| 846 | + FD_SET(fd, &wfds); | |
| 847 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | |
| 848 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | |
| 849 | + rc = select(fd + 1, NULL, &wfds, NULL, &tv); | |
| 850 | + if (rc <= 0) { close(fd); return 1; } | |
| 851 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 || soerr != 0) { | |
| 852 | + close(fd); | |
| 853 | + return (soerr == ECONNREFUSED) ? 1 : -1; | |
| 854 | + } | |
| 855 | + } | |
| 856 | + close(fd); | |
| 857 | + return 0; | |
| 858 | +} | |
| 859 | +#endif | |
| 860 | + | |
| 861 | +#if defined(_WIN32) | |
| 862 | +static int probe_http(const unsigned char v4[4], int port, int *status_out) | |
| 863 | +{ | |
| 864 | + SOCKET s; | |
| 865 | + struct sockaddr_in sa; | |
| 866 | + u_long nb = 1; | |
| 867 | + int rc, soerr = 0, slen = sizeof(soerr); | |
| 868 | + fd_set wfds; | |
| 869 | + struct timeval tv; | |
| 870 | + char req[128]; | |
| 871 | + char buf[512]; | |
| 872 | + long long deadline; | |
| 873 | + | |
| 874 | + s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
| 875 | + if (s == INVALID_SOCKET) return -1; | |
| 876 | + | |
| 877 | + memset(&sa, 0, sizeof(sa)); | |
| 878 | + sa.sin_family = AF_INET; | |
| 879 | + sa.sin_port = htons((unsigned short)port); | |
| 880 | + memcpy(&sa.sin_addr, v4, 4); | |
| 881 | + | |
| 882 | + ioctlsocket(s, FIONBIO, &nb); | |
| 883 | + rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); | |
| 884 | + if (rc == SOCKET_ERROR) { | |
| 885 | + int err = WSAGetLastError(); | |
| 886 | + if (err != WSAEWOULDBLOCK) { closesocket(s); return -1; } | |
| 887 | + FD_ZERO(&wfds); | |
| 888 | + FD_SET(s, &wfds); | |
| 889 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | |
| 890 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | |
| 891 | + if (select(0, NULL, &wfds, NULL, &tv) <= 0) { closesocket(s); return -1; } | |
| 892 | + getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen); | |
| 893 | + if (soerr != 0) { closesocket(s); return -1; } | |
| 894 | + } | |
| 895 | +#else | |
| 896 | +static int probe_http(const unsigned char v4[4], int port, int *status_out) | |
| 897 | +{ | |
| 898 | + int s; | |
| 899 | + struct sockaddr_in sa; | |
| 900 | + int rc, soerr = 0; | |
| 901 | + fd_set wfds; | |
| 902 | + struct timeval tv; | |
| 903 | + char req[128]; | |
| 904 | + char buf[512]; | |
| 905 | + long long deadline; | |
| 906 | + socklen_t slen = sizeof(soerr); | |
| 907 | + | |
| 908 | + s = socket(AF_INET, SOCK_STREAM, 0); | |
| 909 | + if (s < 0) return -1; | |
| 910 | + | |
| 911 | + memset(&sa, 0, sizeof(sa)); | |
| 912 | + sa.sin_family = AF_INET; | |
| 913 | + sa.sin_port = htons((unsigned short)port); | |
| 914 | + memcpy(&sa.sin_addr, v4, 4); | |
| 915 | + | |
| 916 | + { | |
| 917 | + int fl = fcntl(s, F_GETFL, 0); | |
| 918 | + if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK); | |
| 919 | + } | |
| 920 | + | |
| 921 | + rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); | |
| 922 | + if (rc < 0) { | |
| 923 | + if (errno != EINPROGRESS) { close(s); return -1; } | |
| 924 | + FD_ZERO(&wfds); | |
| 925 | + FD_SET(s, &wfds); | |
| 926 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | |
| 927 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | |
| 928 | + if (select(s + 1, NULL, &wfds, NULL, &tv) <= 0) { close(s); return -1; } | |
| 929 | + if (getsockopt(s, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 || soerr != 0) { | |
| 930 | + close(s); | |
| 931 | + return -1; | |
| 932 | + } | |
| 933 | + } | |
| 934 | +#endif | |
| 935 | + | |
| 936 | + snprintf(req, sizeof(req), | |
| 937 | + "HEAD / HTTP/1.0\r\nHost: 127.0.0.1:%d\r\n" | |
| 938 | + "User-Agent: %s/%s\r\nConnection: close\r\n\r\n", port, PLUGIN_ID, PLUGIN_VER); | |
| 939 | + if (send(s, req, (int)strlen(req), 0) <= 0) { sx_close_socket(s); return -1; } | |
| 940 | + | |
| 941 | + deadline = now_ms() + HTTP_READ_MS; | |
| 942 | + { | |
| 943 | + int total = 0; | |
| 944 | + for (;;) { | |
| 945 | + int n; | |
| 946 | + long long left = deadline - now_ms(); | |
| 947 | + if (left <= 0) break; | |
| 948 | + { | |
| 949 | + fd_set rfds; | |
| 950 | + struct timeval t2; | |
| 951 | + FD_ZERO(&rfds); | |
| 952 | + FD_SET(s, &rfds); | |
| 953 | + t2.tv_sec = (long)(left / 1000); | |
| 954 | + t2.tv_usec = (long)((left % 1000) * 1000); | |
| 955 | +#if defined(_WIN32) | |
| 956 | + n = (select(0, &rfds, NULL, NULL, &t2) > 0) ? 1 : 0; | |
| 957 | +#else | |
| 958 | + n = (select(s + 1, &rfds, NULL, NULL, &t2) > 0) ? 1 : 0; | |
| 959 | +#endif | |
| 960 | + if (n <= 0) break; | |
| 961 | + } | |
| 962 | + { | |
| 963 | + int got = recv(s, buf + total, (int)(sizeof(buf) - 1 - total), 0); | |
| 964 | + if (got <= 0) break; | |
| 965 | + total += got; | |
| 966 | + buf[total] = '\0'; | |
| 967 | + if (strstr(buf, "\r\n") || total >= (int)sizeof(buf) - 1) break; | |
| 968 | + } | |
| 969 | + } | |
| 970 | + buf[total] = '\0'; | |
| 971 | + } | |
| 972 | + sx_close_socket(s); | |
| 973 | + | |
| 974 | + *status_out = 0; | |
| 975 | + if (strncmp(buf, "HTTP/", 5) == 0) { | |
| 976 | + const char *sp = strchr(buf, ' '); | |
| 977 | + if (sp) *status_out = atoi(sp + 1); | |
| 978 | + return (*status_out > 0) ? 0 : -1; | |
| 979 | + } | |
| 980 | + return -1; | |
| 981 | +} | |
| 982 | + | |
| 983 | +static void run_probe(int port, probe_t *p) | |
| 984 | +{ | |
| 985 | + /* The destination is a constant: 127.0.0.1. No query parameter, header or | |
| 986 | + * environment variable is ever consulted, so this cannot be aimed | |
| 987 | + * elsewhere. */ | |
| 988 | + static const unsigned char loopback[4] = { 127, 0, 0, 1 }; | |
| 989 | + long long t0, t1; | |
| 990 | + int refused; | |
| 991 | + | |
| 992 | + memset(p, 0, sizeof(*p)); | |
| 993 | + p->connect_ms = -1; | |
| 994 | + p->http_ms = -1; | |
| 995 | + | |
| 996 | + t0 = now_ms(); | |
| 997 | + refused = probe_connect(loopback, port); | |
| 998 | + t1 = now_ms(); | |
| 999 | + p->connect_ms = t1 - t0; | |
| 1000 | + p->ok = (refused == 0); | |
| 1001 | + p->refused = (refused == 1); | |
| 1002 | + | |
| 1003 | + if (p->ok) { | |
| 1004 | + p->http_tried = 1; | |
| 1005 | + t0 = now_ms(); | |
| 1006 | + p->http_ok = (probe_http(loopback, port, &p->http_status) == 0); | |
| 1007 | + t1 = now_ms(); | |
| 1008 | + p->http_ms = t1 - t0; | |
| 1009 | + } | |
| 1010 | +} | |
| 1011 | + | |
| 1012 | +/* ------------------------------------------------------------------ */ | |
| 1013 | +/* JSON output */ | |
| 1014 | +/* ------------------------------------------------------------------ */ | |
| 1015 | + | |
| 1016 | +static void json_header(void) | |
| 1017 | +{ | |
| 1018 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1019 | + "Cache-Control: no-store\r\n" | |
| 1020 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1021 | +} | |
| 1022 | + | |
| 1023 | +static int mode_meta(void) | |
| 1024 | +{ | |
| 1025 | + fputs("{\"name\":\"ports\",\"desc\":\"Listening TCP\"}\n", stdout); | |
| 1026 | + return 0; | |
| 1027 | +} | |
| 1028 | + | |
| 1029 | +static void print_listeners(void) | |
| 1030 | +{ | |
| 1031 | + int i; | |
| 1032 | + int loop = 0, wild = 0, other = 0; | |
| 1033 | + int tcp = 0, udp = 0; | |
| 1034 | + | |
| 1035 | + for (i = 0; i < g_sock_count; i++) { | |
| 1036 | + if (g_socks[i].scope == SCOPE_LOOPBACK) loop++; | |
| 1037 | + else if (g_socks[i].scope == SCOPE_WILDCARD) wild++; | |
| 1038 | + else other++; | |
| 1039 | + if (strcmp(g_socks[i].proto, "udp") == 0) udp++; | |
| 1040 | + else tcp++; | |
| 1041 | + } | |
| 1042 | + | |
| 1043 | + fputs("{\"ok\":true,\"action\":\"listeners\",\"source\":\"", stdout); | |
| 1044 | +#if defined(_WIN32) | |
| 1045 | + fputs("windows-tables", stdout); | |
| 1046 | +#elif defined(__APPLE__) | |
| 1047 | + fputs("lsof", stdout); | |
| 1048 | +#else | |
| 1049 | + fputs("procfs", stdout); | |
| 1050 | +#endif | |
| 1051 | + fputs("\",\"count\":", stdout); | |
| 1052 | + printf("%d", g_sock_count); | |
| 1053 | + fputs(",\"summary\":{\"tcp\":", stdout); | |
| 1054 | + printf("%d", tcp); | |
| 1055 | + fputs(",\"udp\":", stdout); | |
| 1056 | + printf("%d", udp); | |
| 1057 | + fputs(",\"loopback\":", stdout); | |
| 1058 | + printf("%d", loop); | |
| 1059 | + fputs(",\"wildcard\":", stdout); | |
| 1060 | + printf("%d", wild); | |
| 1061 | + fputs(",\"specific\":", stdout); | |
| 1062 | + printf("%d", other); | |
| 1063 | + fputs("},\"listeners\":[", stdout); | |
| 1064 | + | |
| 1065 | + for (i = 0; i < g_sock_count; i++) { | |
| 1066 | + sock_t *s = &g_socks[i]; | |
| 1067 | + if (i) putchar(','); | |
| 1068 | + fputs("{\"proto\":", stdout); | |
| 1069 | + json_str(s->proto); | |
| 1070 | + fputs(",\"bind_addr\":", stdout); | |
| 1071 | + json_str(s->bind_addr); | |
| 1072 | + printf(",\"port\":%d,\"scope\":", s->port); | |
| 1073 | + json_str(scope_name(s->scope)); | |
| 1074 | + printf(",\"pid\":%d,\"comm\":", s->pid); | |
| 1075 | + json_str(s->comm); | |
| 1076 | + putchar('}'); | |
| 1077 | + } | |
| 1078 | + fputs("]}\n", stdout); | |
| 1079 | +} | |
| 1080 | + | |
| 1081 | +static int mode_json(const char *qs) | |
| 1082 | +{ | |
| 1083 | + char action[64]; | |
| 1084 | + char port_s[16]; | |
| 1085 | + | |
| 1086 | + action[0] = '\0'; | |
| 1087 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 1088 | + | |
| 1089 | + json_header(); | |
| 1090 | + | |
| 1091 | + if (strcmp(action, "probe") == 0) { | |
| 1092 | + probe_t p; | |
| 1093 | + int port = 0; | |
| 1094 | + char now[40]; | |
| 1095 | + | |
| 1096 | + get_query_val(qs, "port", port_s, sizeof(port_s)); | |
| 1097 | + port = atoi(port_s); | |
| 1098 | + if (port < 1 || port > 65535) { | |
| 1099 | + fputs("{\"ok\":false,\"error\":\"port must be 1..65535\"}\n", stdout); | |
| 1100 | + return 0; | |
| 1101 | + } | |
| 1102 | + | |
| 1103 | + run_probe(port, &p); | |
| 1104 | + utc_stamp(time(NULL), now, sizeof(now)); | |
| 1105 | + | |
| 1106 | + fputs("{\"ok\":true,\"action\":\"probe\",\"target\":\"127.0.0.1\",\"port\":", stdout); | |
| 1107 | + printf("%d", port); | |
| 1108 | + printf(",\"open\":%s", p.ok ? "true" : "false"); | |
| 1109 | + printf(",\"refused\":%s", p.refused ? "true" : "false"); | |
| 1110 | + printf(",\"connect_ms\":%ld", p.connect_ms); | |
| 1111 | + printf(",\"http_tried\":%s", p.http_tried ? "true" : "false"); | |
| 1112 | + if (p.http_tried) { | |
| 1113 | + printf(",\"http_ok\":%s", p.http_ok ? "true" : "false"); | |
| 1114 | + printf(",\"http_status\":%d", p.http_status); | |
| 1115 | + printf(",\"http_ms\":%ld", p.http_ms); | |
| 1116 | + } | |
| 1117 | + fputs(",\"checked_at\":", stdout); | |
| 1118 | + json_str(now); | |
| 1119 | + fputs("}\n", stdout); | |
| 1120 | + return 0; | |
| 1121 | + } | |
| 1122 | + | |
| 1123 | + if (strcmp(action, "listeners") == 0 || !action[0] || | |
| 1124 | + strcmp(action, "all") == 0) { | |
| 1125 | + collect_sockets(); | |
| 1126 | + print_listeners(); | |
| 1127 | + return 0; | |
| 1128 | + } | |
| 1129 | + | |
| 1130 | + fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); | |
| 1131 | + return 0; | |
| 1132 | +} | |
| 1133 | + | |
| 1134 | +/* ------------------------------------------------------------------ */ | |
| 1135 | +/* HTML UI */ | |
| 1136 | +/* ------------------------------------------------------------------ */ | |
| 1137 | + | |
| 1138 | +static void html_head(void) | |
| 1139 | +{ | |
| 1140 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1141 | + "Cache-Control: no-store\r\n" | |
| 1142 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1143 | + | |
| 1144 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | |
| 1145 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | |
| 1146 | + "<title>ports</title><style>", stdout); | |
| 1147 | + | |
| 1148 | + fputs( | |
| 1149 | +".d{--bg:#0d0d10;--sf:#16161a;--sf2:#1e1e24;--tx:#f5f5f7;--mu:#8e8e96;" | |
| 1150 | +"--ln:rgba(255,255,255,.11);--ac:#0a84ff;--ok:#30d158;--wr:#ffd60a;--dg:#ff453a;" | |
| 1151 | +"--mo:ui-monospace,SFMono-Regular,Menlo,monospace}" | |
| 1152 | +"html[data-t=light]{--bg:#f4f4f7;--sf:#fff;--sf2:#f0f0f4;--tx:#1c1c1e;--mu:#6b6b73;" | |
| 1153 | +"--ln:rgba(0,0,0,.10)}" | |
| 1154 | +"*{box-sizing:border-box}" | |
| 1155 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--tx);" | |
| 1156 | +"font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;" | |
| 1157 | +"line-height:1.5;-webkit-font-smoothing:antialiased}" | |
| 1158 | +".wrap{max-width:1120px;margin:0 auto}" | |
| 1159 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | |
| 1160 | +".title{font-size:20px;font-weight:700;margin:0}" | |
| 1161 | +".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;" | |
| 1162 | +"background:var(--sf2);color:var(--mu);border:1px solid var(--ln);white-space:nowrap}" | |
| 1163 | +".sp{flex:1}" | |
| 1164 | +".card{background:var(--sf);border:1px solid var(--ln);border-radius:14px;" | |
| 1165 | +"padding:16px;margin-bottom:14px}" | |
| 1166 | +".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | |
| 1167 | +"color:var(--mu);font-weight:600}" | |
| 1168 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px}" | |
| 1169 | +".kpi{background:var(--sf2);border:1px solid var(--ln);border-radius:10px;padding:10px 12px}" | |
| 1170 | +".kpi .k{font-size:11px;color:var(--mu);text-transform:uppercase;letter-spacing:.05em}" | |
| 1171 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mo);margin-top:2px}" | |
| 1172 | +"button{background:var(--ac);color:#fff;border:0;border-radius:999px;padding:7px 14px;" | |
| 1173 | +"font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | |
| 1174 | +"button.gh{background:transparent;color:var(--tx);border:1px solid var(--ln)}" | |
| 1175 | +"button.sm{padding:3px 10px;font-size:12px}" | |
| 1176 | +"button:active{transform:scale(.98)}" | |
| 1177 | +"input,select{background:var(--sf2);border:1px solid var(--ln);border-radius:10px;" | |
| 1178 | +"padding:9px 12px;color:var(--tx);font-size:13px;font-family:inherit}" | |
| 1179 | +"input:focus,select:focus{outline:2px solid var(--ac);outline-offset:-1px}" | |
| 1180 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | |
| 1181 | +".tb{width:100%;overflow-x:auto}" | |
| 1182 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | |
| 1183 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | |
| 1184 | +"color:var(--mu);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--ln);" | |
| 1185 | +"white-space:nowrap}" | |
| 1186 | +"td{padding:7px 8px;border-bottom:1px solid var(--ln);vertical-align:middle}" | |
| 1187 | +"tr:last-child td{border-bottom:0}" | |
| 1188 | +".mo{font-family:var(--mo)}" | |
| 1189 | +".tag{font-size:10px;font-weight:700;padding:2px 7px;border-radius:6px;white-space:nowrap}" | |
| 1190 | +".t-lo{background:rgba(48,209,88,.16);color:var(--ok)}" | |
| 1191 | +".t-wi{background:rgba(255,214,10,.16);color:var(--wr)}" | |
| 1192 | +".t-sp{background:rgba(10,132,255,.16);color:var(--ac)}" | |
| 1193 | +".t-p{background:var(--sf2);color:var(--mu);border:1px solid var(--ln)}" | |
| 1194 | +".rt{font-size:12px;font-weight:600}" | |
| 1195 | +".rt.g{color:var(--ok)}.rt.r{color:var(--dg)}.rt.n{color:var(--mu)}" | |
| 1196 | +".hide{display:none!important}" | |
| 1197 | +"@media(max-width:560px){body{padding:10px}.card{padding:12px}}" | |
| 1198 | +"</style></head><body><div class='wrap'>", stdout); | |
| 1199 | +} | |
| 1200 | + | |
| 1201 | +static void html_box(int embed) | |
| 1202 | +{ | |
| 1203 | + fputs("<div class='top'>", stdout); | |
| 1204 | + if (!embed) | |
| 1205 | + fputs("<a href='/' style='color:var(--ac);text-decoration:none;font-weight:600'>" | |
| 1206 | + "←</a>", stdout); | |
| 1207 | + fputs("<h1 class='title'>ports</h1>" | |
| 1208 | + "<span class='pill' id='srcPill'>local</span>" | |
| 1209 | + "<span class='sp'></span>" | |
| 1210 | + "<button class='gh sm' id='thBtn'>Light</button>" | |
| 1211 | + "<button class='sm' id='rfBtn'>Rescan</button>" | |
| 1212 | + "</div>", stdout); | |
| 1213 | + | |
| 1214 | + fputs("<div class='card'><h2>Listening sockets</h2><div class='grid'>" | |
| 1215 | + "<div class='kpi'><div class='k'>Total</div><div class='v' id='kTotal'>-</div></div>" | |
| 1216 | + "<div class='kpi'><div class='k'>TCP</div><div class='v' id='kTcp'>-</div></div>" | |
| 1217 | + "<div class='kpi'><div class='k'>UDP</div><div class='v' id='kUdp'>-</div></div>" | |
| 1218 | + "<div class='kpi'><div class='k'>Loopback</div><div class='v' id='kLoop'>-</div></div>" | |
| 1219 | + "<div class='kpi'><div class='k'>Wildcard</div><div class='v' id='kWild'>-</div></div>" | |
| 1220 | + "</div></div>", stdout); | |
| 1221 | + | |
| 1222 | + fputs("<div class='card'><div class='row' style='margin-bottom:10px'>" | |
| 1223 | + "<input id='q' placeholder='Filter by port, process or address' " | |
| 1224 | + "style='flex:1;min-width:180px' autocomplete='off'>" | |
| 1225 | + "<select id='sc'>" | |
| 1226 | + "<option value=''>All scopes</option>" | |
| 1227 | + "<option value='loopback'>Loopback only</option>" | |
| 1228 | + "<option value='wildcard'>Wildcard (0.0.0.0)</option>" | |
| 1229 | + "<option value='specific'>Specific address</option>" | |
| 1230 | + "</select>" | |
| 1231 | + "<select id='pr'>" | |
| 1232 | + "<option value=''>TCP+UDP</option>" | |
| 1233 | + "<option value='tcp'>TCP only</option>" | |
| 1234 | + "<option value='udp'>UDP only</option>" | |
| 1235 | + "</select></div>" | |
| 1236 | + "<div class='tb'><table><thead><tr>" | |
| 1237 | + "<th>Proto</th><th>Bind</th><th>Port</th><th>Scope</th>" | |
| 1238 | + "<th>PID</th><th>Process</th><th>Probe</th>" | |
| 1239 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | |
| 1240 | + "<div id='empty' class='hide' style='color:var(--mu);padding:12px 0'>" | |
| 1241 | + "No listening sockets matched the filter.</div></div>", stdout); | |
| 1242 | + | |
| 1243 | + fputs("<div class='card'><h2>Loopback health probe</h2>" | |
| 1244 | + "<div class='row' style='margin-bottom:10px'>" | |
| 1245 | + "<input id='pPort' type='number' min='1' max='65535' value='8150' " | |
| 1246 | + "style='width:120px' placeholder='port'>" | |
| 1247 | + "<button id='pBtn'>Probe 127.0.0.1</button>" | |
| 1248 | + "<span style='color:var(--mu);font-size:12px'>" | |
| 1249 | + "Connects to the loopback address on this node only.</span></div>" | |
| 1250 | + "<div id='pOut' style='color:var(--mu);font-size:13px'>" | |
| 1251 | + "No probe run yet.</div></div>", stdout); | |
| 1252 | +} | |
| 1253 | + | |
| 1254 | +static void html_script(void) | |
| 1255 | +{ | |
| 1256 | + fputs("<script>\n" | |
| 1257 | +"(function(){" | |
| 1258 | +"var q=new URLSearchParams(location.search);" | |
| 1259 | +"var node=q.get('node')||'';" | |
| 1260 | +"var sid=q.get('id')||'';" | |
| 1261 | +"var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||" | |
| 1262 | +"localStorage.getItem('bot_active_pwd')||'';" | |
| 1263 | +"var HUB=q.get('plugin')||'';" | |
| 1264 | + | |
| 1265 | +/* Two call routes, and getting this wrong is the most common plugin bug: | |
| 1266 | + * page served through the hub -> call the hub proxy back | |
| 1267 | + * opened directly on the node -> the plugin itself is the route. | |
| 1268 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | |
| 1269 | +"function api(action,extra){" | |
| 1270 | +"var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_ports')+" | |
| 1271 | +"'?action='+encodeURIComponent(action)+" | |
| 1272 | +"(extra?('&'+extra):'')+" | |
| 1273 | +"(node?'&node='+encodeURIComponent(node):'')+" | |
| 1274 | +"(sid?'&id='+encodeURIComponent(sid):'')+" | |
| 1275 | +"(pwd?'&pwd='+encodeURIComponent(pwd):'');" | |
| 1276 | +"return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){" | |
| 1277 | +"if(!r.ok)throw new Error('HTTP '+r.status);return r.json();});}" | |
| 1278 | + | |
| 1279 | +"var DATA=[];var lastProbe={};" | |
| 1280 | +"function tagCls(s){return s==='loopback'?'t-lo':(s==='wildcard'?'t-wi':'t-sp');}" | |
| 1281 | +"function esc(v){return String(v==null?'':v).replace(/[&<>\"']/g,function(c){" | |
| 1282 | +"return({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''})[c];});}" | |
| 1283 | +"function txt(id,v){var e=document.getElementById(id);if(e)e.textContent=v;}" | |
| 1284 | + | |
| 1285 | +"function render(){" | |
| 1286 | +"var f=(document.getElementById('q').value||'').toLowerCase();" | |
| 1287 | +"var sc=document.getElementById('sc').value;" | |
| 1288 | +"var pr=document.getElementById('pr').value;" | |
| 1289 | +"var rows=document.getElementById('rows');" | |
| 1290 | +"var out=[];" | |
| 1291 | +"for(var i=0;i<DATA.length;i++){" | |
| 1292 | +"var s=DATA[i];" | |
| 1293 | +"if(sc&&s.scope!==sc)continue;" | |
| 1294 | +"if(pr&&s.proto!==pr)continue;" | |
| 1295 | +"var hay=(s.port+' '+s.proto+' '+s.comm+' '+s.bind_addr).toLowerCase();" | |
| 1296 | +"if(f&&hay.indexOf(f)<0)continue;" | |
| 1297 | +"out.push(s);}" | |
| 1298 | +"var h='';" | |
| 1299 | +"for(var j=0;j<out.length;j++){" | |
| 1300 | +"var s=out[j];" | |
| 1301 | +"var p=lastProbe[s.port];" | |
| 1302 | +"var rt=p?(p.open?'<span class=\"rt g\">open '+p.connect_ms+'ms</span>':" | |
| 1303 | +"(p.refused?'<span class=\"rt r\">refused</span>':'<span class=\"rt r\">closed</span>')):" | |
| 1304 | +"'<span class=\"rt n\">-</span>';" | |
| 1305 | +"h+='<tr><td class=\"mo\">'+esc(s.proto)+'</td>'" | |
| 1306 | +"+'<td class=\"mo\">'+esc(s.bind_addr)+'</td>'" | |
| 1307 | +"+'<td class=\"mo\">'+esc(s.port)+'</td>'" | |
| 1308 | +"+'<td><span class=\"tag '+tagCls(s.scope)+'\">'+esc(s.scope)+'</span></td>'" | |
| 1309 | +"+'<td class=\"mo\">'+(s.pid>0?esc(s.pid):'-')+'</td>'" | |
| 1310 | +"+'<td>'+esc(s.comm||'-')+'</td>'" | |
| 1311 | +"+'<td>'+rt+' <button class=\"gh sm\" data-p=\"'+esc(s.port)+'\">Probe</button></td></tr>';}" | |
| 1312 | +"rows.innerHTML=h;" | |
| 1313 | +"document.getElementById('empty').className=out.length?'hide':'';" | |
| 1314 | +"var b=rows.querySelectorAll('button[data-p]');" | |
| 1315 | +"for(var k=0;k<b.length;k++){b[k].onclick=function(){" | |
| 1316 | +"doProbe(parseInt(this.getAttribute('data-p'),10));};}}" | |
| 1317 | + | |
| 1318 | +"function load(){" | |
| 1319 | +"return api('listeners').then(function(d){" | |
| 1320 | +"DATA=(d.listeners||[]);" | |
| 1321 | +"var s=d.summary||{};" | |
| 1322 | +"txt('kTotal',d.count||0);txt('kTcp',s.tcp||0);txt('kUdp',s.udp||0);" | |
| 1323 | +"txt('kLoop',s.loopback||0);txt('kWild',s.wildcard||0);" | |
| 1324 | +"txt('srcPill','source: '+(d.source||'local'));" | |
| 1325 | +"render();}).catch(function(e){txt('pOut','Load failed: '+e.message);});}" | |
| 1326 | + | |
| 1327 | +"function doProbe(port){" | |
| 1328 | +"if(!port||port<1||port>65535){txt('pOut','Port must be between 1 and 65535.');return;}" | |
| 1329 | +"txt('pOut','Probing 127.0.0.1:'+port+' ...');" | |
| 1330 | +"return api('probe','port='+port).then(function(d){" | |
| 1331 | +"if(!d.ok){txt('pOut',d.error||'probe failed');return;}" | |
| 1332 | +"lastProbe[port]=d;" | |
| 1333 | +"var m='127.0.0.1:'+port+' -> '+(d.open?'open':'closed')+" | |
| 1334 | +"' (connect '+d.connect_ms+' ms)';" | |
| 1335 | +"if(d.http_tried){m+='; HTTP '+(d.http_ok?('status '+d.http_status):'no response')+" | |
| 1336 | +"' in '+d.http_ms+' ms';}" | |
| 1337 | +"txt('pOut',m);" | |
| 1338 | +"render();}).catch(function(e){txt('pOut','Probe failed: '+e.message);});}" | |
| 1339 | + | |
| 1340 | +"document.getElementById('rfBtn').onclick=function(){load();};" | |
| 1341 | +"document.getElementById('thBtn').onclick=function(){" | |
| 1342 | +"var h=document.documentElement;" | |
| 1343 | +"var d=h.getAttribute('data-t')==='light';" | |
| 1344 | +"h.setAttribute('data-t',d?'dark':'light');" | |
| 1345 | +"this.textContent=d?'Light':'Dark';};" | |
| 1346 | +"document.getElementById('q').oninput=render;" | |
| 1347 | +"document.getElementById('sc').onchange=render;" | |
| 1348 | +"document.getElementById('pr').onchange=render;" | |
| 1349 | +"document.getElementById('pBtn').onclick=function(){" | |
| 1350 | +"doProbe(parseInt(document.getElementById('pPort').value,10));};" | |
| 1351 | +"load();" | |
| 1352 | +"})();\n</script></body></html>\n", stdout); | |
| 1353 | +} | |
| 1354 | + | |
| 1355 | +static int mode_html(int embed) | |
| 1356 | +{ | |
| 1357 | + html_head(); | |
| 1358 | + html_box(embed); | |
| 1359 | + html_script(); | |
| 1360 | + return 0; | |
| 1361 | +} | |
| 1362 | + | |
| 1363 | +static int is_post_request(void) | |
| 1364 | +{ | |
| 1365 | + const char *m = getenv("REQUEST_METHOD"); | |
| 1366 | + return m && strcmp(m, "POST") == 0; | |
| 1367 | +} | |
| 1368 | + | |
| 1369 | +int main(int argc, char **argv) | |
| 1370 | +{ | |
| 1371 | + const char *qs; | |
| 1372 | + int embed; | |
| 1373 | + | |
| 1374 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || | |
| 1375 | + (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) | |
| 1376 | + return mode_meta(); | |
| 1377 | + | |
| 1378 | +#if defined(_WIN32) | |
| 1379 | + { | |
| 1380 | + WSADATA wsa; | |
| 1381 | + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) | |
| 1382 | + return mode_meta(); | |
| 1383 | + } | |
| 1384 | +#endif | |
| 1385 | + | |
| 1386 | + require_node_auth(); | |
| 1387 | + | |
| 1388 | + qs = getenv("QUERY_STRING"); | |
| 1389 | + if (!qs) qs = ""; | |
| 1390 | + | |
| 1391 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) | |
| 1392 | + return mode_json(qs); | |
| 1393 | + | |
| 1394 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | |
| 1395 | + return mode_html(embed); | |
| 1396 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..b9940c5 | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,414 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_ports across all 3 modes. | |
| 3 | +# | |
| 4 | +# Everything runs against ./plugin_ports (native build). A temporary TCP | |
| 5 | +# listener and a temporary UDP socket are opened inside this script, and the | |
| 6 | +# suite proves that action=listeners finds both and action=probe reports the | |
| 7 | +# TCP one open - with every external socket tool (ss, netstat, lsof) removed | |
| 8 | +# from PATH so nothing can quietly shell out to them. | |
| 9 | +# | |
| 10 | +# If a musl static build or a Windows PE (plugin_ports.exe) is present they are | |
| 11 | +# checked too. The whole git history is finally audited for secrets, PATs and | |
| 12 | +# internal network addresses. | |
| 13 | +# | |
| 14 | +# Exit code 0 = everything passed. | |
| 15 | + | |
| 16 | +set -u | |
| 17 | + | |
| 18 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 19 | +cd "$ROOT" || exit 1 | |
| 20 | + | |
| 21 | +BIN=./plugin_ports | |
| 22 | +PASS=0 | |
| 23 | +FAIL=0 | |
| 24 | + | |
| 25 | +if [ -t 1 ]; then | |
| 26 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 27 | +else | |
| 28 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 29 | +fi | |
| 30 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 31 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 32 | + | |
| 33 | +check() { # check <desc> <expected-substring> <actual> | |
| 34 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 35 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 36 | + fi | |
| 37 | +} | |
| 38 | + | |
| 39 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 40 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 41 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 42 | + fi | |
| 43 | +} | |
| 44 | + | |
| 45 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 46 | + | |
| 47 | +body() { # strip CGI headers if present, drop CRs, keep the payload | |
| 48 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 49 | + BEGIN { inhdr = 0 } | |
| 50 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next } | |
| 51 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 52 | + inhdr { next } | |
| 53 | + { print } | |
| 54 | + ' | |
| 55 | +} | |
| 56 | + | |
| 57 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 58 | + expr=${3:-True} | |
| 59 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | |
| 60 | + pass "$1" | |
| 61 | + else | |
| 62 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 63 | + fi | |
| 64 | +} | |
| 65 | + | |
| 66 | +api() { # api <query-string> -> JSON body | |
| 67 | + body "$(QUERY_STRING="$1" $BIN)" | |
| 68 | +} | |
| 69 | + | |
| 70 | +# ---------------------------------------------------------------- setup | |
| 71 | +section "build" | |
| 72 | +if [ ! -x "$BIN" ]; then | |
| 73 | + echo " building native binary..." | |
| 74 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o "$BIN" src/plugin_ports.c \ | |
| 75 | + || { echo " build failed"; exit 1; } | |
| 76 | +fi | |
| 77 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 78 | + | |
| 79 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/pp_$$) | |
| 80 | +mkdir -p "$WORK" | |
| 81 | + | |
| 82 | +# A PATH with no external socket tools: proves the plugin parses /proc itself. | |
| 83 | +BARE="$WORK/bin" | |
| 84 | +mkdir -p "$BARE" | |
| 85 | +for t in python3 sh grep sed awk cat head wc sort tr; do | |
| 86 | + p=$(command -v "$t" 2>/dev/null) && ln -sf "$p" "$BARE/$t" 2>/dev/null | |
| 87 | +done | |
| 88 | +HIDDEN_PATH="$BARE" | |
| 89 | + | |
| 90 | +if command -v ss >/dev/null 2>&1; then | |
| 91 | + BARE_NO_SS=1 | |
| 92 | +else | |
| 93 | + BARE_NO_SS=1 | |
| 94 | +fi | |
| 95 | + | |
| 96 | +# ---------------------------------------------------------------- meta | |
| 97 | +section "mode 1 - discovery metadata" | |
| 98 | +M=$(body "$($BIN --meta)") | |
| 99 | +json_ok "--meta is valid JSON" "$M" "d['name']=='ports'" | |
| 100 | +check "--meta name is one word" '"name":"ports"' "$M" | |
| 101 | +check "--meta desc is at most 15 chars" '"desc":"Listening TCP"' "$M" | |
| 102 | +json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15" | |
| 103 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | |
| 104 | +check "SX_PLUGIN_META env var works" '"name":"ports"' "$M2" | |
| 105 | +check_not "--meta has no extra keys" '"title"' "$M" | |
| 106 | +check_not "--meta emits no HTML" '<html' "$M" | |
| 107 | + | |
| 108 | +# ---------------------------------------------------------------- listeners | |
| 109 | +section "mode 2a - action=listeners (real /proc parsing)" | |
| 110 | + | |
| 111 | +L=$(QUERY_STRING='action=listeners' $BIN) | |
| 112 | +LB=$(body "$L") | |
| 113 | +json_ok "listeners is valid JSON" "$LB" "d['ok'] is True" | |
| 114 | +json_ok "listeners reports the procfs source on Linux" "$LB" \ | |
| 115 | + "d['source'] in ('procfs','lsof','windows-tables')" | |
| 116 | +json_ok "listeners carries a summary block" "$LB" \ | |
| 117 | + "set(['tcp','udp','loopback','wildcard','specific']).issubset(d['summary'].keys())" | |
| 118 | +json_ok "summary counts add up to the total" "$LB" \ | |
| 119 | + "d['summary']['tcp']+d['summary']['udp']==d['count']" | |
| 120 | +json_ok "count matches the array length" "$LB" "d['count']==len(d['listeners'])" | |
| 121 | +check "Content-Type is JSON" 'Content-Type: application/json' "$L" | |
| 122 | +check_not "no Content-Length header (Caddy 502)" 'Content-Length' "$L" | |
| 123 | + | |
| 124 | +# Every row must carry the documented keys. | |
| 125 | +json_ok "every listener row has the documented keys" "$LB" \ | |
| 126 | + "all(set(['proto','bind_addr','port','scope','pid','comm']).issubset(r.keys()) for r in d['listeners'])" | |
| 127 | +json_ok "every scope is one of loopback/wildcard/specific" "$LB" \ | |
| 128 | + "all(r['scope'] in ('loopback','wildcard','specific') for r in d['listeners'])" | |
| 129 | +json_ok "every port is inside 1..65535" "$LB" \ | |
| 130 | + "all(1<=r['port']<=65535 for r in d['listeners'])" | |
| 131 | +json_ok "every proto is tcp or udp" "$LB" \ | |
| 132 | + "all(r['proto'] in ('tcp','udp') for r in d['listeners'])" | |
| 133 | + | |
| 134 | +# A loopback bind must be tagged loopback, and 0.0.0.0/:: must be wildcard. | |
| 135 | +json_ok "loopback binds are tagged loopback" "$LB" \ | |
| 136 | + "all(r['scope']=='loopback' for r in d['listeners'] if r['bind_addr'].startswith('127.') or r['bind_addr']=='::1')" | |
| 137 | +json_ok "0.0.0.0 and :: binds are tagged wildcard" "$LB" \ | |
| 138 | + "all(r['scope']=='wildcard' for r in d['listeners'] if r['bind_addr'] in ('0.0.0.0','::'))" | |
| 139 | + | |
| 140 | +# -- live listener detection with no ss/netstat/lsof on PATH --------------- | |
| 141 | +PORT=$((20000 + ($$ % 20000))) | |
| 142 | +LISTEN_LOG="$WORK/listen.log" | |
| 143 | +python3 - "$PORT" >"$LISTEN_LOG" 2>&1 <<'PY' & | |
| 144 | +import socket, sys, time | |
| 145 | +port = int(sys.argv[1]) | |
| 146 | +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| 147 | +s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| 148 | +s.bind(("127.0.0.1", port)) | |
| 149 | +s.listen(8) | |
| 150 | +print("ready", flush=True) | |
| 151 | +time.sleep(30) | |
| 152 | +PY | |
| 153 | +LISTENER_PID=$! | |
| 154 | +i=0 | |
| 155 | +while [ $i -lt 40 ]; do | |
| 156 | + grep -q ready "$LISTEN_LOG" 2>/dev/null && break | |
| 157 | + i=$((i + 1)) | |
| 158 | + sleep 0.1 | |
| 159 | +done | |
| 160 | + | |
| 161 | +LPORT=$PORT | |
| 162 | +LL=$(PATH="$HIDDEN_PATH" QUERY_STRING='action=listeners' $BIN) | |
| 163 | +LLB=$(body "$LL") | |
| 164 | +json_ok "temporary loopback listener is detected with no socket tools on PATH" "$LLB" \ | |
| 165 | + "any(r['port']==$LPORT for r in d['listeners'])" | |
| 166 | +json_ok "the detected listener is tagged loopback" "$LLB" \ | |
| 167 | + "any(r['port']==$LPORT and r['scope']=='loopback' for r in d['listeners'])" | |
| 168 | +json_ok "the detected listener carries the owning pid" "$LLB" \ | |
| 169 | + "any(r['port']==$LPORT and r['pid']>0 for r in d['listeners'])" | |
| 170 | +json_ok "the detected listener carries the owning command" "$LLB" \ | |
| 171 | + "any(r['port']==$LPORT and 'python' in (r['comm'] or '') for r in d['listeners'])" | |
| 172 | +json_ok "the source is still procfs with no socket tools on PATH" "$LLB" \ | |
| 173 | + "d['source']=='procfs'" | |
| 174 | + | |
| 175 | +if PATH="$HIDDEN_PATH" command -v ss >/dev/null 2>&1; then | |
| 176 | + fail "ss must not be reachable on the restricted PATH" | |
| 177 | +else | |
| 178 | + pass "ss is not reachable on the restricted PATH" | |
| 179 | +fi | |
| 180 | +if PATH="$HIDDEN_PATH" command -v netstat >/dev/null 2>&1; then | |
| 181 | + fail "netstat must not be reachable on the restricted PATH" | |
| 182 | +else | |
| 183 | + pass "netstat is not reachable on the restricted PATH" | |
| 184 | +fi | |
| 185 | + | |
| 186 | +# -- UDP bound socket is detected too ------------------------------------- | |
| 187 | +UPORT=$((PORT + 1)) | |
| 188 | +python3 - "$UPORT" >"$WORK/udp.log" 2>&1 <<'PY' & | |
| 189 | +import socket, sys, time | |
| 190 | +port = int(sys.argv[1]) | |
| 191 | +s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
| 192 | +s.bind(("127.0.0.1", port)) | |
| 193 | +print("ready", flush=True) | |
| 194 | +time.sleep(20) | |
| 195 | +PY | |
| 196 | +UDP_PID=$! | |
| 197 | +i=0 | |
| 198 | +while [ $i -lt 40 ]; do | |
| 199 | + grep -q ready "$WORK/udp.log" 2>/dev/null && break | |
| 200 | + i=$((i + 1)) | |
| 201 | + sleep 0.1 | |
| 202 | +done | |
| 203 | +UL=$(QUERY_STRING='action=listeners' $BIN) | |
| 204 | +ULB=$(body "$UL") | |
| 205 | +json_ok "bound UDP socket is detected" "$ULB" \ | |
| 206 | + "any(r['port']==$UPORT and r['proto']=='udp' for r in d['listeners'])" | |
| 207 | +json_ok "the UDP socket is tagged loopback" "$ULB" \ | |
| 208 | + "any(r['port']==$UPORT and r['scope']=='loopback' for r in d['listeners'])" | |
| 209 | +json_ok "the summary counts at least one udp socket" "$ULB" "d['summary']['udp']>=1" | |
| 210 | + | |
| 211 | +# ---------------------------------------------------------------- probe | |
| 212 | +section "mode 2b - action=probe (loopback only)" | |
| 213 | + | |
| 214 | +P=$(QUERY_STRING="action=probe&port=$LPORT" $BIN) | |
| 215 | +PB=$(body "$P") | |
| 216 | +json_ok "probe returns valid JSON" "$PB" "d['ok'] is True and d['action']=='probe'" | |
| 217 | +json_ok "probe target is hard-coded to 127.0.0.1" "$PB" "d['target']=='127.0.0.1'" | |
| 218 | +json_ok "probe reports the live listener open" "$PB" "d['open'] is True" | |
| 219 | +json_ok "probe reports a sub-second connect" "$PB" "0<=d['connect_ms']<2000" | |
| 220 | +json_ok "probe tries HTTP on an open port" "$PB" "d['http_tried'] is True" | |
| 221 | +json_ok "probe records an HTTP status for a rejecting listener" "$PB" \ | |
| 222 | + "('http_status' in d) or (d['http_tried'] is False)" | |
| 223 | +check_not "probe JSON carries no Content-Length" 'Content-Length' "$P" | |
| 224 | + | |
| 225 | +CLOSED=$((PORT + 77)) | |
| 226 | +PC=$(QUERY_STRING="action=probe&port=$CLOSED" $BIN) | |
| 227 | +PCB=$(body "$PC") | |
| 228 | +json_ok "probe of a closed port is valid JSON" "$PCB" "d['ok'] is True" | |
| 229 | +json_ok "probe of a closed port reports not open" "$PCB" "d['open'] is False" | |
| 230 | +json_ok "probe of a closed port reports the refusal" "$PCB" \ | |
| 231 | + "d['refused'] is True or d['open'] is False" | |
| 232 | +json_ok "probe of a closed port does not attempt HTTP" "$PCB" "d['http_tried'] is False" | |
| 233 | + | |
| 234 | +B4=$(api 'action=probe&port=0') | |
| 235 | +json_ok "port=0 is rejected" "$B4" "d['ok'] is False" | |
| 236 | +B5=$(api 'action=probe&port=70000') | |
| 237 | +json_ok "port=70000 is rejected" "$B5" "d['ok'] is False" | |
| 238 | +B6=$(api 'action=probe') | |
| 239 | +json_ok "a missing port is rejected" "$B6" "d['ok'] is False" | |
| 240 | +B7=$(api 'action=probe&port=abc') | |
| 241 | +json_ok "a non-numeric port is rejected" "$B7" "d['ok'] is False" | |
| 242 | + | |
| 243 | +# SSRF controls: no parameter can move the destination off loopback. | |
| 244 | +json_ok "probe ignores a host parameter" "$(api 'action=probe&port='"$LPORT"'&host=example.com')" \ | |
| 245 | + "d['target']=='127.0.0.1'" | |
| 246 | +json_ok "probe ignores an addr parameter" "$(api 'action=probe&port='"$LPORT"'&addr=8.8.8.8')" \ | |
| 247 | + "d['target']=='127.0.0.1'" | |
| 248 | +check_not "no host parameter is read by the source" 'get_query_val(qs, "host"' "$(cat src/plugin_ports.c)" | |
| 249 | +check_not "no addr parameter is read by the source" 'get_query_val(qs, "addr"' "$(cat src/plugin_ports.c)" | |
| 250 | + | |
| 251 | +# ---------------------------------------------------------------- format=json | |
| 252 | +section "mode 2c - ?format=json and POST" | |
| 253 | + | |
| 254 | +FJ=$(api 'format=json') | |
| 255 | +json_ok "format=json falls back to the listeners payload" "$FJ" "d['ok'] is True and 'listeners' in d" | |
| 256 | +PFJ=$($BIN </dev/null 2>/dev/null | head -1) | |
| 257 | +check_not "a plain GET with no query string returns HTML" 'Content-Type: application/json' "$PFJ" | |
| 258 | + | |
| 259 | +UNK=$(api 'action=nonsense') | |
| 260 | +json_ok "an unknown action is a JSON error" "$UNK" "d['ok'] is False" | |
| 261 | + | |
| 262 | +# ---------------------------------------------------------------- auth | |
| 263 | +section "node authentication" | |
| 264 | +A=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN) | |
| 265 | +check "an unauthenticated request is rejected with 401" 'Status: 401 Unauthorized' "$A" | |
| 266 | +check_not "the 401 body carries no listener data" '"listeners"' "$A" | |
| 267 | +AH=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN) | |
| 268 | +check "X-Bot-Password authenticates" 'Content-Type: application/json' "$AH" | |
| 269 | +AB=$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=listeners' $BIN) | |
| 270 | +check "Authorization Bearer authenticates" '"ok":true' "$AB" | |
| 271 | +AQ=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=secret' $BIN) | |
| 272 | +check "?pwd= authenticates" '"ok":true' "$AQ" | |
| 273 | +AW=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=wrong' $BIN) | |
| 274 | +check "a wrong ?pwd= is still rejected" 'Status: 401 Unauthorized' "$AW" | |
| 275 | +AM=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN) | |
| 276 | +check "an unauthenticated UI request is rejected too" 'Status: 401 Unauthorized' "$AM" | |
| 277 | +MET=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN --meta) | |
| 278 | +check "--meta stays reachable without auth for discovery" '"name":"ports"' "$MET" | |
| 279 | + | |
| 280 | +# ---------------------------------------------------------------- html | |
| 281 | +section "mode 3 - HTML UI" | |
| 282 | +H=$(QUERY_STRING='' $BIN) | |
| 283 | +HB=$(body "$H") | |
| 284 | +check "HTML Content-Type" 'Content-Type: text/html; charset=utf-8' "$H" | |
| 285 | +check "HTML has a doctype" '<!DOCTYPE html>' "$HB" | |
| 286 | +check "HTML names the plugin" ">ports<" "$HB" | |
| 287 | +check "HTML has the listener table body" "id='rows'" "$HB" | |
| 288 | +check "HTML has the probe control" "Probe 127.0.0.1" "$HB" | |
| 289 | +check "HTML has the scope filter" "id='sc'" "$HB" | |
| 290 | +check "HTML has the protocol filter" "id='pr'" "$HB" | |
| 291 | +check "HTML has the search box" "id='q'" "$HB" | |
| 292 | +check "HTML has the rescan button" "id='rfBtn'" "$HB" | |
| 293 | +check "HTML has the theme toggle" "id='thBtn'" "$HB" | |
| 294 | +check "HTML labels the loopback probe target" "127.0.0.1" "$HB" | |
| 295 | +check_not "HTML emits no Content-Length" 'Content-Length' "$H" | |
| 296 | +check_not "HTML has no emoji" '€' "$HB" | |
| 297 | +check_not "HTML has no inline http:// egress" "http://" "$HB" | |
| 298 | +check_not "HTML has no inline https:// egress" "https://" "$HB" | |
| 299 | + | |
| 300 | +HE=$(QUERY_STRING='embed=1' $BIN) | |
| 301 | +HEB=$(body "$HE") | |
| 302 | +check_not "embed=1 drops the back link" "←" "$HEB" | |
| 303 | +check "embed=1 still renders the table" "id='rows'" "$HEB" | |
| 304 | +HN=$(QUERY_STRING='embed=0' $BIN) | |
| 305 | +check "embed=0 keeps the back link" "←" "$(body "$HN")" | |
| 306 | + | |
| 307 | +# The UI must call the hub proxy when it was served through it, and the plugin | |
| 308 | +# route when it was opened directly on the node. | |
| 309 | +check "UI understands the hub proxy route" "q.get('plugin')" "$(cat src/plugin_ports.c)" | |
| 310 | +check "UI falls back to the direct plugin route" "/plugin_ports" "$(cat src/plugin_ports.c)" | |
| 311 | + | |
| 312 | +# ---------------------------------------------------------------- source hygiene | |
| 313 | +section "source hygiene" | |
| 314 | +SRC=$(cat src/plugin_ports.c) | |
| 315 | +check "reads /proc/net/tcp directly" '/proc/net/tcp' "$SRC" | |
| 316 | +check "reads /proc/net/tcp6 directly" '/proc/net/tcp6' "$SRC" | |
| 317 | +check "reads /proc/net/udp directly" '/proc/net/udp' "$SRC" | |
| 318 | +check "resolves owners from /proc/<pid>/fd" '/fd' "$SRC" | |
| 319 | +check "never reads an external host parameter" '127, 0, 0, 1' "$SRC" | |
| 320 | +check "uses lsof on macOS" 'lsof' "$SRC" | |
| 321 | +check "uses GetExtendedTcpTable on Windows" 'GetExtendedTcpTable' "$SRC" | |
| 322 | +check "uses GetExtendedUdpTable on Windows" 'GetExtendedUdpTable' "$SRC" | |
| 323 | +check "guards _DARWIN_C_SOURCE for Apple clang" '_DARWIN_C_SOURCE' "$SRC" | |
| 324 | +check_not "no shelling out to ss(8)" 'popen("ss' "$SRC" | |
| 325 | +check "the netstat fallback exists for macOS only" 'collect_netstat_fallback' "$SRC" | |
| 326 | +check_not "no embedded http:// URL" 'http://' "$SRC" | |
| 327 | +check_not "no embedded https:// URL" 'https://' "$SRC" | |
| 328 | + | |
| 329 | +# ---------------------------------------------------------------- cross builds | |
| 330 | +section "cross-platform artifacts" | |
| 331 | +if [ -f "$BIN.musl" ]; then | |
| 332 | + if file "$BIN.musl" 2>/dev/null | grep -q 'statically linked'; then | |
| 333 | + pass "musl build is statically linked" | |
| 334 | + else | |
| 335 | + pass "musl build present (file(1) unavailable or non-static report)" | |
| 336 | + fi | |
| 337 | + MB=$(body "$(QUERY_STRING='action=listeners' "$BIN".musl)") | |
| 338 | + check "musl build runs" '"ok":true' "$MB" | |
| 339 | +else | |
| 340 | + echo " skip musl build (not built here)" | |
| 341 | +fi | |
| 342 | + | |
| 343 | +if [ -f plugin_ports.exe ]; then | |
| 344 | + if [ "$(head -c 2 plugin_ports.exe)" = "MZ" ]; then | |
| 345 | + pass "windows artifact starts with an MZ header" | |
| 346 | + else | |
| 347 | + fail "windows artifact is not a PE" | |
| 348 | + fi | |
| 349 | + SZ=$(wc -c < plugin_ports.exe | tr -d ' ') | |
| 350 | + if [ "$SZ" -gt 20000 ]; then pass "windows artifact has a plausible size"; else fail "windows artifact is too small"; fi | |
| 351 | +else | |
| 352 | + echo " skip windows artifact (not built here)" | |
| 353 | +fi | |
| 354 | + | |
| 355 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json; do | |
| 356 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | |
| 357 | +done | |
| 358 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | |
| 359 | +check "README documents the actions" 'action=probe' "$(cat README.md)" | |
| 360 | +check "README documents the loopback-only rule" '127.0.0.1' "$(cat README.md)" | |
| 361 | +check "plugin.json declares the slug" '"slug": "ports"' "$(cat plugin.json)" | |
| 362 | +check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)" | |
| 363 | + | |
| 364 | +# ---------------------------------------------------------------- history audit | |
| 365 | +section "git history secret audit" | |
| 366 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 367 | + ALL="$WORK/history.txt" | |
| 368 | + git log -p --all 2>/dev/null \ | |
| 369 | + | grep -v '^Author: ' \ | |
| 370 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \ | |
| 371 | + > "$ALL" || : > "$ALL" | |
| 372 | + | |
| 373 | + audit() { # audit <label> <regex> | |
| 374 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 375 | + if [ -n "$H" ]; then | |
| 376 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 377 | + else | |
| 378 | + pass "history clean: $1" | |
| 379 | + fi | |
| 380 | + } | |
| 381 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 382 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 383 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 384 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 385 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 386 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 387 | + PK="pico""bot"; WT=".work""trees" | |
| 388 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | |
| 389 | + audit "run token assignment" 'RUNNER_'"PASS=" | |
| 390 | +else | |
| 391 | + echo " skip history audit (not a git checkout)" | |
| 392 | +fi | |
| 393 | + | |
| 394 | +# ---------------------------------------------------------------- cleanup | |
| 395 | +kill "$LISTENER_PID" 2>/dev/null | |
| 396 | +kill "$UDP_PID" 2>/dev/null | |
| 397 | +wait "$LISTENER_PID" 2>/dev/null | |
| 398 | +wait "$UDP_PID" 2>/dev/null | |
| 399 | +rm -rf "$WORK" | |
| 400 | + | |
| 401 | +# ---------------------------------------------------------------- summary | |
| 402 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 403 | +printf ' passed: %d\n' "$PASS" | |
| 404 | +printf ' failed: %d\n' "$FAIL" | |
| 405 | +if [ "$FAIL" -ne 0 ]; then | |
| 406 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | |
| 407 | + exit 1 | |
| 408 | +fi | |
| 409 | +if [ "$PASS" -lt 60 ]; then | |
| 410 | + printf ' %sRESULT: TOO FEW CHECKS (%d < 60)%s\n' "$C_BAD" "$PASS" "$C_0" | |
| 411 | + exit 1 | |
| 412 | +fi | |
| 413 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | |
| 414 | +exit 0 | |
| 0 | 415 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a8e8b3b | index 0000000..a8e8b3b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,9 @@ | @@ -0,0 +1,9 @@ | ||
| 1 | +/plugin_ports | ||
| 2 | +/plugin_ports.musl | ||
| 3 | +/plugin_ports.arm64 | ||
| 4 | +/plugin_ports.exe | ||
| 5 | +/plugin_ports.macos-arm64 | ||
| 6 | +/plugin_ports.macos-x86_64 | ||
| 7 | +*.o | ||
| 8 | +*.tmp | ||
| 9 | +*.dSYM |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 0000000..ef80120 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..df60112 | index 0000000..df60112 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,63 @@ | @@ -0,0 +1,63 @@ | ||
| 1 | +# plugin_ports - ScorpioX Bot open-source local listening socket inspector | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_ports | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_ports.musl | ||
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_ports.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_ports.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_ports (run this on macOS) | ||
| 9 | +# make test build + run tests/run.sh | ||
| 10 | +# make clean | ||
| 11 | + | ||
| 12 | +CC ?= cc | ||
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | ||
| 14 | +MUSL_CC ?= musl-gcc | ||
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 16 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 17 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 18 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 19 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 20 | +WIN_LIBS := -liphlpapi -lws2_32 | ||
| 21 | +SRC := src/plugin_ports.c | ||
| 22 | +BIN := plugin_ports | ||
| 23 | +EXE := plugin_ports.exe | ||
| 24 | + | ||
| 25 | +.PHONY: all native musl arm64 win64 macos test clean help | ||
| 26 | + | ||
| 27 | +all: native | ||
| 28 | + | ||
| 29 | +native: $(BIN) | ||
| 30 | + | ||
| 31 | +$(BIN): $(SRC) | ||
| 32 | + @echo "==> native build ($(CC))" | ||
| 33 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 34 | + | ||
| 35 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 36 | +musl: $(SRC) | ||
| 37 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 38 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | ||
| 39 | + | ||
| 40 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 41 | +arm64: $(SRC) | ||
| 42 | + @echo "==> static arm64 build ($(ARM_CC))" | ||
| 43 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | ||
| 44 | + | ||
| 45 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 46 | +win64: $(SRC) | ||
| 47 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 48 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) $(WIN_LIBS) | ||
| 49 | + | ||
| 50 | +# Apple clang build (run this on macOS) | ||
| 51 | +macos: $(SRC) | ||
| 52 | + @echo "==> Apple clang build" | ||
| 53 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 54 | + | ||
| 55 | +test: native | ||
| 56 | + @sh tests/run.sh | ||
| 57 | + | ||
| 58 | +clean: | ||
| 59 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 60 | + rm -rf bin | ||
| 61 | + | ||
| 62 | +help: | ||
| 63 | + @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f142b17 | index 0000000..f142b17 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,202 @@ | @@ -0,0 +1,202 @@ | ||
| 1 | +# plugin_ports | ||
| 2 | + | ||
| 3 | +A clean-room, zero-dependency **local listening socket inspector** for | ||
| 4 | +[ScorpioX Bot](https://code.scorpiox.net). One C99 binary, three modes, no | ||
| 5 | +runtime dependencies at all. It reports the TCP and UDP sockets listening on the | ||
| 6 | +node it runs on, who owns them, and whether `127.0.0.1:<port>` actually answers. | ||
| 7 | + | ||
| 8 | +``` | ||
| 9 | +ports Listening TCP | ||
| 10 | +``` | ||
| 11 | + | ||
| 12 | +## Why /proc instead of ss(8) | ||
| 13 | + | ||
| 14 | +Agent containers and slim BotCloud images routinely ship without `ss` or | ||
| 15 | +`netstat`. Anything that shells out to them reports "no listeners" on exactly | ||
| 16 | +the machines where you most want to know what is listening. This plugin parses | ||
| 17 | +`/proc/net/tcp`, `/proc/net/tcp6`, `/proc/net/udp` and `/proc/net/udp6` | ||
| 18 | +directly, and resolves the owning process from `/proc/<pid>/fd` socket inodes. | ||
| 19 | +The offline test suite proves this by running the plugin with a `PATH` that | ||
| 20 | +contains no socket tool at all - and still detecting a freshly opened listener, | ||
| 21 | +with its PID and command name. | ||
| 22 | + | ||
| 23 | +Platforms: | ||
| 24 | + | ||
| 25 | +| Platform | Listening sockets | Owning process | | ||
| 26 | +|---|---|---| | ||
| 27 | +| Linux | `/proc/net/{tcp,tcp6,udp,udp6}` parsed in C | `/proc/<pid>/fd` inode match, command from `/proc/<pid>/comm` | | ||
| 28 | +| macOS | `lsof -nP -iTCP -sTCP:LISTEN` / `-iUDP`, falling back to `netstat -an` | from the `lsof` PID column | | ||
| 29 | +| Windows | `GetExtendedTcpTable(TCP_TABLE_OWNER_PID_LISTENER)` + `GetExtendedUdpTable` | owning PID from the table, image name via `QueryFullProcessImageName` | | ||
| 30 | + | ||
| 31 | +## The loopback-only probe | ||
| 32 | + | ||
| 33 | +`?action=probe&port=<1..65535>` opens exactly one TCP connection, to | ||
| 34 | +**`127.0.0.1`**. The destination is a `static const unsigned char` in the source | ||
| 35 | +and is never read from a query parameter, header or environment variable, so the | ||
| 36 | +plugin cannot be pointed at another host. That matters: a port scanner that can | ||
| 37 | +be aimed anywhere is an SSRF pivot, and this one cannot be. | ||
| 38 | + | ||
| 39 | +It reports: | ||
| 40 | + | ||
| 41 | +* `open` - did the connect succeed (2 s non-blocking timeout) | ||
| 42 | +* `connect_ms` - how long the connect took | ||
| 43 | +* `http_tried` / `http_ok` / `http_status` / `http_ms` - a bounded `HEAD /` over | ||
| 44 | + the same socket, if the connect succeeded, so an HTTP service reports its | ||
| 45 | + status code and a non-HTTP service simply reports no response | ||
| 46 | + | ||
| 47 | +## Modes | ||
| 48 | + | ||
| 49 | +### 1. Discovery metadata | ||
| 50 | + | ||
| 51 | +```sh | ||
| 52 | +./plugin_ports --meta | ||
| 53 | +# {"name":"ports","desc":"Listening TCP"} | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +`SX_PLUGIN_META=1` does the same. `--meta` is unauthenticated on purpose so | ||
| 57 | +`/plugins` discovery keeps working. | ||
| 58 | + | ||
| 59 | +### 2. JSON API | ||
| 60 | + | ||
| 61 | +```sh | ||
| 62 | +QUERY_STRING='action=listeners' ./plugin_ports | ||
| 63 | +QUERY_STRING='action=probe&port=8150' ./plugin_ports | ||
| 64 | +QUERY_STRING='format=json' ./plugin_ports | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +`action=listeners`: | ||
| 68 | + | ||
| 69 | +```json | ||
| 70 | +{ | ||
| 71 | + "ok": true, | ||
| 72 | + "action": "listeners", | ||
| 73 | + "source": "procfs", | ||
| 74 | + "count": 3, | ||
| 75 | + "summary": {"tcp": 2, "udp": 1, "loopback": 1, "wildcard": 2, "specific": 0}, | ||
| 76 | + "listeners": [ | ||
| 77 | + {"proto": "tcp", "bind_addr": "0.0.0.0", "port": 22, "scope": "wildcard", "pid": 24, "comm": "sshd"}, | ||
| 78 | + {"proto": "tcp", "bind_addr": "127.0.0.1", "port": 8150, "scope": "loopback", "pid": 812, "comm": "scorpiox-server"}, | ||
| 79 | + {"proto": "udp", "bind_addr": "127.0.0.1", "port": 5353, "scope": "loopback", "pid": 77, "comm": "mdns"} | ||
| 80 | + ] | ||
| 81 | +} | ||
| 82 | +``` | ||
| 83 | + | ||
| 84 | +`scope` is `loopback` (`127.0.0.0/8`, `::1`), `wildcard` (`0.0.0.0`, `::`) or | ||
| 85 | +`specific` (any other bound address). `source` is `procfs`, `lsof` or | ||
| 86 | +`windows-tables` depending on platform. | ||
| 87 | + | ||
| 88 | +`action=probe&port=N`: | ||
| 89 | + | ||
| 90 | +```json | ||
| 91 | +{ | ||
| 92 | + "ok": true, | ||
| 93 | + "action": "probe", | ||
| 94 | + "target": "127.0.0.1", | ||
| 95 | + "port": 8150, | ||
| 96 | + "open": true, | ||
| 97 | + "refused": false, | ||
| 98 | + "connect_ms": 0, | ||
| 99 | + "http_tried": true, | ||
| 100 | + "http_ok": true, | ||
| 101 | + "http_status": 200, | ||
| 102 | + "http_ms": 4, | ||
| 103 | + "checked_at": "2026-11-11T05:39:50Z" | ||
| 104 | +} | ||
| 105 | +``` | ||
| 106 | + | ||
| 107 | +Errors are always JSON with `"ok": false` and a human `error` string. A port | ||
| 108 | +outside `1..65535`, or a missing/non-numeric port, is rejected before any socket | ||
| 109 | +is opened. | ||
| 110 | + | ||
| 111 | +### 3. HTML UI | ||
| 112 | + | ||
| 113 | +A plain `GET` serves a responsive dark/light inspector at the node route | ||
| 114 | +(`/plugin_ports`) and through the Bot hub (`/plugins?plugin=plugin_ports`). It | ||
| 115 | +shows KPI counts, a filterable table (free-text across port/process/address, | ||
| 116 | +plus scope and protocol filters), a `Probe 127.0.0.1` button on every row, and a | ||
| 117 | +standalone probe box. `?embed=1` drops the back link for the chat floating | ||
| 118 | +window. | ||
| 119 | + | ||
| 120 | +## Authentication | ||
| 121 | + | ||
| 122 | +When `BOT_PASSWORD` is set in the node environment, every mode except `--meta` | ||
| 123 | +requires it via `X-Bot-Password: <pwd>`, `Authorization: Bearer <pwd>` or | ||
| 124 | +`?pwd=<pwd>`. Without it a request gets `Status: 401 Unauthorized` and no data. | ||
| 125 | +If `BOT_PASSWORD` is unset the plugin is a no-op (local operator use only). | ||
| 126 | + | ||
| 127 | +## Build | ||
| 128 | + | ||
| 129 | +```sh | ||
| 130 | +make # native glibc build -> ./plugin_ports | ||
| 131 | +make musl # static x86_64 build -> ./plugin_ports.musl | ||
| 132 | +make arm64 # static aarch64 build -> ./plugin_ports.arm64 | ||
| 133 | +make win64 # static Windows PE -> ./plugin_ports.exe | ||
| 134 | +make macos # Apple clang (on macOS) -> ./plugin_ports | ||
| 135 | +make test # build + tests/run.sh | ||
| 136 | +``` | ||
| 137 | + | ||
| 138 | +Windows uses `-liphlpapi -lws2_32`. macOS needs `_DARWIN_C_SOURCE` under | ||
| 139 | +`-std=c99`; the source defines it on `__APPLE__`. | ||
| 140 | + | ||
| 141 | +## Install on a node | ||
| 142 | + | ||
| 143 | +```sh | ||
| 144 | +make musl && install -m 0755 plugin_ports.musl ~/.scorpiox/plugins/plugin_ports | ||
| 145 | +``` | ||
| 146 | + | ||
| 147 | +or, on BotCloud containers, `/workspace/.scorpiox/plugins/`. No restart: the | ||
| 148 | +node resolves `plugin_*` routes on every request. | ||
| 149 | + | ||
| 150 | +Prebuilts for every platform are published at | ||
| 151 | +`https://dist.scorpiox.net/bot-plugins/ports/`, and the Bot marketplace can | ||
| 152 | +install them one click or compile this source on the node itself. | ||
| 153 | + | ||
| 154 | +## Tests | ||
| 155 | + | ||
| 156 | +`tests/run.sh` runs 60+ offline assertions with no network access: | ||
| 157 | + | ||
| 158 | +* metadata shape and the 15-character description rule | ||
| 159 | +* listener collection against the real kernel, including a temporary loopback | ||
| 160 | + TCP listener and a temporary bound UDP socket it opens itself | ||
| 161 | +* the same detection with `ss`, `netstat` and `lsof` removed from `PATH` | ||
| 162 | +* owner PID and command resolution for the detected sockets | ||
| 163 | +* scope classification (`127.x`/`::1` vs `0.0.0.0`/`::` vs specific) | ||
| 164 | +* probe against the live listener (open, connect latency, HTTP attempt) and | ||
| 165 | + against a closed port (refused, no HTTP attempt) | ||
| 166 | +* port validation (`0`, `70000`, missing, non-numeric) | ||
| 167 | +* the SSRF controls: `host=` and `addr=` parameters are ignored, and the source | ||
| 168 | + never reads one | ||
| 169 | +* authentication across all four credential carriers, and `--meta` staying open | ||
| 170 | +* HTML structure, `?embed=1`, and no `Content-Length` anywhere | ||
| 171 | +* a full `git log -p --all` audit for LAN addresses, PATs, tokens and fleet paths | ||
| 172 | + | ||
| 173 | +`tests/e2e.py` adds Playwright viewport checks at 1440 / 1024 / 390 and skips | ||
| 174 | +cleanly when Playwright is absent. | ||
| 175 | + | ||
| 176 | +## Release | ||
| 177 | + | ||
| 178 | +```sh | ||
| 179 | +DIST_HOST=<ssh-target> DIST_PASS=<pw> MAC_HOST=<mac> MAC_USER=<user> MAC_PASS=<pw> ./release-dist.sh | ||
| 180 | +``` | ||
| 181 | + | ||
| 182 | +The script runs a full-history secret scan first and refuses to publish on any | ||
| 183 | +hit, builds every target, writes `manifest.json` + `SHA256SUMS` + `source.tar.gz`, | ||
| 184 | +uploads to `dist.scorpiox.net/bot-plugins/ports/1.0.0/`, refreshes `latest.json` | ||
| 185 | +and the aggregate `index.json`, and mirrors the repository to plugingit. | ||
| 186 | + | ||
| 187 | +## Capabilities and trust | ||
| 188 | + | ||
| 189 | +```json | ||
| 190 | +{ | ||
| 191 | + "capabilities": ["procfs_read", "local_socket_list", "loopback_probe"], | ||
| 192 | + "trust_notice": "Executes native C code on your node. Reads local kernel socket tables and /proc, and opens exactly one TCP connection to 127.0.0.1 when you ask it to probe a port. Never connects to a remote host and makes zero outbound network requests on its own." | ||
| 193 | +} | ||
| 194 | +``` | ||
| 195 | + | ||
| 196 | +It reads only local kernel structures and `/proc`. The single socket it ever | ||
| 197 | +opens goes to loopback. It never writes a file, never changes a socket and never | ||
| 198 | +touches another machine. | ||
| 199 | + | ||
| 200 | +## License | ||
| 201 | + | ||
| 202 | +MIT - see `LICENSE`. Copyright (c) 2026 SCORPIOX INC. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..d8b9e9d | index 0000000..d8b9e9d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,53 @@ | @@ -0,0 +1,53 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_ports | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_ports.exe (static PE, runs on any Windows 10/11 x64 node). | ||
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | ||
| 8 | + | ||
| 9 | +$ErrorActionPreference = "Stop" | ||
| 10 | +$ScriptDir = $PSScriptRoot | ||
| 11 | +Push-Location $ScriptDir | ||
| 12 | +try { | ||
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_ports.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_ports.exe" | ||
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | ||
| 16 | + | ||
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | ||
| 18 | + | ||
| 19 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | ||
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | ||
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | ||
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | ||
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | ||
| 24 | + $Cc = "gcc" | ||
| 25 | + } else { | ||
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + Write-Host "==> building plugin_ports.exe with $Cc" | ||
| 31 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -o $Out $Src -liphlpapi -lws2_32 | ||
| 32 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 33 | + | ||
| 34 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 35 | + | ||
| 36 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | ||
| 37 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 38 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 39 | + throw "output is not a PE executable (missing MZ header)" | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + Write-Host "==> metadata check" | ||
| 43 | + & $Out --meta | ||
| 44 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | ||
| 45 | + | ||
| 46 | + $size = (Get-Item $Out).Length | ||
| 47 | + Write-Host "" | ||
| 48 | + Write-Host "Built $Out ($size bytes)" | ||
| 49 | + Write-Host "Install: Copy-Item plugin_ports.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | ||
| 50 | +} | ||
| 51 | +finally { | ||
| 52 | + Pop-Location | ||
| 53 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..08ce6be | index 0000000..08ce6be | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,12 @@ | @@ -0,0 +1,12 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "ports", | ||
| 3 | + "id": "plugin_ports", | ||
| 4 | + "title": "Local Listening Port Inspector", | ||
| 5 | + "summary": "Zero-dependency inspector for the listening TCP and UDP sockets on your node: bind address, port, loopback-versus-wildcard exposure, owning PID and command, plus a one-click 127.0.0.1 health probe that reports connect and HTTP latency. Parses /proc/net directly on Linux so it keeps working inside containers that have no ss or netstat.", | ||
| 6 | + "category": "network", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": ["procfs_read", "local_socket_list", "loopback_probe"], | ||
| 9 | + "trust_notice": "Executes native C code on your node. Reads local kernel socket tables and /proc, and opens exactly one TCP connection to 127.0.0.1 when you ask it to probe a port. Never connects to a remote host and makes zero outbound network requests on its own.", | ||
| 10 | + "author": "SCORPIOX INC", | ||
| 11 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-ports" | ||
| 12 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..8a91ea2 | index 0000000..8a91ea2 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,357 @@ | @@ -0,0 +1,357 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh - build, scan and publish plugin_ports to the plugin registry. | ||
| 3 | +# | ||
| 4 | +# Two paths: | ||
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | ||
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | ||
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | ||
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | ||
| 9 | +# | ||
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | ||
| 11 | +# comes from the environment, so this file stays safe to publish: | ||
| 12 | +# | ||
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | ||
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | ||
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | ||
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | ||
| 17 | +# MAC_USER / MAC_PASS (optional) | ||
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | ||
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | ||
| 20 | +# | ||
| 21 | +# Usage: | ||
| 22 | +# ./release-dist.sh # full release | ||
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | ||
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | ||
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | ||
| 26 | + | ||
| 27 | +set -euo pipefail | ||
| 28 | + | ||
| 29 | +SLUG="ports" | ||
| 30 | +ID="plugin_ports" | ||
| 31 | +VERSION="1.0.0" | ||
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 33 | + | ||
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 35 | +cd "$ROOT" | ||
| 36 | + | ||
| 37 | +DRY_RUN=0 | ||
| 38 | +DO_MACOS=1 | ||
| 39 | +DO_MIRROR=1 | ||
| 40 | +for arg in "$@"; do | ||
| 41 | + case "$arg" in | ||
| 42 | + --dry-run) DRY_RUN=1 ;; | ||
| 43 | + --no-macos) DO_MACOS=0 ;; | ||
| 44 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 45 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | ||
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 47 | + esac | ||
| 48 | +done | ||
| 49 | + | ||
| 50 | +DIST_HOST="${DIST_HOST:-}" | ||
| 51 | +DIST_PASS="${DIST_PASS:-}" | ||
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 55 | + | ||
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 57 | +mkdir -p "$STAGE" | ||
| 58 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 59 | + | ||
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 62 | + | ||
| 63 | +# ---------------------------------------------------------------- 0. preflight | ||
| 64 | +say "0/7 preflight" | ||
| 65 | + | ||
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 67 | + say "using scorpiox-cli-botplugin publish" | ||
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 69 | +fi | ||
| 70 | +echo " scorpiox-cli-botplugin not installed - running standalone pipeline" | ||
| 71 | + | ||
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 75 | +echo " version $VERSION" | ||
| 76 | +echo " commit $COMMIT" | ||
| 77 | + | ||
| 78 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 79 | +say "1/7 secret & LAN scan (full history)" | ||
| 80 | + | ||
| 81 | +SCAN_TMP="$STAGE/history.txt" | ||
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 83 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 84 | +# itself a scan definition - otherwise this file's own detector patterns read as | ||
| 85 | +# findings in every historical revision of it. | ||
| 86 | +git log -p --all 2>/dev/null \ | ||
| 87 | + | grep -v '^Author: ' \ | ||
| 88 | + | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="|\$ALL' \ | ||
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 90 | +HITS=0 | ||
| 91 | +scan() { # scan <label> <regex> | ||
| 92 | + local out | ||
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 94 | + if [ -n "$out" ]; then | ||
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 97 | + HITS=$((HITS + 1)) | ||
| 98 | + else | ||
| 99 | + printf ' ok %s\n' "$1" | ||
| 100 | + fi | ||
| 101 | +} | ||
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 109 | +P_ROOT="/codebases" | ||
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 111 | +P_WT=".work""trees" | ||
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 114 | +if [ "$HITS" -ne 0 ]; then | ||
| 115 | + die "secret scan found $HITS problem(s) - refusing to publish" | ||
| 116 | +fi | ||
| 117 | +echo " clean: 0 hits" | ||
| 118 | + | ||
| 119 | +# ---------------------------------------------------------------- 2. build | ||
| 120 | +say "2/7 build targets" | ||
| 121 | + | ||
| 122 | +# linux-x86_64 (glibc, native) | ||
| 123 | +if command -v cc >/dev/null 2>&1; then | ||
| 124 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | ||
| 125 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 126 | +else | ||
| 127 | + die "no native cc found" | ||
| 128 | +fi | ||
| 129 | + | ||
| 130 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | ||
| 131 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 132 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | ||
| 133 | + || die "musl build failed" | ||
| 134 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 135 | +else | ||
| 136 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 137 | +fi | ||
| 138 | + | ||
| 139 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | ||
| 140 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 141 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 142 | + || die "arm64 build failed" | ||
| 143 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 144 | +else | ||
| 145 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | ||
| 146 | +fi | ||
| 147 | + | ||
| 148 | +# windows-x86_64 (static PE) | ||
| 149 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 150 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | ||
| 151 | + -liphlpapi -lws2_32 || die "MinGW build failed" | ||
| 152 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 153 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 154 | +else | ||
| 155 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 156 | +fi | ||
| 157 | + | ||
| 158 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | ||
| 159 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 160 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 161 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 162 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 163 | + echo " building macOS legs on $MAC_HOST" | ||
| 164 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 165 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 166 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 167 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 168 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 169 | + fi | ||
| 170 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 171 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | ||
| 172 | + # Build straight from the uploaded file - no src/ tree on the remote. | ||
| 173 | + for slice in arm64 x86_64; do | ||
| 174 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 175 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | ||
| 176 | + 2>/dev/null; then | ||
| 177 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 178 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 179 | + else | ||
| 180 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 181 | + fi | ||
| 182 | + done | ||
| 183 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | ||
| 184 | + else | ||
| 185 | + echo " warn: could not upload source to $MAC_HOST" | ||
| 186 | + fi | ||
| 187 | + else | ||
| 188 | + echo " warn: cannot reach macOS builder $MAC_HOST" | ||
| 189 | + fi | ||
| 190 | +else | ||
| 191 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | ||
| 192 | +fi | ||
| 193 | + | ||
| 194 | +# ---------------------------------------------------------------- 3. manifest | ||
| 195 | +say "3/7 manifest + checksums" | ||
| 196 | + | ||
| 197 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 198 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 199 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 200 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 201 | + | ||
| 202 | +target_meta() { # target_meta <key> <file> <format> <relpath> | ||
| 203 | + local key="$1" file="$2" fmt="$3" rel="$4" | ||
| 204 | + [ -f "$file" ] || return 0 | ||
| 205 | + local sha size | ||
| 206 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 207 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 208 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 209 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +{ | ||
| 213 | + printf '{\n' | ||
| 214 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 215 | + printf ' "id": "%s",\n' "$ID" | ||
| 216 | + printf ' "name": "ports",\n' | ||
| 217 | + printf ' "desc": "Listening TCP",\n' | ||
| 218 | + printf ' "title": "Local Listening Port Inspector",\n' | ||
| 219 | + printf ' "summary": "Zero-dependency inspector for the listening TCP and UDP sockets on your node: bind address, port, loopback-versus-wildcard exposure, owning PID and command, plus a one-click 127.0.0.1 health probe that reports connect and HTTP latency. Parses /proc/net directly on Linux so it keeps working inside containers that have no ss or netstat.",\n' | ||
| 220 | + printf ' "category": "network",\n' | ||
| 221 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 222 | + printf ' "license": "MIT",\n' | ||
| 223 | + printf ' "trust_notice": "Executes native C code on your node. Reads local kernel socket tables and /proc, and opens exactly one TCP connection to 127.0.0.1 when you ask it to probe a port. Never connects to a remote host and makes zero outbound network requests on its own.",\n' | ||
| 224 | + printf ' "capabilities": ["procfs_read", "local_socket_list", "loopback_probe"],\n' | ||
| 225 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 226 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 227 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 228 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 229 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 230 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 231 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c -liphlpapi -lws2_32",\n' "$ID" "$ID" | ||
| 232 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 233 | + printf ' "targets": {\n' | ||
| 234 | + first=1 | ||
| 235 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 236 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | ||
| 237 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | ||
| 238 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | ||
| 239 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | ||
| 240 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | ||
| 241 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | ||
| 242 | + printf '\n }\n}\n' | ||
| 243 | +} > "$STAGE/manifest.json" | ||
| 244 | + | ||
| 245 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 246 | + || die "generated manifest.json is not valid JSON" | ||
| 247 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | ||
| 248 | + | ||
| 249 | +# SHA256SUMS - relative paths, exactly as published | ||
| 250 | +( cd "$STAGE" | ||
| 251 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 252 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 253 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 254 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 255 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 256 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 257 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 258 | + true ) > "$STAGE/SHA256SUMS" | ||
| 259 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 260 | + | ||
| 261 | +# ---------------------------------------------------------------- 4. stage | ||
| 262 | +say "4/7 stage tree" | ||
| 263 | +PKG="$STAGE/pkg" | ||
| 264 | +mkdir -p "$PKG" | ||
| 265 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 266 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | ||
| 267 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | ||
| 268 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | ||
| 269 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | ||
| 270 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | ||
| 271 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | ||
| 272 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | ||
| 273 | + | ||
| 274 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 275 | + say "dry run - leaving the staging tree in $PKG" | ||
| 276 | + trap - EXIT | ||
| 277 | + exit 0 | ||
| 278 | +fi | ||
| 279 | + | ||
| 280 | +# ---------------------------------------------------------------- 5. upload | ||
| 281 | +say "5/7 upload to the dist server" | ||
| 282 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | ||
| 283 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 284 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 285 | +if [ -n "$DIST_PASS" ]; then | ||
| 286 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 287 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 288 | +fi | ||
| 289 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 290 | + | ||
| 291 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 292 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 293 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 294 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 295 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 296 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 297 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 298 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 299 | + || die "remote extract failed" | ||
| 300 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 301 | + | ||
| 302 | +# latest.json = copy of this version's manifest | ||
| 303 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 304 | + || die "latest.json update failed" | ||
| 305 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 306 | + | ||
| 307 | +# index.json - merge, preserving every sibling <slug>/latest.json | ||
| 308 | +say "index.json merge" | ||
| 309 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 310 | +import json, os, sys, glob | ||
| 311 | +slug = sys.argv[1] | ||
| 312 | +entries = {} | ||
| 313 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 314 | + s = os.path.dirname(p) | ||
| 315 | + try: | ||
| 316 | + entries[s] = json.load(open(p)) | ||
| 317 | + except Exception: | ||
| 318 | + pass | ||
| 319 | +index = { | ||
| 320 | + 'ok': True, | ||
| 321 | + 'service': 'bot-plugins-dist', | ||
| 322 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 323 | + 'count': len(entries), | ||
| 324 | + 'slugs': sorted(entries), | ||
| 325 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 326 | +} | ||
| 327 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 328 | +os.replace('index.json.tmp', 'index.json') | ||
| 329 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 330 | +PY" || die "index.json merge failed" | ||
| 331 | + | ||
| 332 | +# ---------------------------------------------------------------- 6. mirror | ||
| 333 | +say "6/7 plugingit mirror" | ||
| 334 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 335 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 336 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | ||
| 337 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 338 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 339 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 340 | +else | ||
| 341 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 342 | +fi | ||
| 343 | + | ||
| 344 | +# ---------------------------------------------------------------- 7. verify | ||
| 345 | +say "7/7 verify" | ||
| 346 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 347 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 348 | +if [ "$CODE" = "200" ]; then | ||
| 349 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | ||
| 350 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 351 | +else | ||
| 352 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 353 | +fi | ||
| 354 | + | ||
| 355 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 356 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 357 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..9d83b0c | index 0000000..9d83b0c | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_ports.c | +++ b/src/plugin_ports.c | ||
| @@ -0,0 +1,1396 @@ | @@ -0,0 +1,1396 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_ports - ScorpioX Bot open-source local listening socket inspector | ||
| 3 | + * | ||
| 4 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | ||
| 6 | + * 2. ?action=listeners | ?action=probe&port=N | ?format=json -> JSON node API | ||
| 7 | + * 3. GET (default) -> responsive HTML inspector | ||
| 8 | + * | ||
| 9 | + * Everything it reports is LOCAL to the node. Listening sockets come from | ||
| 10 | + * /proc/net/tcp{,6} and /proc/net/udp{,6} parsed directly (so it keeps working | ||
| 11 | + * inside minimal containers where ss(8) and netstat(8) are not installed), from | ||
| 12 | + * lsof(8)/netstat(8) on macOS, and from GetExtendedTcpTable/GetExtendedUdpTable | ||
| 13 | + * on Windows. Owners are resolved from /proc/<pid>/fd socket inodes on Linux and | ||
| 14 | + * from the OS table on Windows. | ||
| 15 | + * | ||
| 16 | + * The probe action opens exactly one TCP connection, and its destination is | ||
| 17 | + * hard-coded to the loopback address. There is no parameter anywhere in this | ||
| 18 | + * file that can redirect it at another host, so the plugin cannot be used as an | ||
| 19 | + * SSRF pivot. | ||
| 20 | + * | ||
| 21 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 22 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 23 | + * scorpiox-server on the node. | ||
| 24 | + * | ||
| 25 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 26 | + */ | ||
| 27 | + | ||
| 28 | +/* Must come before every include: iphlpapi.h and ws2tcpip.h gate | ||
| 29 | + * GetExtendedTcpTable/QueryFullProcessImageName/inet_ntop on it, and MinGW | ||
| 30 | + * defaults to 0x502 (Server 2003) which hides all three. */ | ||
| 31 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 32 | +# define _WIN32_WINNT 0x0601 | ||
| 33 | +#endif | ||
| 34 | + | ||
| 35 | +#if !defined(_WIN32) | ||
| 36 | +# define _POSIX_C_SOURCE 200809L | ||
| 37 | +# define _DEFAULT_SOURCE 1 | ||
| 38 | +# if defined(__APPLE__) | ||
| 39 | +# define _DARWIN_C_SOURCE 1 | ||
| 40 | +# endif | ||
| 41 | +#endif | ||
| 42 | + | ||
| 43 | +#include <stdio.h> | ||
| 44 | +#include <stdlib.h> | ||
| 45 | +#include <string.h> | ||
| 46 | +#include <ctype.h> | ||
| 47 | +#include <errno.h> | ||
| 48 | +#include <time.h> | ||
| 49 | + | ||
| 50 | +#if defined(_WIN32) | ||
| 51 | +# define WIN32_LEAN_AND_MEAN | ||
| 52 | +# include <winsock2.h> | ||
| 53 | +# include <ws2tcpip.h> | ||
| 54 | +# include <windows.h> | ||
| 55 | +# include <iphlpapi.h> | ||
| 56 | +# define sx_popen _popen | ||
| 57 | +# define sx_pclose _pclose | ||
| 58 | +# define sx_close_socket closesocket | ||
| 59 | +#else | ||
| 60 | +# include <unistd.h> | ||
| 61 | +# include <dirent.h> | ||
| 62 | +# include <fcntl.h> | ||
| 63 | +# include <sys/types.h> | ||
| 64 | +# include <sys/socket.h> | ||
| 65 | +# include <sys/select.h> | ||
| 66 | +# include <sys/time.h> | ||
| 67 | +# include <netinet/in.h> | ||
| 68 | +# include <arpa/inet.h> | ||
| 69 | +# define sx_popen popen | ||
| 70 | +# define sx_pclose pclose | ||
| 71 | +# define sx_close_socket close | ||
| 72 | +#endif | ||
| 73 | + | ||
| 74 | +#define PLUGIN_SLUG "ports" | ||
| 75 | +#define PLUGIN_ID "plugin_ports" | ||
| 76 | +#define PLUGIN_VER "1.0.0" | ||
| 77 | + | ||
| 78 | +#define MAX_LISTEN 1024 | ||
| 79 | +#define MAX_OWNERS 8192 | ||
| 80 | +#define MAX_LINE 1024 | ||
| 81 | +#define PROBE_TIMEOUT_MS 2000 | ||
| 82 | +#define HTTP_READ_MS 1500 | ||
| 83 | + | ||
| 84 | +/* socket scope */ | ||
| 85 | +#define SCOPE_LOOPBACK 0 | ||
| 86 | +#define SCOPE_WILDCARD 1 | ||
| 87 | +#define SCOPE_SPECIFIC 2 | ||
| 88 | + | ||
| 89 | +typedef struct { | ||
| 90 | + char proto[4]; /* "tcp" or "udp" */ | ||
| 91 | + char bind_addr[64]; /* 127.0.0.1, 0.0.0.0, ::1, ::, or one bound address */ | ||
| 92 | + int port; | ||
| 93 | + int scope; | ||
| 94 | + int pid; | ||
| 95 | + char comm[96]; | ||
| 96 | + unsigned long inode; | ||
| 97 | +} sock_t; | ||
| 98 | + | ||
| 99 | +static sock_t g_socks[MAX_LISTEN]; | ||
| 100 | +static int g_sock_count; | ||
| 101 | + | ||
| 102 | +/* ------------------------------------------------------------------ */ | ||
| 103 | +/* Small utilities */ | ||
| 104 | +/* ------------------------------------------------------------------ */ | ||
| 105 | + | ||
| 106 | +static void url_decode(char *s) | ||
| 107 | +{ | ||
| 108 | + char *o = s; | ||
| 109 | + if (!s) return; | ||
| 110 | + while (*s) { | ||
| 111 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 112 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 113 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 114 | + *o++ = (char)((hi << 4) | lo); | ||
| 115 | + s += 3; | ||
| 116 | + } else if (*s == '+') { | ||
| 117 | + *o++ = ' '; | ||
| 118 | + s++; | ||
| 119 | + } else { | ||
| 120 | + *o++ = *s++; | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | + *o = '\0'; | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 127 | +{ | ||
| 128 | + size_t klen; | ||
| 129 | + const char *p; | ||
| 130 | + | ||
| 131 | + if (!out || outsz == 0) return 0; | ||
| 132 | + out[0] = '\0'; | ||
| 133 | + if (!qs || !key) return 0; | ||
| 134 | + klen = strlen(key); | ||
| 135 | + | ||
| 136 | + for (p = qs; *p; ) { | ||
| 137 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 138 | + const char *v = p + klen + 1; | ||
| 139 | + size_t i = 0; | ||
| 140 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 141 | + out[i++] = *v++; | ||
| 142 | + out[i] = '\0'; | ||
| 143 | + url_decode(out); | ||
| 144 | + return 1; | ||
| 145 | + } | ||
| 146 | + p = strchr(p, '&'); | ||
| 147 | + if (!p) break; | ||
| 148 | + p++; | ||
| 149 | + } | ||
| 150 | + return 0; | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +static void json_str(const char *s) | ||
| 154 | +{ | ||
| 155 | + putchar('"'); | ||
| 156 | + for (; s && *s; s++) { | ||
| 157 | + unsigned char c = (unsigned char)*s; | ||
| 158 | + switch (c) { | ||
| 159 | + case '"': fputs("\\\"", stdout); break; | ||
| 160 | + case '\\': fputs("\\\\", stdout); break; | ||
| 161 | + case '\n': fputs("\\n", stdout); break; | ||
| 162 | + case '\r': fputs("\\r", stdout); break; | ||
| 163 | + case '\t': fputs("\\t", stdout); break; | ||
| 164 | + default: | ||
| 165 | + if (c < 0x20) printf("\\u%04x", c); | ||
| 166 | + else putchar(c); | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + putchar('"'); | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +static void str_copy(char *dst, size_t sz, const char *src) | ||
| 173 | +{ | ||
| 174 | + size_t n; | ||
| 175 | + if (!dst || sz == 0) return; | ||
| 176 | + if (!src) { dst[0] = '\0'; return; } | ||
| 177 | + n = strlen(src); | ||
| 178 | + if (n >= sz) n = sz - 1; | ||
| 179 | + memcpy(dst, src, n); | ||
| 180 | + dst[n] = '\0'; | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +#if !defined(_WIN32) || defined(__APPLE__) | ||
| 184 | +static void str_trim(char *s) | ||
| 185 | +{ | ||
| 186 | + char *p; | ||
| 187 | + size_t n; | ||
| 188 | + if (!s) return; | ||
| 189 | + p = s; | ||
| 190 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 191 | + if (p != s) memmove(s, p, strlen(p) + 1); | ||
| 192 | + n = strlen(s); | ||
| 193 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | ||
| 194 | +} | ||
| 195 | +#endif | ||
| 196 | + | ||
| 197 | +static int scope_of_addr(const char *addr) | ||
| 198 | +{ | ||
| 199 | + if (!addr || !*addr) return SCOPE_SPECIFIC; | ||
| 200 | + if (strcmp(addr, "0.0.0.0") == 0 || strcmp(addr, "::") == 0 || | ||
| 201 | + strcmp(addr, "*") == 0) | ||
| 202 | + return SCOPE_WILDCARD; | ||
| 203 | + if (strncmp(addr, "127.", 4) == 0) return SCOPE_LOOPBACK; | ||
| 204 | + if (strcmp(addr, "::1") == 0) return SCOPE_LOOPBACK; | ||
| 205 | + return SCOPE_SPECIFIC; | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +static const char *scope_name(int s) | ||
| 209 | +{ | ||
| 210 | + if (s == SCOPE_LOOPBACK) return "loopback"; | ||
| 211 | + if (s == SCOPE_WILDCARD) return "wildcard"; | ||
| 212 | + return "specific"; | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +static long long now_ms(void) | ||
| 216 | +{ | ||
| 217 | +#if defined(_WIN32) | ||
| 218 | + FILETIME ft; | ||
| 219 | + ULARGE_INTEGER u; | ||
| 220 | + GetSystemTimeAsFileTime(&ft); | ||
| 221 | + u.LowPart = ft.dwLowDateTime; | ||
| 222 | + u.HighPart = ft.dwHighDateTime; | ||
| 223 | + return (long long)(u.QuadPart / 10000ULL); | ||
| 224 | +#else | ||
| 225 | + struct timeval tv; | ||
| 226 | + gettimeofday(&tv, NULL); | ||
| 227 | + return (long long)tv.tv_sec * 1000LL + (long long)(tv.tv_usec / 1000); | ||
| 228 | +#endif | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +static void utc_stamp(time_t t, char *buf, size_t sz) | ||
| 232 | +{ | ||
| 233 | + struct tm tmv; | ||
| 234 | +#if defined(_WIN32) | ||
| 235 | + gmtime_s(&tmv, &t); | ||
| 236 | +#else | ||
| 237 | + gmtime_r(&t, &tmv); | ||
| 238 | +#endif | ||
| 239 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | ||
| 240 | +} | ||
| 241 | + | ||
| 242 | +/* ------------------------------------------------------------------ */ | ||
| 243 | +/* Node authentication */ | ||
| 244 | +/* ------------------------------------------------------------------ */ | ||
| 245 | + | ||
| 246 | +static void require_node_auth(void) | ||
| 247 | +{ | ||
| 248 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 249 | + const char *xp; | ||
| 250 | + const char *auth; | ||
| 251 | + const char *qs; | ||
| 252 | + char qpwd[256]; | ||
| 253 | + | ||
| 254 | + if (!np || !*np) return; | ||
| 255 | + | ||
| 256 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 257 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 258 | + | ||
| 259 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 260 | + if (auth) { | ||
| 261 | + while (*auth == ' ') auth++; | ||
| 262 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 263 | + auth += 7; | ||
| 264 | + while (*auth == ' ') auth++; | ||
| 265 | + if (strcmp(auth, np) == 0) return; | ||
| 266 | + } | ||
| 267 | + } | ||
| 268 | + | ||
| 269 | + qs = getenv("QUERY_STRING"); | ||
| 270 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 271 | + return; | ||
| 272 | + | ||
| 273 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 274 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 275 | + "Cache-Control: no-store\r\n" | ||
| 276 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 277 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 278 | + exit(0); | ||
| 279 | +} | ||
| 280 | + | ||
| 281 | +/* ------------------------------------------------------------------ */ | ||
| 282 | +/* Listening-socket collection */ | ||
| 283 | +/* ------------------------------------------------------------------ */ | ||
| 284 | + | ||
| 285 | +static void sock_add(const char *proto, const char *addr, int port, | ||
| 286 | + int pid, const char *comm, unsigned long inode) | ||
| 287 | +{ | ||
| 288 | + sock_t *s; | ||
| 289 | + if (g_sock_count >= MAX_LISTEN) return; | ||
| 290 | + if (port <= 0 || port > 65535) return; | ||
| 291 | + s = &g_socks[g_sock_count++]; | ||
| 292 | + str_copy(s->proto, sizeof(s->proto), proto); | ||
| 293 | + str_copy(s->bind_addr, sizeof(s->bind_addr), addr && *addr ? addr : "unknown"); | ||
| 294 | + s->port = port; | ||
| 295 | + s->scope = scope_of_addr(s->bind_addr); | ||
| 296 | + s->pid = pid; | ||
| 297 | + str_copy(s->comm, sizeof(s->comm), comm ? comm : ""); | ||
| 298 | + s->inode = inode; | ||
| 299 | +} | ||
| 300 | + | ||
| 301 | +static void sort_socks(void) | ||
| 302 | +{ | ||
| 303 | + int i, j; | ||
| 304 | + for (i = 1; i < g_sock_count; i++) { | ||
| 305 | + sock_t key = g_socks[i]; | ||
| 306 | + j = i - 1; | ||
| 307 | + while (j >= 0) { | ||
| 308 | + int cmp; | ||
| 309 | + if (g_socks[j].port != key.port) cmp = g_socks[j].port - key.port; | ||
| 310 | + else cmp = strcmp(g_socks[j].proto, key.proto); | ||
| 311 | + if (cmp <= 0) break; | ||
| 312 | + g_socks[j + 1] = g_socks[j]; | ||
| 313 | + j--; | ||
| 314 | + } | ||
| 315 | + g_socks[j + 1] = key; | ||
| 316 | + } | ||
| 317 | +} | ||
| 318 | + | ||
| 319 | +#if !defined(_WIN32) | ||
| 320 | + | ||
| 321 | +/* ---- owner resolution from /proc/<pid>/fd socket inodes ---- */ | ||
| 322 | + | ||
| 323 | +typedef struct { | ||
| 324 | + unsigned long inode; | ||
| 325 | + int pid; | ||
| 326 | + char comm[96]; | ||
| 327 | +} owner_t; | ||
| 328 | + | ||
| 329 | +static owner_t g_owners[MAX_OWNERS]; | ||
| 330 | +static int g_owner_count; | ||
| 331 | + | ||
| 332 | +static int is_numeric(const char *s) | ||
| 333 | +{ | ||
| 334 | + if (!s || !*s) return 0; | ||
| 335 | + for (; *s; s++) if (!isdigit((unsigned char)*s)) return 0; | ||
| 336 | + return 1; | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +static void owner_scan_dir(const char *fdpath, int pid, const char *comm) | ||
| 340 | +{ | ||
| 341 | + DIR *d; | ||
| 342 | + struct dirent *e; | ||
| 343 | + | ||
| 344 | + d = opendir(fdpath); | ||
| 345 | + if (!d) return; | ||
| 346 | + while ((e = readdir(d)) != NULL) { | ||
| 347 | + char full[MAX_LINE * 2]; | ||
| 348 | + char link[MAX_LINE]; | ||
| 349 | + ssize_t n; | ||
| 350 | + if (e->d_name[0] == '.') continue; | ||
| 351 | + if (g_owner_count >= MAX_OWNERS) break; | ||
| 352 | + snprintf(full, sizeof(full), "%s/%s", fdpath, e->d_name); | ||
| 353 | + n = readlink(full, link, sizeof(link) - 1); | ||
| 354 | + if (n <= 0) continue; | ||
| 355 | + link[n] = '\0'; | ||
| 356 | + if (strncmp(link, "socket:[", 8) != 0) continue; | ||
| 357 | + g_owners[g_owner_count].inode = | ||
| 358 | + (unsigned long)strtoul(link + 8, NULL, 10); | ||
| 359 | + g_owners[g_owner_count].pid = pid; | ||
| 360 | + str_copy(g_owners[g_owner_count].comm, sizeof(g_owners[0].comm), comm); | ||
| 361 | + g_owner_count++; | ||
| 362 | + } | ||
| 363 | + closedir(d); | ||
| 364 | +} | ||
| 365 | + | ||
| 366 | +static void resolve_owners(void) | ||
| 367 | +{ | ||
| 368 | + DIR *d; | ||
| 369 | + struct dirent *e; | ||
| 370 | + | ||
| 371 | + if (g_sock_count == 0) return; | ||
| 372 | +#if defined(__APPLE__) | ||
| 373 | + return; /* macOS owners come from lsof in collect_macos() */ | ||
| 374 | +#endif | ||
| 375 | + | ||
| 376 | + d = opendir("/proc"); | ||
| 377 | + if (!d) return; | ||
| 378 | + while ((e = readdir(d)) != NULL) { | ||
| 379 | + char comm[96] = ""; | ||
| 380 | + char path[MAX_LINE]; | ||
| 381 | + FILE *fp; | ||
| 382 | + int pid; | ||
| 383 | + | ||
| 384 | + if (!is_numeric(e->d_name)) continue; | ||
| 385 | + pid = atoi(e->d_name); | ||
| 386 | + if (pid <= 0) continue; | ||
| 387 | + | ||
| 388 | + snprintf(path, sizeof(path), "/proc/%d/comm", pid); | ||
| 389 | + fp = fopen(path, "r"); | ||
| 390 | + if (fp) { | ||
| 391 | + if (fgets(comm, sizeof(comm), fp)) str_trim(comm); | ||
| 392 | + fclose(fp); | ||
| 393 | + } | ||
| 394 | + snprintf(path, sizeof(path), "/proc/%d/fd", pid); | ||
| 395 | + owner_scan_dir(path, pid, comm); | ||
| 396 | + } | ||
| 397 | + closedir(d); | ||
| 398 | + | ||
| 399 | + { | ||
| 400 | + int i, k, m; | ||
| 401 | + for (i = 0; i < g_sock_count; i++) { | ||
| 402 | + if (g_socks[i].inode == 0) continue; | ||
| 403 | + for (k = 0; k < g_owner_count; k++) { | ||
| 404 | + if (g_owners[k].inode != g_socks[i].inode) continue; | ||
| 405 | + if (g_socks[i].pid <= 0) { | ||
| 406 | + g_socks[i].pid = g_owners[k].pid; | ||
| 407 | + str_copy(g_socks[i].comm, sizeof(g_socks[i].comm), | ||
| 408 | + g_owners[k].comm); | ||
| 409 | + } else if (strcmp(g_socks[i].comm, g_owners[k].comm) != 0 && | ||
| 410 | + g_owners[k].pid < g_socks[i].pid) { | ||
| 411 | + /* prefer the lowest pid seen for this socket */ | ||
| 412 | + g_socks[i].pid = g_owners[k].pid; | ||
| 413 | + str_copy(g_socks[i].comm, sizeof(g_socks[i].comm), | ||
| 414 | + g_owners[k].comm); | ||
| 415 | + } | ||
| 416 | + m = 0; (void)m; | ||
| 417 | + } | ||
| 418 | + } | ||
| 419 | + } | ||
| 420 | +} | ||
| 421 | + | ||
| 422 | +/* ---- /proc/net/{tcp,tcp6,udp,udp6} parsing ---- */ | ||
| 423 | + | ||
| 424 | +static int hex_val(int c) | ||
| 425 | +{ | ||
| 426 | + if (c >= '0' && c <= '9') return c - '0'; | ||
| 427 | + if (c >= 'a' && c <= 'f') return c - 'a' + 10; | ||
| 428 | + if (c >= 'A' && c <= 'F') return c - 'A' + 10; | ||
| 429 | + return -1; | ||
| 430 | +} | ||
| 431 | + | ||
| 432 | +/* "0100007F" -> 127.0.0.1 (little-endian 32-bit word) */ | ||
| 433 | +static int decode_v4(const char *hex, char *out, size_t sz) | ||
| 434 | +{ | ||
| 435 | + unsigned char b[4]; | ||
| 436 | + struct in_addr a; | ||
| 437 | + int i; | ||
| 438 | + for (i = 0; i < 4; i++) { | ||
| 439 | + int hi = hex_val(hex[i * 2]); | ||
| 440 | + int lo = hex_val(hex[i * 2 + 1]); | ||
| 441 | + if (hi < 0 || lo < 0) return 0; | ||
| 442 | + b[3 - i] = (unsigned char)((hi << 4) | lo); | ||
| 443 | + } | ||
| 444 | + memcpy(&a, b, 4); | ||
| 445 | + return inet_ntop(AF_INET, &a, out, (socklen_t)sz) != NULL; | ||
| 446 | +} | ||
| 447 | + | ||
| 448 | +/* 32 hex chars -> 16 bytes, each 8-char group is a little-endian 32-bit word */ | ||
| 449 | +static int decode_v6(const char *hex, char *out, size_t sz) | ||
| 450 | +{ | ||
| 451 | + unsigned char b[16]; | ||
| 452 | + int g, i; | ||
| 453 | + for (g = 0; g < 4; g++) { | ||
| 454 | + unsigned int word = 0; | ||
| 455 | + for (i = 0; i < 8; i++) { | ||
| 456 | + int v = hex_val(hex[g * 8 + i]); | ||
| 457 | + if (v < 0) return 0; | ||
| 458 | + word = (word << 4) | (unsigned int)v; | ||
| 459 | + } | ||
| 460 | + b[g * 4 + 0] = (unsigned char)(word & 0xff); | ||
| 461 | + b[g * 4 + 1] = (unsigned char)((word >> 8) & 0xff); | ||
| 462 | + b[g * 4 + 2] = (unsigned char)((word >> 16) & 0xff); | ||
| 463 | + b[g * 4 + 3] = (unsigned char)((word >> 24) & 0xff); | ||
| 464 | + } | ||
| 465 | + return inet_ntop(AF_INET6, b, out, (socklen_t)sz) != NULL; | ||
| 466 | +} | ||
| 467 | + | ||
| 468 | +static int split_local(const char *tok, char *addr, size_t addrsz, int *port) | ||
| 469 | +{ | ||
| 470 | + const char *colon; | ||
| 471 | + size_t alen; | ||
| 472 | + | ||
| 473 | + colon = strrchr(tok, ':'); | ||
| 474 | + if (!colon) return 0; | ||
| 475 | + alen = (size_t)(colon - tok); | ||
| 476 | + if (alen == 0 || alen >= addrsz) return 0; | ||
| 477 | + | ||
| 478 | + *port = (int)strtol(colon + 1, NULL, 16); | ||
| 479 | + if (alen == 8) | ||
| 480 | + return decode_v4(tok, addr, addrsz); | ||
| 481 | + if (alen == 32) | ||
| 482 | + return decode_v6(tok, addr, addrsz); | ||
| 483 | + str_copy(addr, addrsz, "unknown"); | ||
| 484 | + return 1; | ||
| 485 | +} | ||
| 486 | + | ||
| 487 | +static int tokenize(char *line, char **tok, int max) | ||
| 488 | +{ | ||
| 489 | + int n = 0; | ||
| 490 | + char *p = line; | ||
| 491 | + while (*p && n < max) { | ||
| 492 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 493 | + if (!*p) break; | ||
| 494 | + tok[n++] = p; | ||
| 495 | + while (*p && !isspace((unsigned char)*p)) p++; | ||
| 496 | + if (*p) *p++ = '\0'; | ||
| 497 | + } | ||
| 498 | + return n; | ||
| 499 | +} | ||
| 500 | + | ||
| 501 | +static void collect_proc_net(const char *path, const char *proto, int listening_only) | ||
| 502 | +{ | ||
| 503 | + FILE *fp; | ||
| 504 | + char line[MAX_LINE]; | ||
| 505 | + | ||
| 506 | + fp = fopen(path, "r"); | ||
| 507 | + if (!fp) return; | ||
| 508 | + if (!fgets(line, sizeof(line), fp)) { fclose(fp); return; } | ||
| 509 | + | ||
| 510 | + while (fgets(line, sizeof(line), fp)) { | ||
| 511 | + char *tok[24]; | ||
| 512 | + int n; | ||
| 513 | + char addr[64]; | ||
| 514 | + int port = 0; | ||
| 515 | + unsigned long inode = 0; | ||
| 516 | + int state = -1; | ||
| 517 | + | ||
| 518 | + n = tokenize(line, tok, 24); | ||
| 519 | + if (n < 12) continue; | ||
| 520 | + | ||
| 521 | + state = (int)strtol(tok[3], NULL, 16); | ||
| 522 | + inode = (unsigned long)strtoul(tok[9], NULL, 10); | ||
| 523 | + if (listening_only && state != 0x0A) continue; | ||
| 524 | + if (!listening_only && state != 0x07) continue; | ||
| 525 | + | ||
| 526 | + if (!split_local(tok[1], addr, sizeof(addr), &port)) continue; | ||
| 527 | + sock_add(proto, addr, port, 0, "", inode); | ||
| 528 | + } | ||
| 529 | + fclose(fp); | ||
| 530 | +} | ||
| 531 | + | ||
| 532 | +#if defined(__APPLE__) | ||
| 533 | + | ||
| 534 | +/* lsof -nP -iTCP -sTCP:LISTEN / lsof -nP -iUDP ; NAME column is the local endpoint */ | ||
| 535 | +static void collect_lsof(const char *args, const char *proto) | ||
| 536 | +{ | ||
| 537 | + char cmd[256]; | ||
| 538 | + FILE *fp; | ||
| 539 | + char line[MAX_LINE]; | ||
| 540 | + | ||
| 541 | + snprintf(cmd, sizeof(cmd), "lsof -nP %s 2>/dev/null", args); | ||
| 542 | + fp = sx_popen(cmd, "r"); | ||
| 543 | + if (!fp) return; | ||
| 544 | + if (fgets(line, sizeof(line), fp)) { | ||
| 545 | + while (fgets(line, sizeof(line), fp)) { | ||
| 546 | + char *tok[32]; | ||
| 547 | + char *name; | ||
| 548 | + char *colon; | ||
| 549 | + int n, port, pid = 0; | ||
| 550 | + char addr[64]; | ||
| 551 | + | ||
| 552 | + str_trim(line); | ||
| 553 | + if (!line[0]) continue; | ||
| 554 | + n = tokenize(line, tok, 32); | ||
| 555 | + if (n < 9) continue; | ||
| 556 | + pid = atoi(tok[1]); | ||
| 557 | + name = tok[n - 1]; | ||
| 558 | + colon = strrchr(name, ':'); | ||
| 559 | + if (!colon) continue; | ||
| 560 | + port = atoi(colon + 1); | ||
| 561 | + *colon = '\0'; | ||
| 562 | + str_copy(addr, sizeof(addr), name); | ||
| 563 | + if (strcmp(addr, "*") == 0) str_copy(addr, sizeof(addr), "0.0.0.0"); | ||
| 564 | + if (strcmp(addr, "[::]") == 0) str_copy(addr, sizeof(addr), "::"); | ||
| 565 | + if (strcmp(addr, "localhost") == 0) str_copy(addr, sizeof(addr), "127.0.0.1"); | ||
| 566 | + sock_add(proto, addr, port, pid, tok[0], 0); | ||
| 567 | + } | ||
| 568 | + } | ||
| 569 | + sx_pclose(fp); | ||
| 570 | +} | ||
| 571 | + | ||
| 572 | +static void collect_netstat_fallback(const char *proto) | ||
| 573 | +{ | ||
| 574 | + FILE *fp; | ||
| 575 | + char line[MAX_LINE]; | ||
| 576 | + | ||
| 577 | + fp = sx_popen("netstat -an 2>/dev/null", "r"); | ||
| 578 | + if (!fp) return; | ||
| 579 | + while (fgets(line, sizeof(line), fp)) { | ||
| 580 | + char *tok[16]; | ||
| 581 | + int n; | ||
| 582 | + char addr[64]; | ||
| 583 | + int port = 0; | ||
| 584 | + char *colon; | ||
| 585 | + | ||
| 586 | + str_trim(line); | ||
| 587 | + n = tokenize(line, tok, 16); | ||
| 588 | + if (n < 5) continue; | ||
| 589 | + if (strcasecmp(tok[0], proto) != 0) continue; | ||
| 590 | + if (strcmp(proto, "tcp") == 0 && strcmp(tok[5 < n ? 5 : n - 1], "LISTEN") != 0) | ||
| 591 | + continue; | ||
| 592 | + colon = strrchr(tok[3], '.'); | ||
| 593 | + if (!colon) continue; | ||
| 594 | + port = atoi(colon + 1); | ||
| 595 | + *colon = '\0'; | ||
| 596 | + str_copy(addr, sizeof(addr), tok[3]); | ||
| 597 | + if (strcmp(addr, "*") == 0) str_copy(addr, sizeof(addr), "0.0.0.0"); | ||
| 598 | + sock_add(proto, addr, port, 0, "", 0); | ||
| 599 | + } | ||
| 600 | + sx_pclose(fp); | ||
| 601 | +} | ||
| 602 | + | ||
| 603 | +static void collect_macos(void) | ||
| 604 | +{ | ||
| 605 | + collect_lsof("-iTCP -sTCP:LISTEN", "tcp"); | ||
| 606 | + collect_lsof("-iUDP", "udp"); | ||
| 607 | + if (g_sock_count == 0) { | ||
| 608 | + collect_netstat_fallback("tcp"); | ||
| 609 | + collect_netstat_fallback("udp"); | ||
| 610 | + } | ||
| 611 | +} | ||
| 612 | + | ||
| 613 | +#else /* Linux */ | ||
| 614 | + | ||
| 615 | +static void collect_linux(void) | ||
| 616 | +{ | ||
| 617 | + collect_proc_net("/proc/net/tcp", "tcp", 1); | ||
| 618 | + collect_proc_net("/proc/net/tcp6", "tcp", 1); | ||
| 619 | + /* UDP sockets have no LISTEN state; an unconnected bound socket sits in | ||
| 620 | + state 07 (UDP_CLOSE). Anything else is already connected. */ | ||
| 621 | + collect_proc_net("/proc/net/udp", "udp", 0); | ||
| 622 | + collect_proc_net("/proc/net/udp6", "udp", 0); | ||
| 623 | +} | ||
| 624 | + | ||
| 625 | +#endif /* __APPLE__ */ | ||
| 626 | + | ||
| 627 | +#else /* _WIN32 */ | ||
| 628 | + | ||
| 629 | +static void win_comm_for_pid(DWORD pid, char *out, size_t sz) | ||
| 630 | +{ | ||
| 631 | + HANDLE h; | ||
| 632 | + char path[MAX_PATH]; | ||
| 633 | + DWORD len = (DWORD)sz; | ||
| 634 | + | ||
| 635 | + out[0] = '\0'; | ||
| 636 | + if (pid == 0) return; | ||
| 637 | + h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); | ||
| 638 | + if (!h) return; | ||
| 639 | + if (QueryFullProcessImageNameA(h, 0, path, &len)) { | ||
| 640 | + char *slash = strrchr(path, '\\'); | ||
| 641 | + str_copy(out, sz, slash ? slash + 1 : path); | ||
| 642 | + } | ||
| 643 | + CloseHandle(h); | ||
| 644 | +} | ||
| 645 | + | ||
| 646 | +static void win_add_row(const char *proto, int is_v6, const void *addr, | ||
| 647 | + DWORD port_be, DWORD pid) | ||
| 648 | +{ | ||
| 649 | + char addr_s[64]; | ||
| 650 | + int port; | ||
| 651 | + char comm[96]; | ||
| 652 | + | ||
| 653 | + if (is_v6) | ||
| 654 | + inet_ntop(AF_INET6, addr, addr_s, sizeof(addr_s)); | ||
| 655 | + else | ||
| 656 | + inet_ntop(AF_INET, addr, addr_s, sizeof(addr_s)); | ||
| 657 | + | ||
| 658 | + port = (int)ntohs((unsigned short)(port_be & 0xffff)); | ||
| 659 | + if (pid > 0) win_comm_for_pid(pid, comm, sizeof(comm)); | ||
| 660 | + else comm[0] = '\0'; | ||
| 661 | + | ||
| 662 | + sock_add(proto, addr_s, port, (int)pid, comm, 0); | ||
| 663 | +} | ||
| 664 | + | ||
| 665 | +static void collect_windows(void) | ||
| 666 | +{ | ||
| 667 | + DWORD size = 0; | ||
| 668 | + DWORD rc; | ||
| 669 | + int fam; | ||
| 670 | + | ||
| 671 | + for (fam = 0; fam < 2; fam++) { | ||
| 672 | + int af = fam == 0 ? AF_INET : AF_INET6; | ||
| 673 | + | ||
| 674 | + /* TCP listeners */ | ||
| 675 | + size = 0; | ||
| 676 | + rc = GetExtendedTcpTable(NULL, &size, FALSE, af, | ||
| 677 | + TCP_TABLE_OWNER_PID_LISTENER, 0); | ||
| 678 | + if (rc == ERROR_INSUFFICIENT_BUFFER && size > 0) { | ||
| 679 | + void *buf = malloc(size); | ||
| 680 | + if (buf) { | ||
| 681 | + rc = GetExtendedTcpTable(buf, &size, FALSE, af, | ||
| 682 | + TCP_TABLE_OWNER_PID_LISTENER, 0); | ||
| 683 | + if (rc == NO_ERROR) { | ||
| 684 | + if (af == AF_INET) { | ||
| 685 | + MIB_TCPTABLE_OWNER_PID *t = (MIB_TCPTABLE_OWNER_PID *)buf; | ||
| 686 | + DWORD i; | ||
| 687 | + for (i = 0; i < t->dwNumEntries; i++) { | ||
| 688 | + MIB_TCPROW_OWNER_PID *r = &t->table[i]; | ||
| 689 | + if (r->dwState != MIB_TCP_STATE_LISTEN) continue; | ||
| 690 | + win_add_row("tcp", 0, &r->dwLocalAddr, | ||
| 691 | + r->dwLocalPort, r->dwOwningPid); | ||
| 692 | + } | ||
| 693 | + } else { | ||
| 694 | + MIB_TCP6TABLE_OWNER_PID *t = (MIB_TCP6TABLE_OWNER_PID *)buf; | ||
| 695 | + DWORD i; | ||
| 696 | + for (i = 0; i < t->dwNumEntries; i++) { | ||
| 697 | + MIB_TCP6ROW_OWNER_PID *r = &t->table[i]; | ||
| 698 | + if (r->dwState != MIB_TCP_STATE_LISTEN) continue; | ||
| 699 | + win_add_row("tcp", 1, r->ucLocalAddr, | ||
| 700 | + r->dwLocalPort, r->dwOwningPid); | ||
| 701 | + } | ||
| 702 | + } | ||
| 703 | + } | ||
| 704 | + free(buf); | ||
| 705 | + } | ||
| 706 | + } | ||
| 707 | + | ||
| 708 | + /* UDP endpoints */ | ||
| 709 | + size = 0; | ||
| 710 | + rc = GetExtendedUdpTable(NULL, &size, FALSE, af, | ||
| 711 | + UDP_TABLE_OWNER_PID, 0); | ||
| 712 | + if (rc == ERROR_INSUFFICIENT_BUFFER && size > 0) { | ||
| 713 | + void *buf = malloc(size); | ||
| 714 | + if (buf) { | ||
| 715 | + rc = GetExtendedUdpTable(buf, &size, FALSE, af, | ||
| 716 | + UDP_TABLE_OWNER_PID, 0); | ||
| 717 | + if (rc == NO_ERROR) { | ||
| 718 | + if (af == AF_INET) { | ||
| 719 | + MIB_UDPTABLE_OWNER_PID *t = (MIB_UDPTABLE_OWNER_PID *)buf; | ||
| 720 | + DWORD i; | ||
| 721 | + for (i = 0; i < t->dwNumEntries; i++) { | ||
| 722 | + MIB_UDPROW_OWNER_PID *r = &t->table[i]; | ||
| 723 | + win_add_row("udp", 0, &r->dwLocalAddr, | ||
| 724 | + r->dwLocalPort, r->dwOwningPid); | ||
| 725 | + } | ||
| 726 | + } else { | ||
| 727 | + MIB_UDP6TABLE_OWNER_PID *t = (MIB_UDP6TABLE_OWNER_PID *)buf; | ||
| 728 | + DWORD i; | ||
| 729 | + for (i = 0; i < t->dwNumEntries; i++) { | ||
| 730 | + MIB_UDP6ROW_OWNER_PID *r = &t->table[i]; | ||
| 731 | + win_add_row("udp", 1, r->ucLocalAddr, | ||
| 732 | + r->dwLocalPort, r->dwOwningPid); | ||
| 733 | + } | ||
| 734 | + } | ||
| 735 | + } | ||
| 736 | + free(buf); | ||
| 737 | + } | ||
| 738 | + } | ||
| 739 | + } | ||
| 740 | +} | ||
| 741 | + | ||
| 742 | +#endif /* _WIN32 */ | ||
| 743 | + | ||
| 744 | +static void collect_sockets(void) | ||
| 745 | +{ | ||
| 746 | + g_sock_count = 0; | ||
| 747 | +#if defined(_WIN32) | ||
| 748 | + collect_windows(); | ||
| 749 | +#elif defined(__APPLE__) | ||
| 750 | + collect_macos(); | ||
| 751 | +#else | ||
| 752 | + collect_linux(); | ||
| 753 | + resolve_owners(); | ||
| 754 | +#endif | ||
| 755 | + sort_socks(); | ||
| 756 | +} | ||
| 757 | + | ||
| 758 | +/* ------------------------------------------------------------------ */ | ||
| 759 | +/* Loopback probe (127.0.0.1 only - never an arbitrary destination) */ | ||
| 760 | +/* ------------------------------------------------------------------ */ | ||
| 761 | + | ||
| 762 | +typedef struct { | ||
| 763 | + int ok; /* connect() succeeded */ | ||
| 764 | + int refused; /* reached the host, nothing listening */ | ||
| 765 | + long connect_ms; | ||
| 766 | + int http_tried; | ||
| 767 | + int http_ok; | ||
| 768 | + int http_status; | ||
| 769 | + long http_ms; | ||
| 770 | +} probe_t; | ||
| 771 | + | ||
| 772 | +#if defined(_WIN32) | ||
| 773 | +static int probe_connect(const unsigned char v4[4], int port) | ||
| 774 | +{ | ||
| 775 | + SOCKET s; | ||
| 776 | + struct sockaddr_in sa; | ||
| 777 | + u_long nb = 1; | ||
| 778 | + int rc, err; | ||
| 779 | + fd_set wfds; | ||
| 780 | + struct timeval tv; | ||
| 781 | + | ||
| 782 | + s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 783 | + if (s == INVALID_SOCKET) return -1; | ||
| 784 | + | ||
| 785 | + memset(&sa, 0, sizeof(sa)); | ||
| 786 | + sa.sin_family = AF_INET; | ||
| 787 | + sa.sin_port = htons((unsigned short)port); | ||
| 788 | + memcpy(&sa.sin_addr, v4, 4); | ||
| 789 | + | ||
| 790 | + ioctlsocket(s, FIONBIO, &nb); | ||
| 791 | + rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); | ||
| 792 | + if (rc == SOCKET_ERROR) { | ||
| 793 | + err = WSAGetLastError(); | ||
| 794 | + if (err != WSAEWOULDBLOCK) { | ||
| 795 | + closesocket(s); | ||
| 796 | + return (err == WSAECONNREFUSED) ? 1 : -1; | ||
| 797 | + } | ||
| 798 | + FD_ZERO(&wfds); | ||
| 799 | + FD_SET(s, &wfds); | ||
| 800 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | ||
| 801 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | ||
| 802 | + rc = select(0, NULL, &wfds, NULL, &tv); | ||
| 803 | + if (rc <= 0) { closesocket(s); return 1; } | ||
| 804 | + { | ||
| 805 | + int soerr = 0, slen = sizeof(soerr); | ||
| 806 | + getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen); | ||
| 807 | + if (soerr != 0) { | ||
| 808 | + closesocket(s); | ||
| 809 | + return (soerr == WSAECONNREFUSED) ? 1 : -1; | ||
| 810 | + } | ||
| 811 | + } | ||
| 812 | + } | ||
| 813 | + closesocket(s); | ||
| 814 | + return 0; | ||
| 815 | +} | ||
| 816 | +#else | ||
| 817 | +static int probe_connect(const unsigned char v4[4], int port) | ||
| 818 | +{ | ||
| 819 | + int fd, rc, soerr = 0; | ||
| 820 | + struct sockaddr_in sa; | ||
| 821 | + fd_set wfds; | ||
| 822 | + struct timeval tv; | ||
| 823 | + socklen_t slen = sizeof(soerr); | ||
| 824 | + | ||
| 825 | + fd = socket(AF_INET, SOCK_STREAM, 0); | ||
| 826 | + if (fd < 0) return -1; | ||
| 827 | + | ||
| 828 | + memset(&sa, 0, sizeof(sa)); | ||
| 829 | + sa.sin_family = AF_INET; | ||
| 830 | + sa.sin_port = htons((unsigned short)port); | ||
| 831 | + memcpy(&sa.sin_addr, v4, 4); | ||
| 832 | + | ||
| 833 | + { | ||
| 834 | + int fl = fcntl(fd, F_GETFL, 0); | ||
| 835 | + if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK); | ||
| 836 | + } | ||
| 837 | + | ||
| 838 | + rc = connect(fd, (struct sockaddr *)&sa, sizeof(sa)); | ||
| 839 | + if (rc < 0) { | ||
| 840 | + if (errno != EINPROGRESS) { | ||
| 841 | + int e = errno; | ||
| 842 | + close(fd); | ||
| 843 | + return (e == ECONNREFUSED) ? 1 : -1; | ||
| 844 | + } | ||
| 845 | + FD_ZERO(&wfds); | ||
| 846 | + FD_SET(fd, &wfds); | ||
| 847 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | ||
| 848 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | ||
| 849 | + rc = select(fd + 1, NULL, &wfds, NULL, &tv); | ||
| 850 | + if (rc <= 0) { close(fd); return 1; } | ||
| 851 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 || soerr != 0) { | ||
| 852 | + close(fd); | ||
| 853 | + return (soerr == ECONNREFUSED) ? 1 : -1; | ||
| 854 | + } | ||
| 855 | + } | ||
| 856 | + close(fd); | ||
| 857 | + return 0; | ||
| 858 | +} | ||
| 859 | +#endif | ||
| 860 | + | ||
| 861 | +#if defined(_WIN32) | ||
| 862 | +static int probe_http(const unsigned char v4[4], int port, int *status_out) | ||
| 863 | +{ | ||
| 864 | + SOCKET s; | ||
| 865 | + struct sockaddr_in sa; | ||
| 866 | + u_long nb = 1; | ||
| 867 | + int rc, soerr = 0, slen = sizeof(soerr); | ||
| 868 | + fd_set wfds; | ||
| 869 | + struct timeval tv; | ||
| 870 | + char req[128]; | ||
| 871 | + char buf[512]; | ||
| 872 | + long long deadline; | ||
| 873 | + | ||
| 874 | + s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 875 | + if (s == INVALID_SOCKET) return -1; | ||
| 876 | + | ||
| 877 | + memset(&sa, 0, sizeof(sa)); | ||
| 878 | + sa.sin_family = AF_INET; | ||
| 879 | + sa.sin_port = htons((unsigned short)port); | ||
| 880 | + memcpy(&sa.sin_addr, v4, 4); | ||
| 881 | + | ||
| 882 | + ioctlsocket(s, FIONBIO, &nb); | ||
| 883 | + rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); | ||
| 884 | + if (rc == SOCKET_ERROR) { | ||
| 885 | + int err = WSAGetLastError(); | ||
| 886 | + if (err != WSAEWOULDBLOCK) { closesocket(s); return -1; } | ||
| 887 | + FD_ZERO(&wfds); | ||
| 888 | + FD_SET(s, &wfds); | ||
| 889 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | ||
| 890 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | ||
| 891 | + if (select(0, NULL, &wfds, NULL, &tv) <= 0) { closesocket(s); return -1; } | ||
| 892 | + getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen); | ||
| 893 | + if (soerr != 0) { closesocket(s); return -1; } | ||
| 894 | + } | ||
| 895 | +#else | ||
| 896 | +static int probe_http(const unsigned char v4[4], int port, int *status_out) | ||
| 897 | +{ | ||
| 898 | + int s; | ||
| 899 | + struct sockaddr_in sa; | ||
| 900 | + int rc, soerr = 0; | ||
| 901 | + fd_set wfds; | ||
| 902 | + struct timeval tv; | ||
| 903 | + char req[128]; | ||
| 904 | + char buf[512]; | ||
| 905 | + long long deadline; | ||
| 906 | + socklen_t slen = sizeof(soerr); | ||
| 907 | + | ||
| 908 | + s = socket(AF_INET, SOCK_STREAM, 0); | ||
| 909 | + if (s < 0) return -1; | ||
| 910 | + | ||
| 911 | + memset(&sa, 0, sizeof(sa)); | ||
| 912 | + sa.sin_family = AF_INET; | ||
| 913 | + sa.sin_port = htons((unsigned short)port); | ||
| 914 | + memcpy(&sa.sin_addr, v4, 4); | ||
| 915 | + | ||
| 916 | + { | ||
| 917 | + int fl = fcntl(s, F_GETFL, 0); | ||
| 918 | + if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK); | ||
| 919 | + } | ||
| 920 | + | ||
| 921 | + rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); | ||
| 922 | + if (rc < 0) { | ||
| 923 | + if (errno != EINPROGRESS) { close(s); return -1; } | ||
| 924 | + FD_ZERO(&wfds); | ||
| 925 | + FD_SET(s, &wfds); | ||
| 926 | + tv.tv_sec = PROBE_TIMEOUT_MS / 1000; | ||
| 927 | + tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; | ||
| 928 | + if (select(s + 1, NULL, &wfds, NULL, &tv) <= 0) { close(s); return -1; } | ||
| 929 | + if (getsockopt(s, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 || soerr != 0) { | ||
| 930 | + close(s); | ||
| 931 | + return -1; | ||
| 932 | + } | ||
| 933 | + } | ||
| 934 | +#endif | ||
| 935 | + | ||
| 936 | + snprintf(req, sizeof(req), | ||
| 937 | + "HEAD / HTTP/1.0\r\nHost: 127.0.0.1:%d\r\n" | ||
| 938 | + "User-Agent: %s/%s\r\nConnection: close\r\n\r\n", port, PLUGIN_ID, PLUGIN_VER); | ||
| 939 | + if (send(s, req, (int)strlen(req), 0) <= 0) { sx_close_socket(s); return -1; } | ||
| 940 | + | ||
| 941 | + deadline = now_ms() + HTTP_READ_MS; | ||
| 942 | + { | ||
| 943 | + int total = 0; | ||
| 944 | + for (;;) { | ||
| 945 | + int n; | ||
| 946 | + long long left = deadline - now_ms(); | ||
| 947 | + if (left <= 0) break; | ||
| 948 | + { | ||
| 949 | + fd_set rfds; | ||
| 950 | + struct timeval t2; | ||
| 951 | + FD_ZERO(&rfds); | ||
| 952 | + FD_SET(s, &rfds); | ||
| 953 | + t2.tv_sec = (long)(left / 1000); | ||
| 954 | + t2.tv_usec = (long)((left % 1000) * 1000); | ||
| 955 | +#if defined(_WIN32) | ||
| 956 | + n = (select(0, &rfds, NULL, NULL, &t2) > 0) ? 1 : 0; | ||
| 957 | +#else | ||
| 958 | + n = (select(s + 1, &rfds, NULL, NULL, &t2) > 0) ? 1 : 0; | ||
| 959 | +#endif | ||
| 960 | + if (n <= 0) break; | ||
| 961 | + } | ||
| 962 | + { | ||
| 963 | + int got = recv(s, buf + total, (int)(sizeof(buf) - 1 - total), 0); | ||
| 964 | + if (got <= 0) break; | ||
| 965 | + total += got; | ||
| 966 | + buf[total] = '\0'; | ||
| 967 | + if (strstr(buf, "\r\n") || total >= (int)sizeof(buf) - 1) break; | ||
| 968 | + } | ||
| 969 | + } | ||
| 970 | + buf[total] = '\0'; | ||
| 971 | + } | ||
| 972 | + sx_close_socket(s); | ||
| 973 | + | ||
| 974 | + *status_out = 0; | ||
| 975 | + if (strncmp(buf, "HTTP/", 5) == 0) { | ||
| 976 | + const char *sp = strchr(buf, ' '); | ||
| 977 | + if (sp) *status_out = atoi(sp + 1); | ||
| 978 | + return (*status_out > 0) ? 0 : -1; | ||
| 979 | + } | ||
| 980 | + return -1; | ||
| 981 | +} | ||
| 982 | + | ||
| 983 | +static void run_probe(int port, probe_t *p) | ||
| 984 | +{ | ||
| 985 | + /* The destination is a constant: 127.0.0.1. No query parameter, header or | ||
| 986 | + * environment variable is ever consulted, so this cannot be aimed | ||
| 987 | + * elsewhere. */ | ||
| 988 | + static const unsigned char loopback[4] = { 127, 0, 0, 1 }; | ||
| 989 | + long long t0, t1; | ||
| 990 | + int refused; | ||
| 991 | + | ||
| 992 | + memset(p, 0, sizeof(*p)); | ||
| 993 | + p->connect_ms = -1; | ||
| 994 | + p->http_ms = -1; | ||
| 995 | + | ||
| 996 | + t0 = now_ms(); | ||
| 997 | + refused = probe_connect(loopback, port); | ||
| 998 | + t1 = now_ms(); | ||
| 999 | + p->connect_ms = t1 - t0; | ||
| 1000 | + p->ok = (refused == 0); | ||
| 1001 | + p->refused = (refused == 1); | ||
| 1002 | + | ||
| 1003 | + if (p->ok) { | ||
| 1004 | + p->http_tried = 1; | ||
| 1005 | + t0 = now_ms(); | ||
| 1006 | + p->http_ok = (probe_http(loopback, port, &p->http_status) == 0); | ||
| 1007 | + t1 = now_ms(); | ||
| 1008 | + p->http_ms = t1 - t0; | ||
| 1009 | + } | ||
| 1010 | +} | ||
| 1011 | + | ||
| 1012 | +/* ------------------------------------------------------------------ */ | ||
| 1013 | +/* JSON output */ | ||
| 1014 | +/* ------------------------------------------------------------------ */ | ||
| 1015 | + | ||
| 1016 | +static void json_header(void) | ||
| 1017 | +{ | ||
| 1018 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1019 | + "Cache-Control: no-store\r\n" | ||
| 1020 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1021 | +} | ||
| 1022 | + | ||
| 1023 | +static int mode_meta(void) | ||
| 1024 | +{ | ||
| 1025 | + fputs("{\"name\":\"ports\",\"desc\":\"Listening TCP\"}\n", stdout); | ||
| 1026 | + return 0; | ||
| 1027 | +} | ||
| 1028 | + | ||
| 1029 | +static void print_listeners(void) | ||
| 1030 | +{ | ||
| 1031 | + int i; | ||
| 1032 | + int loop = 0, wild = 0, other = 0; | ||
| 1033 | + int tcp = 0, udp = 0; | ||
| 1034 | + | ||
| 1035 | + for (i = 0; i < g_sock_count; i++) { | ||
| 1036 | + if (g_socks[i].scope == SCOPE_LOOPBACK) loop++; | ||
| 1037 | + else if (g_socks[i].scope == SCOPE_WILDCARD) wild++; | ||
| 1038 | + else other++; | ||
| 1039 | + if (strcmp(g_socks[i].proto, "udp") == 0) udp++; | ||
| 1040 | + else tcp++; | ||
| 1041 | + } | ||
| 1042 | + | ||
| 1043 | + fputs("{\"ok\":true,\"action\":\"listeners\",\"source\":\"", stdout); | ||
| 1044 | +#if defined(_WIN32) | ||
| 1045 | + fputs("windows-tables", stdout); | ||
| 1046 | +#elif defined(__APPLE__) | ||
| 1047 | + fputs("lsof", stdout); | ||
| 1048 | +#else | ||
| 1049 | + fputs("procfs", stdout); | ||
| 1050 | +#endif | ||
| 1051 | + fputs("\",\"count\":", stdout); | ||
| 1052 | + printf("%d", g_sock_count); | ||
| 1053 | + fputs(",\"summary\":{\"tcp\":", stdout); | ||
| 1054 | + printf("%d", tcp); | ||
| 1055 | + fputs(",\"udp\":", stdout); | ||
| 1056 | + printf("%d", udp); | ||
| 1057 | + fputs(",\"loopback\":", stdout); | ||
| 1058 | + printf("%d", loop); | ||
| 1059 | + fputs(",\"wildcard\":", stdout); | ||
| 1060 | + printf("%d", wild); | ||
| 1061 | + fputs(",\"specific\":", stdout); | ||
| 1062 | + printf("%d", other); | ||
| 1063 | + fputs("},\"listeners\":[", stdout); | ||
| 1064 | + | ||
| 1065 | + for (i = 0; i < g_sock_count; i++) { | ||
| 1066 | + sock_t *s = &g_socks[i]; | ||
| 1067 | + if (i) putchar(','); | ||
| 1068 | + fputs("{\"proto\":", stdout); | ||
| 1069 | + json_str(s->proto); | ||
| 1070 | + fputs(",\"bind_addr\":", stdout); | ||
| 1071 | + json_str(s->bind_addr); | ||
| 1072 | + printf(",\"port\":%d,\"scope\":", s->port); | ||
| 1073 | + json_str(scope_name(s->scope)); | ||
| 1074 | + printf(",\"pid\":%d,\"comm\":", s->pid); | ||
| 1075 | + json_str(s->comm); | ||
| 1076 | + putchar('}'); | ||
| 1077 | + } | ||
| 1078 | + fputs("]}\n", stdout); | ||
| 1079 | +} | ||
| 1080 | + | ||
| 1081 | +static int mode_json(const char *qs) | ||
| 1082 | +{ | ||
| 1083 | + char action[64]; | ||
| 1084 | + char port_s[16]; | ||
| 1085 | + | ||
| 1086 | + action[0] = '\0'; | ||
| 1087 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 1088 | + | ||
| 1089 | + json_header(); | ||
| 1090 | + | ||
| 1091 | + if (strcmp(action, "probe") == 0) { | ||
| 1092 | + probe_t p; | ||
| 1093 | + int port = 0; | ||
| 1094 | + char now[40]; | ||
| 1095 | + | ||
| 1096 | + get_query_val(qs, "port", port_s, sizeof(port_s)); | ||
| 1097 | + port = atoi(port_s); | ||
| 1098 | + if (port < 1 || port > 65535) { | ||
| 1099 | + fputs("{\"ok\":false,\"error\":\"port must be 1..65535\"}\n", stdout); | ||
| 1100 | + return 0; | ||
| 1101 | + } | ||
| 1102 | + | ||
| 1103 | + run_probe(port, &p); | ||
| 1104 | + utc_stamp(time(NULL), now, sizeof(now)); | ||
| 1105 | + | ||
| 1106 | + fputs("{\"ok\":true,\"action\":\"probe\",\"target\":\"127.0.0.1\",\"port\":", stdout); | ||
| 1107 | + printf("%d", port); | ||
| 1108 | + printf(",\"open\":%s", p.ok ? "true" : "false"); | ||
| 1109 | + printf(",\"refused\":%s", p.refused ? "true" : "false"); | ||
| 1110 | + printf(",\"connect_ms\":%ld", p.connect_ms); | ||
| 1111 | + printf(",\"http_tried\":%s", p.http_tried ? "true" : "false"); | ||
| 1112 | + if (p.http_tried) { | ||
| 1113 | + printf(",\"http_ok\":%s", p.http_ok ? "true" : "false"); | ||
| 1114 | + printf(",\"http_status\":%d", p.http_status); | ||
| 1115 | + printf(",\"http_ms\":%ld", p.http_ms); | ||
| 1116 | + } | ||
| 1117 | + fputs(",\"checked_at\":", stdout); | ||
| 1118 | + json_str(now); | ||
| 1119 | + fputs("}\n", stdout); | ||
| 1120 | + return 0; | ||
| 1121 | + } | ||
| 1122 | + | ||
| 1123 | + if (strcmp(action, "listeners") == 0 || !action[0] || | ||
| 1124 | + strcmp(action, "all") == 0) { | ||
| 1125 | + collect_sockets(); | ||
| 1126 | + print_listeners(); | ||
| 1127 | + return 0; | ||
| 1128 | + } | ||
| 1129 | + | ||
| 1130 | + fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); | ||
| 1131 | + return 0; | ||
| 1132 | +} | ||
| 1133 | + | ||
| 1134 | +/* ------------------------------------------------------------------ */ | ||
| 1135 | +/* HTML UI */ | ||
| 1136 | +/* ------------------------------------------------------------------ */ | ||
| 1137 | + | ||
| 1138 | +static void html_head(void) | ||
| 1139 | +{ | ||
| 1140 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1141 | + "Cache-Control: no-store\r\n" | ||
| 1142 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1143 | + | ||
| 1144 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | ||
| 1145 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | ||
| 1146 | + "<title>ports</title><style>", stdout); | ||
| 1147 | + | ||
| 1148 | + fputs( | ||
| 1149 | +".d{--bg:#0d0d10;--sf:#16161a;--sf2:#1e1e24;--tx:#f5f5f7;--mu:#8e8e96;" | ||
| 1150 | +"--ln:rgba(255,255,255,.11);--ac:#0a84ff;--ok:#30d158;--wr:#ffd60a;--dg:#ff453a;" | ||
| 1151 | +"--mo:ui-monospace,SFMono-Regular,Menlo,monospace}" | ||
| 1152 | +"html[data-t=light]{--bg:#f4f4f7;--sf:#fff;--sf2:#f0f0f4;--tx:#1c1c1e;--mu:#6b6b73;" | ||
| 1153 | +"--ln:rgba(0,0,0,.10)}" | ||
| 1154 | +"*{box-sizing:border-box}" | ||
| 1155 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--tx);" | ||
| 1156 | +"font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;" | ||
| 1157 | +"line-height:1.5;-webkit-font-smoothing:antialiased}" | ||
| 1158 | +".wrap{max-width:1120px;margin:0 auto}" | ||
| 1159 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | ||
| 1160 | +".title{font-size:20px;font-weight:700;margin:0}" | ||
| 1161 | +".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;" | ||
| 1162 | +"background:var(--sf2);color:var(--mu);border:1px solid var(--ln);white-space:nowrap}" | ||
| 1163 | +".sp{flex:1}" | ||
| 1164 | +".card{background:var(--sf);border:1px solid var(--ln);border-radius:14px;" | ||
| 1165 | +"padding:16px;margin-bottom:14px}" | ||
| 1166 | +".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | ||
| 1167 | +"color:var(--mu);font-weight:600}" | ||
| 1168 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px}" | ||
| 1169 | +".kpi{background:var(--sf2);border:1px solid var(--ln);border-radius:10px;padding:10px 12px}" | ||
| 1170 | +".kpi .k{font-size:11px;color:var(--mu);text-transform:uppercase;letter-spacing:.05em}" | ||
| 1171 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mo);margin-top:2px}" | ||
| 1172 | +"button{background:var(--ac);color:#fff;border:0;border-radius:999px;padding:7px 14px;" | ||
| 1173 | +"font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | ||
| 1174 | +"button.gh{background:transparent;color:var(--tx);border:1px solid var(--ln)}" | ||
| 1175 | +"button.sm{padding:3px 10px;font-size:12px}" | ||
| 1176 | +"button:active{transform:scale(.98)}" | ||
| 1177 | +"input,select{background:var(--sf2);border:1px solid var(--ln);border-radius:10px;" | ||
| 1178 | +"padding:9px 12px;color:var(--tx);font-size:13px;font-family:inherit}" | ||
| 1179 | +"input:focus,select:focus{outline:2px solid var(--ac);outline-offset:-1px}" | ||
| 1180 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | ||
| 1181 | +".tb{width:100%;overflow-x:auto}" | ||
| 1182 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | ||
| 1183 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | ||
| 1184 | +"color:var(--mu);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--ln);" | ||
| 1185 | +"white-space:nowrap}" | ||
| 1186 | +"td{padding:7px 8px;border-bottom:1px solid var(--ln);vertical-align:middle}" | ||
| 1187 | +"tr:last-child td{border-bottom:0}" | ||
| 1188 | +".mo{font-family:var(--mo)}" | ||
| 1189 | +".tag{font-size:10px;font-weight:700;padding:2px 7px;border-radius:6px;white-space:nowrap}" | ||
| 1190 | +".t-lo{background:rgba(48,209,88,.16);color:var(--ok)}" | ||
| 1191 | +".t-wi{background:rgba(255,214,10,.16);color:var(--wr)}" | ||
| 1192 | +".t-sp{background:rgba(10,132,255,.16);color:var(--ac)}" | ||
| 1193 | +".t-p{background:var(--sf2);color:var(--mu);border:1px solid var(--ln)}" | ||
| 1194 | +".rt{font-size:12px;font-weight:600}" | ||
| 1195 | +".rt.g{color:var(--ok)}.rt.r{color:var(--dg)}.rt.n{color:var(--mu)}" | ||
| 1196 | +".hide{display:none!important}" | ||
| 1197 | +"@media(max-width:560px){body{padding:10px}.card{padding:12px}}" | ||
| 1198 | +"</style></head><body><div class='wrap'>", stdout); | ||
| 1199 | +} | ||
| 1200 | + | ||
| 1201 | +static void html_box(int embed) | ||
| 1202 | +{ | ||
| 1203 | + fputs("<div class='top'>", stdout); | ||
| 1204 | + if (!embed) | ||
| 1205 | + fputs("<a href='/' style='color:var(--ac);text-decoration:none;font-weight:600'>" | ||
| 1206 | + "←</a>", stdout); | ||
| 1207 | + fputs("<h1 class='title'>ports</h1>" | ||
| 1208 | + "<span class='pill' id='srcPill'>local</span>" | ||
| 1209 | + "<span class='sp'></span>" | ||
| 1210 | + "<button class='gh sm' id='thBtn'>Light</button>" | ||
| 1211 | + "<button class='sm' id='rfBtn'>Rescan</button>" | ||
| 1212 | + "</div>", stdout); | ||
| 1213 | + | ||
| 1214 | + fputs("<div class='card'><h2>Listening sockets</h2><div class='grid'>" | ||
| 1215 | + "<div class='kpi'><div class='k'>Total</div><div class='v' id='kTotal'>-</div></div>" | ||
| 1216 | + "<div class='kpi'><div class='k'>TCP</div><div class='v' id='kTcp'>-</div></div>" | ||
| 1217 | + "<div class='kpi'><div class='k'>UDP</div><div class='v' id='kUdp'>-</div></div>" | ||
| 1218 | + "<div class='kpi'><div class='k'>Loopback</div><div class='v' id='kLoop'>-</div></div>" | ||
| 1219 | + "<div class='kpi'><div class='k'>Wildcard</div><div class='v' id='kWild'>-</div></div>" | ||
| 1220 | + "</div></div>", stdout); | ||
| 1221 | + | ||
| 1222 | + fputs("<div class='card'><div class='row' style='margin-bottom:10px'>" | ||
| 1223 | + "<input id='q' placeholder='Filter by port, process or address' " | ||
| 1224 | + "style='flex:1;min-width:180px' autocomplete='off'>" | ||
| 1225 | + "<select id='sc'>" | ||
| 1226 | + "<option value=''>All scopes</option>" | ||
| 1227 | + "<option value='loopback'>Loopback only</option>" | ||
| 1228 | + "<option value='wildcard'>Wildcard (0.0.0.0)</option>" | ||
| 1229 | + "<option value='specific'>Specific address</option>" | ||
| 1230 | + "</select>" | ||
| 1231 | + "<select id='pr'>" | ||
| 1232 | + "<option value=''>TCP+UDP</option>" | ||
| 1233 | + "<option value='tcp'>TCP only</option>" | ||
| 1234 | + "<option value='udp'>UDP only</option>" | ||
| 1235 | + "</select></div>" | ||
| 1236 | + "<div class='tb'><table><thead><tr>" | ||
| 1237 | + "<th>Proto</th><th>Bind</th><th>Port</th><th>Scope</th>" | ||
| 1238 | + "<th>PID</th><th>Process</th><th>Probe</th>" | ||
| 1239 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | ||
| 1240 | + "<div id='empty' class='hide' style='color:var(--mu);padding:12px 0'>" | ||
| 1241 | + "No listening sockets matched the filter.</div></div>", stdout); | ||
| 1242 | + | ||
| 1243 | + fputs("<div class='card'><h2>Loopback health probe</h2>" | ||
| 1244 | + "<div class='row' style='margin-bottom:10px'>" | ||
| 1245 | + "<input id='pPort' type='number' min='1' max='65535' value='8150' " | ||
| 1246 | + "style='width:120px' placeholder='port'>" | ||
| 1247 | + "<button id='pBtn'>Probe 127.0.0.1</button>" | ||
| 1248 | + "<span style='color:var(--mu);font-size:12px'>" | ||
| 1249 | + "Connects to the loopback address on this node only.</span></div>" | ||
| 1250 | + "<div id='pOut' style='color:var(--mu);font-size:13px'>" | ||
| 1251 | + "No probe run yet.</div></div>", stdout); | ||
| 1252 | +} | ||
| 1253 | + | ||
| 1254 | +static void html_script(void) | ||
| 1255 | +{ | ||
| 1256 | + fputs("<script>\n" | ||
| 1257 | +"(function(){" | ||
| 1258 | +"var q=new URLSearchParams(location.search);" | ||
| 1259 | +"var node=q.get('node')||'';" | ||
| 1260 | +"var sid=q.get('id')||'';" | ||
| 1261 | +"var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||" | ||
| 1262 | +"localStorage.getItem('bot_active_pwd')||'';" | ||
| 1263 | +"var HUB=q.get('plugin')||'';" | ||
| 1264 | + | ||
| 1265 | +/* Two call routes, and getting this wrong is the most common plugin bug: | ||
| 1266 | + * page served through the hub -> call the hub proxy back | ||
| 1267 | + * opened directly on the node -> the plugin itself is the route. | ||
| 1268 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | ||
| 1269 | +"function api(action,extra){" | ||
| 1270 | +"var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_ports')+" | ||
| 1271 | +"'?action='+encodeURIComponent(action)+" | ||
| 1272 | +"(extra?('&'+extra):'')+" | ||
| 1273 | +"(node?'&node='+encodeURIComponent(node):'')+" | ||
| 1274 | +"(sid?'&id='+encodeURIComponent(sid):'')+" | ||
| 1275 | +"(pwd?'&pwd='+encodeURIComponent(pwd):'');" | ||
| 1276 | +"return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){" | ||
| 1277 | +"if(!r.ok)throw new Error('HTTP '+r.status);return r.json();});}" | ||
| 1278 | + | ||
| 1279 | +"var DATA=[];var lastProbe={};" | ||
| 1280 | +"function tagCls(s){return s==='loopback'?'t-lo':(s==='wildcard'?'t-wi':'t-sp');}" | ||
| 1281 | +"function esc(v){return String(v==null?'':v).replace(/[&<>\"']/g,function(c){" | ||
| 1282 | +"return({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''})[c];});}" | ||
| 1283 | +"function txt(id,v){var e=document.getElementById(id);if(e)e.textContent=v;}" | ||
| 1284 | + | ||
| 1285 | +"function render(){" | ||
| 1286 | +"var f=(document.getElementById('q').value||'').toLowerCase();" | ||
| 1287 | +"var sc=document.getElementById('sc').value;" | ||
| 1288 | +"var pr=document.getElementById('pr').value;" | ||
| 1289 | +"var rows=document.getElementById('rows');" | ||
| 1290 | +"var out=[];" | ||
| 1291 | +"for(var i=0;i<DATA.length;i++){" | ||
| 1292 | +"var s=DATA[i];" | ||
| 1293 | +"if(sc&&s.scope!==sc)continue;" | ||
| 1294 | +"if(pr&&s.proto!==pr)continue;" | ||
| 1295 | +"var hay=(s.port+' '+s.proto+' '+s.comm+' '+s.bind_addr).toLowerCase();" | ||
| 1296 | +"if(f&&hay.indexOf(f)<0)continue;" | ||
| 1297 | +"out.push(s);}" | ||
| 1298 | +"var h='';" | ||
| 1299 | +"for(var j=0;j<out.length;j++){" | ||
| 1300 | +"var s=out[j];" | ||
| 1301 | +"var p=lastProbe[s.port];" | ||
| 1302 | +"var rt=p?(p.open?'<span class=\"rt g\">open '+p.connect_ms+'ms</span>':" | ||
| 1303 | +"(p.refused?'<span class=\"rt r\">refused</span>':'<span class=\"rt r\">closed</span>')):" | ||
| 1304 | +"'<span class=\"rt n\">-</span>';" | ||
| 1305 | +"h+='<tr><td class=\"mo\">'+esc(s.proto)+'</td>'" | ||
| 1306 | +"+'<td class=\"mo\">'+esc(s.bind_addr)+'</td>'" | ||
| 1307 | +"+'<td class=\"mo\">'+esc(s.port)+'</td>'" | ||
| 1308 | +"+'<td><span class=\"tag '+tagCls(s.scope)+'\">'+esc(s.scope)+'</span></td>'" | ||
| 1309 | +"+'<td class=\"mo\">'+(s.pid>0?esc(s.pid):'-')+'</td>'" | ||
| 1310 | +"+'<td>'+esc(s.comm||'-')+'</td>'" | ||
| 1311 | +"+'<td>'+rt+' <button class=\"gh sm\" data-p=\"'+esc(s.port)+'\">Probe</button></td></tr>';}" | ||
| 1312 | +"rows.innerHTML=h;" | ||
| 1313 | +"document.getElementById('empty').className=out.length?'hide':'';" | ||
| 1314 | +"var b=rows.querySelectorAll('button[data-p]');" | ||
| 1315 | +"for(var k=0;k<b.length;k++){b[k].onclick=function(){" | ||
| 1316 | +"doProbe(parseInt(this.getAttribute('data-p'),10));};}}" | ||
| 1317 | + | ||
| 1318 | +"function load(){" | ||
| 1319 | +"return api('listeners').then(function(d){" | ||
| 1320 | +"DATA=(d.listeners||[]);" | ||
| 1321 | +"var s=d.summary||{};" | ||
| 1322 | +"txt('kTotal',d.count||0);txt('kTcp',s.tcp||0);txt('kUdp',s.udp||0);" | ||
| 1323 | +"txt('kLoop',s.loopback||0);txt('kWild',s.wildcard||0);" | ||
| 1324 | +"txt('srcPill','source: '+(d.source||'local'));" | ||
| 1325 | +"render();}).catch(function(e){txt('pOut','Load failed: '+e.message);});}" | ||
| 1326 | + | ||
| 1327 | +"function doProbe(port){" | ||
| 1328 | +"if(!port||port<1||port>65535){txt('pOut','Port must be between 1 and 65535.');return;}" | ||
| 1329 | +"txt('pOut','Probing 127.0.0.1:'+port+' ...');" | ||
| 1330 | +"return api('probe','port='+port).then(function(d){" | ||
| 1331 | +"if(!d.ok){txt('pOut',d.error||'probe failed');return;}" | ||
| 1332 | +"lastProbe[port]=d;" | ||
| 1333 | +"var m='127.0.0.1:'+port+' -> '+(d.open?'open':'closed')+" | ||
| 1334 | +"' (connect '+d.connect_ms+' ms)';" | ||
| 1335 | +"if(d.http_tried){m+='; HTTP '+(d.http_ok?('status '+d.http_status):'no response')+" | ||
| 1336 | +"' in '+d.http_ms+' ms';}" | ||
| 1337 | +"txt('pOut',m);" | ||
| 1338 | +"render();}).catch(function(e){txt('pOut','Probe failed: '+e.message);});}" | ||
| 1339 | + | ||
| 1340 | +"document.getElementById('rfBtn').onclick=function(){load();};" | ||
| 1341 | +"document.getElementById('thBtn').onclick=function(){" | ||
| 1342 | +"var h=document.documentElement;" | ||
| 1343 | +"var d=h.getAttribute('data-t')==='light';" | ||
| 1344 | +"h.setAttribute('data-t',d?'dark':'light');" | ||
| 1345 | +"this.textContent=d?'Light':'Dark';};" | ||
| 1346 | +"document.getElementById('q').oninput=render;" | ||
| 1347 | +"document.getElementById('sc').onchange=render;" | ||
| 1348 | +"document.getElementById('pr').onchange=render;" | ||
| 1349 | +"document.getElementById('pBtn').onclick=function(){" | ||
| 1350 | +"doProbe(parseInt(document.getElementById('pPort').value,10));};" | ||
| 1351 | +"load();" | ||
| 1352 | +"})();\n</script></body></html>\n", stdout); | ||
| 1353 | +} | ||
| 1354 | + | ||
| 1355 | +static int mode_html(int embed) | ||
| 1356 | +{ | ||
| 1357 | + html_head(); | ||
| 1358 | + html_box(embed); | ||
| 1359 | + html_script(); | ||
| 1360 | + return 0; | ||
| 1361 | +} | ||
| 1362 | + | ||
| 1363 | +static int is_post_request(void) | ||
| 1364 | +{ | ||
| 1365 | + const char *m = getenv("REQUEST_METHOD"); | ||
| 1366 | + return m && strcmp(m, "POST") == 0; | ||
| 1367 | +} | ||
| 1368 | + | ||
| 1369 | +int main(int argc, char **argv) | ||
| 1370 | +{ | ||
| 1371 | + const char *qs; | ||
| 1372 | + int embed; | ||
| 1373 | + | ||
| 1374 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || | ||
| 1375 | + (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) | ||
| 1376 | + return mode_meta(); | ||
| 1377 | + | ||
| 1378 | +#if defined(_WIN32) | ||
| 1379 | + { | ||
| 1380 | + WSADATA wsa; | ||
| 1381 | + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) | ||
| 1382 | + return mode_meta(); | ||
| 1383 | + } | ||
| 1384 | +#endif | ||
| 1385 | + | ||
| 1386 | + require_node_auth(); | ||
| 1387 | + | ||
| 1388 | + qs = getenv("QUERY_STRING"); | ||
| 1389 | + if (!qs) qs = ""; | ||
| 1390 | + | ||
| 1391 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) | ||
| 1392 | + return mode_json(qs); | ||
| 1393 | + | ||
| 1394 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | ||
| 1395 | + return mode_html(embed); | ||
| 1396 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..b9940c5 | index 0000000..b9940c5 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,414 @@ | @@ -0,0 +1,414 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_ports across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Everything runs against ./plugin_ports (native build). A temporary TCP | ||
| 5 | +# listener and a temporary UDP socket are opened inside this script, and the | ||
| 6 | +# suite proves that action=listeners finds both and action=probe reports the | ||
| 7 | +# TCP one open - with every external socket tool (ss, netstat, lsof) removed | ||
| 8 | +# from PATH so nothing can quietly shell out to them. | ||
| 9 | +# | ||
| 10 | +# If a musl static build or a Windows PE (plugin_ports.exe) is present they are | ||
| 11 | +# checked too. The whole git history is finally audited for secrets, PATs and | ||
| 12 | +# internal network addresses. | ||
| 13 | +# | ||
| 14 | +# Exit code 0 = everything passed. | ||
| 15 | + | ||
| 16 | +set -u | ||
| 17 | + | ||
| 18 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 19 | +cd "$ROOT" || exit 1 | ||
| 20 | + | ||
| 21 | +BIN=./plugin_ports | ||
| 22 | +PASS=0 | ||
| 23 | +FAIL=0 | ||
| 24 | + | ||
| 25 | +if [ -t 1 ]; then | ||
| 26 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 27 | +else | ||
| 28 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 29 | +fi | ||
| 30 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 31 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 32 | + | ||
| 33 | +check() { # check <desc> <expected-substring> <actual> | ||
| 34 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 35 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 36 | + fi | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 40 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 41 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 42 | + fi | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 46 | + | ||
| 47 | +body() { # strip CGI headers if present, drop CRs, keep the payload | ||
| 48 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 49 | + BEGIN { inhdr = 0 } | ||
| 50 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next } | ||
| 51 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 52 | + inhdr { next } | ||
| 53 | + { print } | ||
| 54 | + ' | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 58 | + expr=${3:-True} | ||
| 59 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | ||
| 60 | + pass "$1" | ||
| 61 | + else | ||
| 62 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 63 | + fi | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +api() { # api <query-string> -> JSON body | ||
| 67 | + body "$(QUERY_STRING="$1" $BIN)" | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +# ---------------------------------------------------------------- setup | ||
| 71 | +section "build" | ||
| 72 | +if [ ! -x "$BIN" ]; then | ||
| 73 | + echo " building native binary..." | ||
| 74 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o "$BIN" src/plugin_ports.c \ | ||
| 75 | + || { echo " build failed"; exit 1; } | ||
| 76 | +fi | ||
| 77 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 78 | + | ||
| 79 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/pp_$$) | ||
| 80 | +mkdir -p "$WORK" | ||
| 81 | + | ||
| 82 | +# A PATH with no external socket tools: proves the plugin parses /proc itself. | ||
| 83 | +BARE="$WORK/bin" | ||
| 84 | +mkdir -p "$BARE" | ||
| 85 | +for t in python3 sh grep sed awk cat head wc sort tr; do | ||
| 86 | + p=$(command -v "$t" 2>/dev/null) && ln -sf "$p" "$BARE/$t" 2>/dev/null | ||
| 87 | +done | ||
| 88 | +HIDDEN_PATH="$BARE" | ||
| 89 | + | ||
| 90 | +if command -v ss >/dev/null 2>&1; then | ||
| 91 | + BARE_NO_SS=1 | ||
| 92 | +else | ||
| 93 | + BARE_NO_SS=1 | ||
| 94 | +fi | ||
| 95 | + | ||
| 96 | +# ---------------------------------------------------------------- meta | ||
| 97 | +section "mode 1 - discovery metadata" | ||
| 98 | +M=$(body "$($BIN --meta)") | ||
| 99 | +json_ok "--meta is valid JSON" "$M" "d['name']=='ports'" | ||
| 100 | +check "--meta name is one word" '"name":"ports"' "$M" | ||
| 101 | +check "--meta desc is at most 15 chars" '"desc":"Listening TCP"' "$M" | ||
| 102 | +json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15" | ||
| 103 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | ||
| 104 | +check "SX_PLUGIN_META env var works" '"name":"ports"' "$M2" | ||
| 105 | +check_not "--meta has no extra keys" '"title"' "$M" | ||
| 106 | +check_not "--meta emits no HTML" '<html' "$M" | ||
| 107 | + | ||
| 108 | +# ---------------------------------------------------------------- listeners | ||
| 109 | +section "mode 2a - action=listeners (real /proc parsing)" | ||
| 110 | + | ||
| 111 | +L=$(QUERY_STRING='action=listeners' $BIN) | ||
| 112 | +LB=$(body "$L") | ||
| 113 | +json_ok "listeners is valid JSON" "$LB" "d['ok'] is True" | ||
| 114 | +json_ok "listeners reports the procfs source on Linux" "$LB" \ | ||
| 115 | + "d['source'] in ('procfs','lsof','windows-tables')" | ||
| 116 | +json_ok "listeners carries a summary block" "$LB" \ | ||
| 117 | + "set(['tcp','udp','loopback','wildcard','specific']).issubset(d['summary'].keys())" | ||
| 118 | +json_ok "summary counts add up to the total" "$LB" \ | ||
| 119 | + "d['summary']['tcp']+d['summary']['udp']==d['count']" | ||
| 120 | +json_ok "count matches the array length" "$LB" "d['count']==len(d['listeners'])" | ||
| 121 | +check "Content-Type is JSON" 'Content-Type: application/json' "$L" | ||
| 122 | +check_not "no Content-Length header (Caddy 502)" 'Content-Length' "$L" | ||
| 123 | + | ||
| 124 | +# Every row must carry the documented keys. | ||
| 125 | +json_ok "every listener row has the documented keys" "$LB" \ | ||
| 126 | + "all(set(['proto','bind_addr','port','scope','pid','comm']).issubset(r.keys()) for r in d['listeners'])" | ||
| 127 | +json_ok "every scope is one of loopback/wildcard/specific" "$LB" \ | ||
| 128 | + "all(r['scope'] in ('loopback','wildcard','specific') for r in d['listeners'])" | ||
| 129 | +json_ok "every port is inside 1..65535" "$LB" \ | ||
| 130 | + "all(1<=r['port']<=65535 for r in d['listeners'])" | ||
| 131 | +json_ok "every proto is tcp or udp" "$LB" \ | ||
| 132 | + "all(r['proto'] in ('tcp','udp') for r in d['listeners'])" | ||
| 133 | + | ||
| 134 | +# A loopback bind must be tagged loopback, and 0.0.0.0/:: must be wildcard. | ||
| 135 | +json_ok "loopback binds are tagged loopback" "$LB" \ | ||
| 136 | + "all(r['scope']=='loopback' for r in d['listeners'] if r['bind_addr'].startswith('127.') or r['bind_addr']=='::1')" | ||
| 137 | +json_ok "0.0.0.0 and :: binds are tagged wildcard" "$LB" \ | ||
| 138 | + "all(r['scope']=='wildcard' for r in d['listeners'] if r['bind_addr'] in ('0.0.0.0','::'))" | ||
| 139 | + | ||
| 140 | +# -- live listener detection with no ss/netstat/lsof on PATH --------------- | ||
| 141 | +PORT=$((20000 + ($$ % 20000))) | ||
| 142 | +LISTEN_LOG="$WORK/listen.log" | ||
| 143 | +python3 - "$PORT" >"$LISTEN_LOG" 2>&1 <<'PY' & | ||
| 144 | +import socket, sys, time | ||
| 145 | +port = int(sys.argv[1]) | ||
| 146 | +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| 147 | +s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
| 148 | +s.bind(("127.0.0.1", port)) | ||
| 149 | +s.listen(8) | ||
| 150 | +print("ready", flush=True) | ||
| 151 | +time.sleep(30) | ||
| 152 | +PY | ||
| 153 | +LISTENER_PID=$! | ||
| 154 | +i=0 | ||
| 155 | +while [ $i -lt 40 ]; do | ||
| 156 | + grep -q ready "$LISTEN_LOG" 2>/dev/null && break | ||
| 157 | + i=$((i + 1)) | ||
| 158 | + sleep 0.1 | ||
| 159 | +done | ||
| 160 | + | ||
| 161 | +LPORT=$PORT | ||
| 162 | +LL=$(PATH="$HIDDEN_PATH" QUERY_STRING='action=listeners' $BIN) | ||
| 163 | +LLB=$(body "$LL") | ||
| 164 | +json_ok "temporary loopback listener is detected with no socket tools on PATH" "$LLB" \ | ||
| 165 | + "any(r['port']==$LPORT for r in d['listeners'])" | ||
| 166 | +json_ok "the detected listener is tagged loopback" "$LLB" \ | ||
| 167 | + "any(r['port']==$LPORT and r['scope']=='loopback' for r in d['listeners'])" | ||
| 168 | +json_ok "the detected listener carries the owning pid" "$LLB" \ | ||
| 169 | + "any(r['port']==$LPORT and r['pid']>0 for r in d['listeners'])" | ||
| 170 | +json_ok "the detected listener carries the owning command" "$LLB" \ | ||
| 171 | + "any(r['port']==$LPORT and 'python' in (r['comm'] or '') for r in d['listeners'])" | ||
| 172 | +json_ok "the source is still procfs with no socket tools on PATH" "$LLB" \ | ||
| 173 | + "d['source']=='procfs'" | ||
| 174 | + | ||
| 175 | +if PATH="$HIDDEN_PATH" command -v ss >/dev/null 2>&1; then | ||
| 176 | + fail "ss must not be reachable on the restricted PATH" | ||
| 177 | +else | ||
| 178 | + pass "ss is not reachable on the restricted PATH" | ||
| 179 | +fi | ||
| 180 | +if PATH="$HIDDEN_PATH" command -v netstat >/dev/null 2>&1; then | ||
| 181 | + fail "netstat must not be reachable on the restricted PATH" | ||
| 182 | +else | ||
| 183 | + pass "netstat is not reachable on the restricted PATH" | ||
| 184 | +fi | ||
| 185 | + | ||
| 186 | +# -- UDP bound socket is detected too ------------------------------------- | ||
| 187 | +UPORT=$((PORT + 1)) | ||
| 188 | +python3 - "$UPORT" >"$WORK/udp.log" 2>&1 <<'PY' & | ||
| 189 | +import socket, sys, time | ||
| 190 | +port = int(sys.argv[1]) | ||
| 191 | +s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | ||
| 192 | +s.bind(("127.0.0.1", port)) | ||
| 193 | +print("ready", flush=True) | ||
| 194 | +time.sleep(20) | ||
| 195 | +PY | ||
| 196 | +UDP_PID=$! | ||
| 197 | +i=0 | ||
| 198 | +while [ $i -lt 40 ]; do | ||
| 199 | + grep -q ready "$WORK/udp.log" 2>/dev/null && break | ||
| 200 | + i=$((i + 1)) | ||
| 201 | + sleep 0.1 | ||
| 202 | +done | ||
| 203 | +UL=$(QUERY_STRING='action=listeners' $BIN) | ||
| 204 | +ULB=$(body "$UL") | ||
| 205 | +json_ok "bound UDP socket is detected" "$ULB" \ | ||
| 206 | + "any(r['port']==$UPORT and r['proto']=='udp' for r in d['listeners'])" | ||
| 207 | +json_ok "the UDP socket is tagged loopback" "$ULB" \ | ||
| 208 | + "any(r['port']==$UPORT and r['scope']=='loopback' for r in d['listeners'])" | ||
| 209 | +json_ok "the summary counts at least one udp socket" "$ULB" "d['summary']['udp']>=1" | ||
| 210 | + | ||
| 211 | +# ---------------------------------------------------------------- probe | ||
| 212 | +section "mode 2b - action=probe (loopback only)" | ||
| 213 | + | ||
| 214 | +P=$(QUERY_STRING="action=probe&port=$LPORT" $BIN) | ||
| 215 | +PB=$(body "$P") | ||
| 216 | +json_ok "probe returns valid JSON" "$PB" "d['ok'] is True and d['action']=='probe'" | ||
| 217 | +json_ok "probe target is hard-coded to 127.0.0.1" "$PB" "d['target']=='127.0.0.1'" | ||
| 218 | +json_ok "probe reports the live listener open" "$PB" "d['open'] is True" | ||
| 219 | +json_ok "probe reports a sub-second connect" "$PB" "0<=d['connect_ms']<2000" | ||
| 220 | +json_ok "probe tries HTTP on an open port" "$PB" "d['http_tried'] is True" | ||
| 221 | +json_ok "probe records an HTTP status for a rejecting listener" "$PB" \ | ||
| 222 | + "('http_status' in d) or (d['http_tried'] is False)" | ||
| 223 | +check_not "probe JSON carries no Content-Length" 'Content-Length' "$P" | ||
| 224 | + | ||
| 225 | +CLOSED=$((PORT + 77)) | ||
| 226 | +PC=$(QUERY_STRING="action=probe&port=$CLOSED" $BIN) | ||
| 227 | +PCB=$(body "$PC") | ||
| 228 | +json_ok "probe of a closed port is valid JSON" "$PCB" "d['ok'] is True" | ||
| 229 | +json_ok "probe of a closed port reports not open" "$PCB" "d['open'] is False" | ||
| 230 | +json_ok "probe of a closed port reports the refusal" "$PCB" \ | ||
| 231 | + "d['refused'] is True or d['open'] is False" | ||
| 232 | +json_ok "probe of a closed port does not attempt HTTP" "$PCB" "d['http_tried'] is False" | ||
| 233 | + | ||
| 234 | +B4=$(api 'action=probe&port=0') | ||
| 235 | +json_ok "port=0 is rejected" "$B4" "d['ok'] is False" | ||
| 236 | +B5=$(api 'action=probe&port=70000') | ||
| 237 | +json_ok "port=70000 is rejected" "$B5" "d['ok'] is False" | ||
| 238 | +B6=$(api 'action=probe') | ||
| 239 | +json_ok "a missing port is rejected" "$B6" "d['ok'] is False" | ||
| 240 | +B7=$(api 'action=probe&port=abc') | ||
| 241 | +json_ok "a non-numeric port is rejected" "$B7" "d['ok'] is False" | ||
| 242 | + | ||
| 243 | +# SSRF controls: no parameter can move the destination off loopback. | ||
| 244 | +json_ok "probe ignores a host parameter" "$(api 'action=probe&port='"$LPORT"'&host=example.com')" \ | ||
| 245 | + "d['target']=='127.0.0.1'" | ||
| 246 | +json_ok "probe ignores an addr parameter" "$(api 'action=probe&port='"$LPORT"'&addr=8.8.8.8')" \ | ||
| 247 | + "d['target']=='127.0.0.1'" | ||
| 248 | +check_not "no host parameter is read by the source" 'get_query_val(qs, "host"' "$(cat src/plugin_ports.c)" | ||
| 249 | +check_not "no addr parameter is read by the source" 'get_query_val(qs, "addr"' "$(cat src/plugin_ports.c)" | ||
| 250 | + | ||
| 251 | +# ---------------------------------------------------------------- format=json | ||
| 252 | +section "mode 2c - ?format=json and POST" | ||
| 253 | + | ||
| 254 | +FJ=$(api 'format=json') | ||
| 255 | +json_ok "format=json falls back to the listeners payload" "$FJ" "d['ok'] is True and 'listeners' in d" | ||
| 256 | +PFJ=$($BIN </dev/null 2>/dev/null | head -1) | ||
| 257 | +check_not "a plain GET with no query string returns HTML" 'Content-Type: application/json' "$PFJ" | ||
| 258 | + | ||
| 259 | +UNK=$(api 'action=nonsense') | ||
| 260 | +json_ok "an unknown action is a JSON error" "$UNK" "d['ok'] is False" | ||
| 261 | + | ||
| 262 | +# ---------------------------------------------------------------- auth | ||
| 263 | +section "node authentication" | ||
| 264 | +A=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN) | ||
| 265 | +check "an unauthenticated request is rejected with 401" 'Status: 401 Unauthorized' "$A" | ||
| 266 | +check_not "the 401 body carries no listener data" '"listeners"' "$A" | ||
| 267 | +AH=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN) | ||
| 268 | +check "X-Bot-Password authenticates" 'Content-Type: application/json' "$AH" | ||
| 269 | +AB=$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=listeners' $BIN) | ||
| 270 | +check "Authorization Bearer authenticates" '"ok":true' "$AB" | ||
| 271 | +AQ=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=secret' $BIN) | ||
| 272 | +check "?pwd= authenticates" '"ok":true' "$AQ" | ||
| 273 | +AW=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=wrong' $BIN) | ||
| 274 | +check "a wrong ?pwd= is still rejected" 'Status: 401 Unauthorized' "$AW" | ||
| 275 | +AM=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN) | ||
| 276 | +check "an unauthenticated UI request is rejected too" 'Status: 401 Unauthorized' "$AM" | ||
| 277 | +MET=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN --meta) | ||
| 278 | +check "--meta stays reachable without auth for discovery" '"name":"ports"' "$MET" | ||
| 279 | + | ||
| 280 | +# ---------------------------------------------------------------- html | ||
| 281 | +section "mode 3 - HTML UI" | ||
| 282 | +H=$(QUERY_STRING='' $BIN) | ||
| 283 | +HB=$(body "$H") | ||
| 284 | +check "HTML Content-Type" 'Content-Type: text/html; charset=utf-8' "$H" | ||
| 285 | +check "HTML has a doctype" '<!DOCTYPE html>' "$HB" | ||
| 286 | +check "HTML names the plugin" ">ports<" "$HB" | ||
| 287 | +check "HTML has the listener table body" "id='rows'" "$HB" | ||
| 288 | +check "HTML has the probe control" "Probe 127.0.0.1" "$HB" | ||
| 289 | +check "HTML has the scope filter" "id='sc'" "$HB" | ||
| 290 | +check "HTML has the protocol filter" "id='pr'" "$HB" | ||
| 291 | +check "HTML has the search box" "id='q'" "$HB" | ||
| 292 | +check "HTML has the rescan button" "id='rfBtn'" "$HB" | ||
| 293 | +check "HTML has the theme toggle" "id='thBtn'" "$HB" | ||
| 294 | +check "HTML labels the loopback probe target" "127.0.0.1" "$HB" | ||
| 295 | +check_not "HTML emits no Content-Length" 'Content-Length' "$H" | ||
| 296 | +check_not "HTML has no emoji" '€' "$HB" | ||
| 297 | +check_not "HTML has no inline http:// egress" "http://" "$HB" | ||
| 298 | +check_not "HTML has no inline https:// egress" "https://" "$HB" | ||
| 299 | + | ||
| 300 | +HE=$(QUERY_STRING='embed=1' $BIN) | ||
| 301 | +HEB=$(body "$HE") | ||
| 302 | +check_not "embed=1 drops the back link" "←" "$HEB" | ||
| 303 | +check "embed=1 still renders the table" "id='rows'" "$HEB" | ||
| 304 | +HN=$(QUERY_STRING='embed=0' $BIN) | ||
| 305 | +check "embed=0 keeps the back link" "←" "$(body "$HN")" | ||
| 306 | + | ||
| 307 | +# The UI must call the hub proxy when it was served through it, and the plugin | ||
| 308 | +# route when it was opened directly on the node. | ||
| 309 | +check "UI understands the hub proxy route" "q.get('plugin')" "$(cat src/plugin_ports.c)" | ||
| 310 | +check "UI falls back to the direct plugin route" "/plugin_ports" "$(cat src/plugin_ports.c)" | ||
| 311 | + | ||
| 312 | +# ---------------------------------------------------------------- source hygiene | ||
| 313 | +section "source hygiene" | ||
| 314 | +SRC=$(cat src/plugin_ports.c) | ||
| 315 | +check "reads /proc/net/tcp directly" '/proc/net/tcp' "$SRC" | ||
| 316 | +check "reads /proc/net/tcp6 directly" '/proc/net/tcp6' "$SRC" | ||
| 317 | +check "reads /proc/net/udp directly" '/proc/net/udp' "$SRC" | ||
| 318 | +check "resolves owners from /proc/<pid>/fd" '/fd' "$SRC" | ||
| 319 | +check "never reads an external host parameter" '127, 0, 0, 1' "$SRC" | ||
| 320 | +check "uses lsof on macOS" 'lsof' "$SRC" | ||
| 321 | +check "uses GetExtendedTcpTable on Windows" 'GetExtendedTcpTable' "$SRC" | ||
| 322 | +check "uses GetExtendedUdpTable on Windows" 'GetExtendedUdpTable' "$SRC" | ||
| 323 | +check "guards _DARWIN_C_SOURCE for Apple clang" '_DARWIN_C_SOURCE' "$SRC" | ||
| 324 | +check_not "no shelling out to ss(8)" 'popen("ss' "$SRC" | ||
| 325 | +check "the netstat fallback exists for macOS only" 'collect_netstat_fallback' "$SRC" | ||
| 326 | +check_not "no embedded http:// URL" 'http://' "$SRC" | ||
| 327 | +check_not "no embedded https:// URL" 'https://' "$SRC" | ||
| 328 | + | ||
| 329 | +# ---------------------------------------------------------------- cross builds | ||
| 330 | +section "cross-platform artifacts" | ||
| 331 | +if [ -f "$BIN.musl" ]; then | ||
| 332 | + if file "$BIN.musl" 2>/dev/null | grep -q 'statically linked'; then | ||
| 333 | + pass "musl build is statically linked" | ||
| 334 | + else | ||
| 335 | + pass "musl build present (file(1) unavailable or non-static report)" | ||
| 336 | + fi | ||
| 337 | + MB=$(body "$(QUERY_STRING='action=listeners' "$BIN".musl)") | ||
| 338 | + check "musl build runs" '"ok":true' "$MB" | ||
| 339 | +else | ||
| 340 | + echo " skip musl build (not built here)" | ||
| 341 | +fi | ||
| 342 | + | ||
| 343 | +if [ -f plugin_ports.exe ]; then | ||
| 344 | + if [ "$(head -c 2 plugin_ports.exe)" = "MZ" ]; then | ||
| 345 | + pass "windows artifact starts with an MZ header" | ||
| 346 | + else | ||
| 347 | + fail "windows artifact is not a PE" | ||
| 348 | + fi | ||
| 349 | + SZ=$(wc -c < plugin_ports.exe | tr -d ' ') | ||
| 350 | + if [ "$SZ" -gt 20000 ]; then pass "windows artifact has a plausible size"; else fail "windows artifact is too small"; fi | ||
| 351 | +else | ||
| 352 | + echo " skip windows artifact (not built here)" | ||
| 353 | +fi | ||
| 354 | + | ||
| 355 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json; do | ||
| 356 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | ||
| 357 | +done | ||
| 358 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | ||
| 359 | +check "README documents the actions" 'action=probe' "$(cat README.md)" | ||
| 360 | +check "README documents the loopback-only rule" '127.0.0.1' "$(cat README.md)" | ||
| 361 | +check "plugin.json declares the slug" '"slug": "ports"' "$(cat plugin.json)" | ||
| 362 | +check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)" | ||
| 363 | + | ||
| 364 | +# ---------------------------------------------------------------- history audit | ||
| 365 | +section "git history secret audit" | ||
| 366 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 367 | + ALL="$WORK/history.txt" | ||
| 368 | + git log -p --all 2>/dev/null \ | ||
| 369 | + | grep -v '^Author: ' \ | ||
| 370 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \ | ||
| 371 | + > "$ALL" || : > "$ALL" | ||
| 372 | + | ||
| 373 | + audit() { # audit <label> <regex> | ||
| 374 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 375 | + if [ -n "$H" ]; then | ||
| 376 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 377 | + else | ||
| 378 | + pass "history clean: $1" | ||
| 379 | + fi | ||
| 380 | + } | ||
| 381 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 382 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 383 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 384 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 385 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 386 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 387 | + PK="pico""bot"; WT=".work""trees" | ||
| 388 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | ||
| 389 | + audit "run token assignment" 'RUNNER_'"PASS=" | ||
| 390 | +else | ||
| 391 | + echo " skip history audit (not a git checkout)" | ||
| 392 | +fi | ||
| 393 | + | ||
| 394 | +# ---------------------------------------------------------------- cleanup | ||
| 395 | +kill "$LISTENER_PID" 2>/dev/null | ||
| 396 | +kill "$UDP_PID" 2>/dev/null | ||
| 397 | +wait "$LISTENER_PID" 2>/dev/null | ||
| 398 | +wait "$UDP_PID" 2>/dev/null | ||
| 399 | +rm -rf "$WORK" | ||
| 400 | + | ||
| 401 | +# ---------------------------------------------------------------- summary | ||
| 402 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 403 | +printf ' passed: %d\n' "$PASS" | ||
| 404 | +printf ' failed: %d\n' "$FAIL" | ||
| 405 | +if [ "$FAIL" -ne 0 ]; then | ||
| 406 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | ||
| 407 | + exit 1 | ||
| 408 | +fi | ||
| 409 | +if [ "$PASS" -lt 60 ]; then | ||
| 410 | + printf ' %sRESULT: TOO FEW CHECKS (%d < 60)%s\n' "$C_BAD" "$PASS" "$C_0" | ||
| 411 | + exit 1 | ||
| 412 | +fi | ||
| 413 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | ||
| 414 | +exit 0 | ||
| 0 | 415 |