summaryrefslogtreecommitdiff
path: root/web/discover.py
blob: d3d08be7810a6d57903c7183c3155ba4911d458c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""One-shot Linux listener inventory for 9web. Never connects to a listener.

Only socket-inode ownership establishes a process/listener relationship. Parent
commands can identify a launcher, but never turn an arbitrary Node socket into
HTTP. Output deliberately omits full argv/environment (which may hold secrets).
"""
import ipaddress
import json
import os
import socket
import sys


def recognize(argv):
    if not argv:
        return None
    exe = os.path.basename(argv[0])
    args = argv[1:]
    if exe in ('miniserve', '9web'):
        return exe, 'https' if '--tls-cert' in args else 'http', 'recognized executable'
    if exe.startswith('python') and any(args[i:i+2] == ['-m', 'http.server'] for i in range(len(args))):
        return 'python http.server', 'http', 'python -m http.server'
    if exe == 'typst' and 'watch' in args:
        return 'typst watch', 'http', 'typst watch'
    # Require a CLI entrypoint, not a substring anywhere in arbitrary arguments.
    if exe in ('node', 'nodejs', 'bun') and args:
        entry = args[0].replace('\\', '/')
        if entry.endswith(('/vite/bin/vite.js', '/vite/bin/vite.mjs')):
            return 'vite', 'https' if '--https' in args else 'http', 'Vite CLI entrypoint'
        if '/wrangler/' in entry and 'dev' in args:
            return 'wrangler dev', 'http', 'Wrangler dev entrypoint'
    return None


def inventory(web_pid=None, web_ports=()):
    owners = {}
    for name in os.listdir('/proc'):
        if not name.isdecimal():
            continue
        base = '/proc/' + name
        try:
            argv = open(base + '/cmdline', 'rb').read(65536).decode(errors='replace').rstrip('\0').split('\0')
            exe = os.path.basename(os.readlink(base + '/exe'))
            cwd = os.readlink(base + '/cwd')
            fds = os.listdir(base + '/fd')
        except (OSError, ValueError):
            continue
        recognized = recognize([exe] + argv[1:])
        # 9web has both HTTP and 9P sockets. Its own configured listeners are
        # supplied separately by the catalogue, never inferred from its name.
        if exe == '9web':
            recognized = None
        for fd in fds:
            try:
                link = os.readlink(base + '/fd/' + fd)
            except OSError:
                continue
            if link.startswith('socket:['):
                owners.setdefault(link[8:-1], []).append(dict(
                    pid=int(name), process=exe, cwd=cwd, recognized=recognized))
    rows = []
    for table, family in [('tcp', socket.AF_INET), ('tcp6', socket.AF_INET6)]:
        try:
            lines = open('/proc/net/' + table).readlines()[1:]
        except OSError:
            continue
        for line in lines:
            fields = line.split()
            if fields[3] != '0A':
                continue
            raw, port = fields[1].split(':')
            packed = b''.join(int(raw[i:i+8], 16).to_bytes(4, sys.byteorder) for i in range(0, len(raw), 8))
            address = socket.inet_ntop(family, packed)
            inode = fields[9]
            processes = {p['pid']: p for p in owners.get(inode, [])}
            recognized = [p for p in processes.values() if p['recognized']]
            p = recognized[0] if recognized else next(iter(processes.values()), None)
            rec = p['recognized'] if p else None
            if web_pid in processes and int(port, 16) in web_ports:
                p = processes[web_pid]
                rec = ('9web', 'http', '9web known HTTP listener')
            rows.append(dict(id=table + '-' + inode, address=address, port=int(port, 16),
                protocol=rec[1] if rec else 'unknown', service=rec[0] if rec else None,
                pid=p['pid'] if p else None, process=p['process'] if p else None,
                cwd=p['cwd'] if p else None,
                local=ipaddress.ip_address(address).is_loopback,
                evidence=('socket inode ownership; ' + rec[2]) if rec else
                    ('socket inode ownership; unrecognized protocol' if p else 'process ownership unavailable')))
    return sorted(rows, key=lambda r: (r['port'], r['address']))


if __name__ == '__main__':
    print(json.dumps(inventory(int(sys.argv[1]), [int(p) for p in sys.argv[2].split(',')]) if len(sys.argv) == 3 else inventory()))