@myrialabs/clopen 0.4.33 → 0.4.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/auth/permissions.ts +3 -0
- package/backend/auth/rate-limiter.test.ts +115 -0
- package/backend/auth/rate-limiter.ts +25 -12
- package/backend/db-client/connection-manager.ts +13 -0
- package/backend/index.ts +9 -0
- package/backend/middleware/security.test.ts +95 -0
- package/backend/middleware/security.ts +114 -0
- package/backend/ports/attribute.test.ts +231 -0
- package/backend/ports/attribute.ts +444 -0
- package/backend/ports/kill.ts +203 -0
- package/backend/ports/monitor.ts +365 -0
- package/backend/ports/processes.test.ts +98 -0
- package/backend/ports/processes.ts +374 -0
- package/backend/ports/registry.ts +165 -0
- package/backend/ports/runner.ts +195 -0
- package/backend/ports/scan-host.ts +260 -0
- package/backend/ports/scan.test.ts +341 -0
- package/backend/ports/scan.ts +687 -0
- package/backend/ports/ssh-lineage.ts +318 -0
- package/backend/ssh/forwards.ts +31 -0
- package/backend/ws/auth/device.ts +1 -1
- package/backend/ws/auth/login.ts +8 -4
- package/backend/ws/index.ts +2 -0
- package/backend/ws/ports/index.ts +19 -0
- package/backend/ws/ports/kill.ts +80 -0
- package/backend/ws/ports/list.ts +60 -0
- package/dist/assets/{index-BW0DA8NV.js → index-gGTMFUa8.js} +1 -1
- package/dist/assets/{index-BF4buYmI.js → index-vW2RpdHu.js} +1 -1
- package/dist/assets/main-CYCMEbXB.css +1 -0
- package/dist/assets/{main-BbwWLJRN.js → main-ZCojSzvW.js} +409 -406
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/ports/index.ts +5 -0
- package/shared/types/ports/port.ts +192 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-CCvRMXlP.css +0 -1
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port manager — reading the socket table on any supported platform.
|
|
3
|
+
*
|
|
4
|
+
* Each platform gets the probe that actually answers the question there, and
|
|
5
|
+
* every probe is normalised into the same `PortSocket` row so nothing
|
|
6
|
+
* downstream has to care which one ran:
|
|
7
|
+
*
|
|
8
|
+
* - macOS `lsof -F` — pid, login name and full bind address in one pass
|
|
9
|
+
* - Linux `ss -tuna -p` — falls back to `netstat`, then to `lsof`
|
|
10
|
+
* - Windows `netstat -ano` — pid only; the process name comes from the table
|
|
11
|
+
* built in processes.ts
|
|
12
|
+
*
|
|
13
|
+
* Two honest limits are reported rather than papered over. On Linux the kernel
|
|
14
|
+
* only names the owning process for sockets belonging to the calling user, so
|
|
15
|
+
* an unprivileged scan legitimately returns rows with no pid. And when a
|
|
16
|
+
* primary probe is missing and a fallback ran, the caller is told, because the
|
|
17
|
+
* fallbacks carry less detail.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type {
|
|
21
|
+
PortIpVersion,
|
|
22
|
+
PortLimitation,
|
|
23
|
+
PortProtocol,
|
|
24
|
+
PortSocket,
|
|
25
|
+
PortSocketState
|
|
26
|
+
} from '$shared/types/ports';
|
|
27
|
+
import { posixArgv, type CommandRunner, type ProbePlatform } from './runner';
|
|
28
|
+
import { debug } from '$shared/utils/logger';
|
|
29
|
+
|
|
30
|
+
/** Per-host memory of which probe answered, held by the host's scanner. */
|
|
31
|
+
export interface ProbeMemo {
|
|
32
|
+
probe?: string;
|
|
33
|
+
argv?: string[];
|
|
34
|
+
parse?: (stdout: string) => PortSocket[];
|
|
35
|
+
limitations?: PortLimitation[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface SocketScan {
|
|
39
|
+
sockets: PortSocket[];
|
|
40
|
+
limitations: PortLimitation[];
|
|
41
|
+
/** The probe that produced these rows, for the panel to report. */
|
|
42
|
+
probe: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Split `addr:port` where addr may be IPv6, bracketed, wildcard, or scoped. */
|
|
46
|
+
function splitAddressPort(value: string): { address: string; port: number } | null {
|
|
47
|
+
const trimmed = value.trim();
|
|
48
|
+
if (!trimmed || trimmed === '*') return null;
|
|
49
|
+
|
|
50
|
+
const lastColon = trimmed.lastIndexOf(':');
|
|
51
|
+
if (lastColon <= 0) return null;
|
|
52
|
+
|
|
53
|
+
let address = trimmed.slice(0, lastColon);
|
|
54
|
+
const portText = trimmed.slice(lastColon + 1);
|
|
55
|
+
|
|
56
|
+
// A wildcard port belongs to the peer column of a listening socket, which
|
|
57
|
+
// carries no information — the caller drops these.
|
|
58
|
+
if (portText === '*' || portText === '') return null;
|
|
59
|
+
const port = Number.parseInt(portText, 10);
|
|
60
|
+
if (!Number.isFinite(port) || port < 0 || port > 65535) return null;
|
|
61
|
+
|
|
62
|
+
if (address.startsWith('[') && address.endsWith(']')) address = address.slice(1, -1);
|
|
63
|
+
if (address === '' || address === '*') address = '*';
|
|
64
|
+
|
|
65
|
+
return { address, port };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** `0.0.0.0` and `::` mean the same thing as `*` and read worse in a table. */
|
|
69
|
+
function normaliseAddress(address: string): string {
|
|
70
|
+
if (address === '0.0.0.0' || address === '::' || address === '[::]') return '*';
|
|
71
|
+
return address;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function ipVersionOf(address: string, hint?: PortIpVersion): PortIpVersion {
|
|
75
|
+
if (hint) return hint;
|
|
76
|
+
return address.includes(':') ? 'v6' : 'v4';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Collapse the TCP state machine to the three states the UI acts on. A UDP
|
|
81
|
+
* socket has no state; a bound one with no peer is what "port in use" means,
|
|
82
|
+
* so it is reported as listening.
|
|
83
|
+
*/
|
|
84
|
+
function normaliseState(raw: string | null, protocol: PortProtocol, hasPeer: boolean): PortSocketState {
|
|
85
|
+
// UDP is connectionless, so whatever the probe puts in the state column is
|
|
86
|
+
// not a TCP state: `ss` says UNCONN, netstat leaves it blank. A bound socket
|
|
87
|
+
// with no peer is precisely what "this port is in use" means, so the peer
|
|
88
|
+
// decides and the reported state is ignored.
|
|
89
|
+
if (protocol === 'udp') return hasPeer ? 'established' : 'listen';
|
|
90
|
+
|
|
91
|
+
const state = (raw ?? '').toUpperCase();
|
|
92
|
+
if (state === 'LISTEN' || state === 'LISTENING') return 'listen';
|
|
93
|
+
if (state === 'ESTABLISHED' || state === 'ESTAB') return 'established';
|
|
94
|
+
return 'other';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function makeSocket(input: {
|
|
98
|
+
protocol: PortProtocol;
|
|
99
|
+
local: { address: string; port: number };
|
|
100
|
+
peer: { address: string; port: number } | null;
|
|
101
|
+
state: string | null;
|
|
102
|
+
pid: number | null;
|
|
103
|
+
processName: string | null;
|
|
104
|
+
user: string | null;
|
|
105
|
+
ipVersion?: PortIpVersion;
|
|
106
|
+
}): PortSocket {
|
|
107
|
+
const address = normaliseAddress(input.local.address);
|
|
108
|
+
return {
|
|
109
|
+
protocol: input.protocol,
|
|
110
|
+
ipVersion: ipVersionOf(address, input.ipVersion),
|
|
111
|
+
address,
|
|
112
|
+
port: input.local.port,
|
|
113
|
+
state: normaliseState(input.state, input.protocol, Boolean(input.peer)),
|
|
114
|
+
pid: input.pid,
|
|
115
|
+
processName: input.processName,
|
|
116
|
+
user: input.user,
|
|
117
|
+
peerAddress: input.peer ? normaliseAddress(input.peer.address) : null,
|
|
118
|
+
peerPort: input.peer ? input.peer.port : null
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
// lsof — macOS primary, Unix last resort
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
const LSOF_ARGV = posixArgv(['lsof', '-nP', '-iTCP', '-iUDP', '-FpcLfPntT']);
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* `lsof -F` emits one field per line, tagged by its first character: a process
|
|
130
|
+
* block (`p`id, `c`ommand, `L`ogin) followed by that process's file blocks
|
|
131
|
+
* (`f`d, `t`ype, `P`rotocol, `n`ame, `T`CP state). Fields carry forward until
|
|
132
|
+
* replaced, so the parser tracks the current process and flushes a socket each
|
|
133
|
+
* time a new `f` block or process block begins.
|
|
134
|
+
*/
|
|
135
|
+
export function parseLsof(stdout: string): PortSocket[] {
|
|
136
|
+
const sockets: PortSocket[] = [];
|
|
137
|
+
|
|
138
|
+
let pid: number | null = null;
|
|
139
|
+
let processName: string | null = null;
|
|
140
|
+
let user: string | null = null;
|
|
141
|
+
|
|
142
|
+
let protocol: PortProtocol | null = null;
|
|
143
|
+
let name: string | null = null;
|
|
144
|
+
let state: string | null = null;
|
|
145
|
+
let ipVersion: PortIpVersion | undefined;
|
|
146
|
+
|
|
147
|
+
const flush = (): void => {
|
|
148
|
+
if (!protocol || !name) return;
|
|
149
|
+
const [localText, peerText] = name.split('->');
|
|
150
|
+
const local = splitAddressPort(localText);
|
|
151
|
+
if (local) {
|
|
152
|
+
sockets.push(
|
|
153
|
+
makeSocket({
|
|
154
|
+
protocol,
|
|
155
|
+
local,
|
|
156
|
+
peer: peerText ? splitAddressPort(peerText) : null,
|
|
157
|
+
state,
|
|
158
|
+
pid,
|
|
159
|
+
processName,
|
|
160
|
+
user,
|
|
161
|
+
ipVersion
|
|
162
|
+
})
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
protocol = null;
|
|
166
|
+
name = null;
|
|
167
|
+
state = null;
|
|
168
|
+
ipVersion = undefined;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
for (const line of stdout.split('\n')) {
|
|
172
|
+
if (!line) continue;
|
|
173
|
+
const tag = line[0];
|
|
174
|
+
const value = line.slice(1);
|
|
175
|
+
|
|
176
|
+
switch (tag) {
|
|
177
|
+
case 'p':
|
|
178
|
+
flush();
|
|
179
|
+
pid = Number.parseInt(value, 10) || null;
|
|
180
|
+
break;
|
|
181
|
+
case 'c':
|
|
182
|
+
processName = value || null;
|
|
183
|
+
break;
|
|
184
|
+
case 'L':
|
|
185
|
+
user = value || null;
|
|
186
|
+
break;
|
|
187
|
+
case 'f':
|
|
188
|
+
flush();
|
|
189
|
+
break;
|
|
190
|
+
case 't':
|
|
191
|
+
ipVersion = value === 'IPv6' ? 'v6' : value === 'IPv4' ? 'v4' : undefined;
|
|
192
|
+
break;
|
|
193
|
+
case 'P':
|
|
194
|
+
protocol = value.toLowerCase() === 'udp' ? 'udp' : 'tcp';
|
|
195
|
+
break;
|
|
196
|
+
case 'n':
|
|
197
|
+
name = value;
|
|
198
|
+
break;
|
|
199
|
+
case 'T':
|
|
200
|
+
// Only the state matters; queue depths share this tag.
|
|
201
|
+
if (value.startsWith('ST=')) state = value.slice(3);
|
|
202
|
+
break;
|
|
203
|
+
default:
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
flush();
|
|
208
|
+
|
|
209
|
+
return sockets;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ---------------------------------------------------------------------------
|
|
213
|
+
// ss — Linux primary
|
|
214
|
+
// ---------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
const SS_ARGV = posixArgv(['ss', '-tuna', '-p']);
|
|
217
|
+
|
|
218
|
+
/** `users:(("nginx",pid=800,fd=6),("nginx",pid=801,fd=6))` → first pid + name. */
|
|
219
|
+
function parseSsProcess(field: string | undefined): { pid: number | null; name: string | null } {
|
|
220
|
+
if (!field) return { pid: null, name: null };
|
|
221
|
+
const match = field.match(/\("([^"]+)",pid=(\d+)/);
|
|
222
|
+
if (!match) return { pid: null, name: null };
|
|
223
|
+
return { name: match[1], pid: Number.parseInt(match[2], 10) || null };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function parseSs(stdout: string): PortSocket[] {
|
|
227
|
+
const sockets: PortSocket[] = [];
|
|
228
|
+
|
|
229
|
+
for (const rawLine of stdout.split('\n')) {
|
|
230
|
+
const line = rawLine.trim();
|
|
231
|
+
if (!line) continue;
|
|
232
|
+
// Older iproute2 has no -H, so the header is skipped by content.
|
|
233
|
+
if (line.startsWith('Netid') || line.startsWith('State')) continue;
|
|
234
|
+
|
|
235
|
+
const columns = line.split(/\s+/);
|
|
236
|
+
if (columns.length < 5) continue;
|
|
237
|
+
|
|
238
|
+
const netid = columns[0].toLowerCase();
|
|
239
|
+
if (netid !== 'tcp' && netid !== 'udp') continue;
|
|
240
|
+
const protocol: PortProtocol = netid === 'udp' ? 'udp' : 'tcp';
|
|
241
|
+
|
|
242
|
+
const local = splitAddressPort(columns[4]);
|
|
243
|
+
if (!local) continue;
|
|
244
|
+
const peer = columns.length > 5 ? splitAddressPort(columns[5]) : null;
|
|
245
|
+
const owner = parseSsProcess(columns.find((column) => column.startsWith('users:(')));
|
|
246
|
+
|
|
247
|
+
sockets.push(
|
|
248
|
+
makeSocket({
|
|
249
|
+
protocol,
|
|
250
|
+
local,
|
|
251
|
+
peer,
|
|
252
|
+
state: columns[1],
|
|
253
|
+
pid: owner.pid,
|
|
254
|
+
processName: owner.name,
|
|
255
|
+
user: null
|
|
256
|
+
})
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return sockets;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
// netstat — Linux fallback and Windows primary
|
|
265
|
+
// ---------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
const NETSTAT_UNIX_ARGV = posixArgv(['netstat', '-tunap']);
|
|
268
|
+
const NETSTAT_WINDOWS_ARGV = ['netstat', '-ano'];
|
|
269
|
+
|
|
270
|
+
/** `800/sshd` → pid and name; a bare `-` means the kernel withheld the owner. */
|
|
271
|
+
function parseNetstatProcess(field: string | undefined): { pid: number | null; name: string | null } {
|
|
272
|
+
if (!field || field === '-') return { pid: null, name: null };
|
|
273
|
+
const [pidText, ...rest] = field.split('/');
|
|
274
|
+
const pid = Number.parseInt(pidText, 10);
|
|
275
|
+
return {
|
|
276
|
+
pid: Number.isFinite(pid) ? pid : null,
|
|
277
|
+
name: rest.length ? rest.join('/').split(' ')[0] || null : null
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function parseNetstatUnix(stdout: string): PortSocket[] {
|
|
282
|
+
const sockets: PortSocket[] = [];
|
|
283
|
+
|
|
284
|
+
for (const rawLine of stdout.split('\n')) {
|
|
285
|
+
const line = rawLine.trim();
|
|
286
|
+
if (!line) continue;
|
|
287
|
+
|
|
288
|
+
const columns = line.split(/\s+/);
|
|
289
|
+
const proto = columns[0]?.toLowerCase() ?? '';
|
|
290
|
+
if (!proto.startsWith('tcp') && !proto.startsWith('udp')) continue;
|
|
291
|
+
const protocol: PortProtocol = proto.startsWith('udp') ? 'udp' : 'tcp';
|
|
292
|
+
// `tcp6`/`udp6` name the family directly, which beats guessing from the
|
|
293
|
+
// address — a wildcard bind looks identical in both families.
|
|
294
|
+
const ipVersion: PortIpVersion = proto.endsWith('6') ? 'v6' : 'v4';
|
|
295
|
+
|
|
296
|
+
const local = splitAddressPort(columns[3]);
|
|
297
|
+
if (!local) continue;
|
|
298
|
+
const peer = splitAddressPort(columns[4] ?? '');
|
|
299
|
+
// UDP rows have no state column, so the owner shifts one place left.
|
|
300
|
+
const state = protocol === 'tcp' ? (columns[5] ?? null) : null;
|
|
301
|
+
const owner = parseNetstatProcess(protocol === 'tcp' ? columns[6] : columns[5]);
|
|
302
|
+
|
|
303
|
+
sockets.push({
|
|
304
|
+
...makeSocket({
|
|
305
|
+
protocol,
|
|
306
|
+
local,
|
|
307
|
+
peer,
|
|
308
|
+
state,
|
|
309
|
+
pid: owner.pid,
|
|
310
|
+
processName: owner.name,
|
|
311
|
+
user: null,
|
|
312
|
+
ipVersion
|
|
313
|
+
})
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return sockets;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function parseNetstatWindows(stdout: string): PortSocket[] {
|
|
321
|
+
const sockets: PortSocket[] = [];
|
|
322
|
+
|
|
323
|
+
for (const rawLine of stdout.split('\n')) {
|
|
324
|
+
const line = rawLine.trim();
|
|
325
|
+
if (!line) continue;
|
|
326
|
+
|
|
327
|
+
const columns = line.split(/\s+/);
|
|
328
|
+
const proto = columns[0]?.toUpperCase() ?? '';
|
|
329
|
+
if (proto !== 'TCP' && proto !== 'UDP') continue;
|
|
330
|
+
const protocol: PortProtocol = proto === 'UDP' ? 'udp' : 'tcp';
|
|
331
|
+
|
|
332
|
+
const local = splitAddressPort(columns[1]);
|
|
333
|
+
if (!local) continue;
|
|
334
|
+
const peer = splitAddressPort(columns[2] ?? '');
|
|
335
|
+
// TCP: proto local peer state pid. UDP: proto local peer pid.
|
|
336
|
+
const state = protocol === 'tcp' ? (columns[3] ?? null) : null;
|
|
337
|
+
const pidText = protocol === 'tcp' ? columns[4] : columns[3];
|
|
338
|
+
const pid = Number.parseInt(pidText ?? '', 10);
|
|
339
|
+
|
|
340
|
+
sockets.push(
|
|
341
|
+
makeSocket({
|
|
342
|
+
protocol,
|
|
343
|
+
local,
|
|
344
|
+
peer,
|
|
345
|
+
state,
|
|
346
|
+
pid: Number.isFinite(pid) && pid > 0 ? pid : null,
|
|
347
|
+
// netstat never names the process; processes.ts fills this in.
|
|
348
|
+
processName: null,
|
|
349
|
+
user: null
|
|
350
|
+
})
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return sockets;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// ---------------------------------------------------------------------------
|
|
358
|
+
// /proc/net — the Linux probe that needs nothing installed
|
|
359
|
+
// ---------------------------------------------------------------------------
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Every file the kernel publishes its socket tables in. `grep ''` over all four
|
|
363
|
+
* prints each line prefixed with the file it came from, so one command returns
|
|
364
|
+
* every family and protocol already labelled — and files that do not exist are
|
|
365
|
+
* simply absent from the output.
|
|
366
|
+
*/
|
|
367
|
+
const PROC_NET_ARGV = posixArgv([
|
|
368
|
+
'grep',
|
|
369
|
+
'',
|
|
370
|
+
'/proc/net/tcp',
|
|
371
|
+
'/proc/net/tcp6',
|
|
372
|
+
'/proc/net/udp',
|
|
373
|
+
'/proc/net/udp6'
|
|
374
|
+
]);
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Sockets held open by processes we can see, as `inode → pid`.
|
|
378
|
+
*
|
|
379
|
+
* This is the one place a shell is used, because matching `/proc/<pid>/fd`
|
|
380
|
+
* across every process needs a glob and there is no way to expand one without
|
|
381
|
+
* it. The command is a fixed string with nothing interpolated into it.
|
|
382
|
+
*/
|
|
383
|
+
const PROC_FD_ARGV = ['sh', '-c', 'ls -l /proc/[0-9]*/fd/ 2>/dev/null'];
|
|
384
|
+
|
|
385
|
+
/** `0100007F` → `127.0.0.1`: four little-endian bytes in hex. */
|
|
386
|
+
function hexToIpv4(hex: string): string {
|
|
387
|
+
const octets: number[] = [];
|
|
388
|
+
for (let index = 6; index >= 0; index -= 2) octets.push(Number.parseInt(hex.slice(index, index + 2), 16));
|
|
389
|
+
return octets.join('.');
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 32 hex chars as four little-endian 32-bit words, rendered as IPv6. */
|
|
393
|
+
function hexToIpv6(hex: string): string {
|
|
394
|
+
const groups: string[] = [];
|
|
395
|
+
for (let word = 0; word < 4; word++) {
|
|
396
|
+
const chunk = hex.slice(word * 8, word * 8 + 8);
|
|
397
|
+
// Each 32-bit word is byte-swapped, giving two IPv6 groups once undone.
|
|
398
|
+
const swapped = chunk.slice(6, 8) + chunk.slice(4, 6) + chunk.slice(2, 4) + chunk.slice(0, 2);
|
|
399
|
+
groups.push(swapped.slice(0, 4), swapped.slice(4, 8));
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// The v4-mapped form reads as the address people actually recognise.
|
|
403
|
+
if (groups.slice(0, 5).every((group) => group === '0000') && groups[5].toLowerCase() === 'ffff') {
|
|
404
|
+
const high = Number.parseInt(groups[6], 16);
|
|
405
|
+
const low = Number.parseInt(groups[7], 16);
|
|
406
|
+
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
return compressIpv6(groups.map((group) => group.replace(/^0+/, '') || '0'));
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Collapse the longest run of zero groups into `::`, as IPv6 is written.
|
|
414
|
+
* Done by finding the run rather than by rewriting the string: a regex that
|
|
415
|
+
* chews through colons turns the all-zero address into a single `:`.
|
|
416
|
+
*/
|
|
417
|
+
function compressIpv6(groups: string[]): string {
|
|
418
|
+
let bestStart = -1;
|
|
419
|
+
let bestLength = 0;
|
|
420
|
+
let runStart = -1;
|
|
421
|
+
|
|
422
|
+
for (let index = 0; index <= groups.length; index++) {
|
|
423
|
+
if (index < groups.length && groups[index] === '0') {
|
|
424
|
+
if (runStart === -1) runStart = index;
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
if (runStart !== -1) {
|
|
428
|
+
const length = index - runStart;
|
|
429
|
+
// A single zero group is written out; `::` is only for a run.
|
|
430
|
+
if (length > bestLength && length > 1) {
|
|
431
|
+
bestStart = runStart;
|
|
432
|
+
bestLength = length;
|
|
433
|
+
}
|
|
434
|
+
runStart = -1;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (bestStart === -1) return groups.join(':');
|
|
439
|
+
|
|
440
|
+
const head = groups.slice(0, bestStart).join(':');
|
|
441
|
+
const tail = groups.slice(bestStart + bestLength).join(':');
|
|
442
|
+
return `${head}::${tail}`;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** TCP states as `/proc/net/tcp` numbers them. */
|
|
446
|
+
const PROC_STATE_LISTEN = '0A';
|
|
447
|
+
const PROC_STATE_ESTABLISHED = '01';
|
|
448
|
+
|
|
449
|
+
interface ProcNetSocket {
|
|
450
|
+
socket: PortSocket;
|
|
451
|
+
inode: number;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export function parseProcNet(stdout: string): ProcNetSocket[] {
|
|
455
|
+
const results: ProcNetSocket[] = [];
|
|
456
|
+
|
|
457
|
+
for (const rawLine of stdout.split('\n')) {
|
|
458
|
+
const line = rawLine.trim();
|
|
459
|
+
if (!line) continue;
|
|
460
|
+
|
|
461
|
+
const labelled = line.match(/^\/proc\/net\/(tcp6?|udp6?):(.*)$/);
|
|
462
|
+
if (!labelled) continue;
|
|
463
|
+
|
|
464
|
+
const source = labelled[1];
|
|
465
|
+
const protocol: PortProtocol = source.startsWith('udp') ? 'udp' : 'tcp';
|
|
466
|
+
const ipVersion: PortIpVersion = source.endsWith('6') ? 'v6' : 'v4';
|
|
467
|
+
|
|
468
|
+
const columns = labelled[2].trim().split(/\s+/);
|
|
469
|
+
// sl, local, remote, state, queues, timers, retrans, uid, timeout, inode
|
|
470
|
+
if (columns.length < 10 || !columns[0].endsWith(':')) continue;
|
|
471
|
+
|
|
472
|
+
const [localHex, localPortHex] = (columns[1] ?? '').split(':');
|
|
473
|
+
const [peerHex, peerPortHex] = (columns[2] ?? '').split(':');
|
|
474
|
+
if (!localHex || !localPortHex) continue;
|
|
475
|
+
|
|
476
|
+
const port = Number.parseInt(localPortHex, 16);
|
|
477
|
+
if (!Number.isFinite(port)) continue;
|
|
478
|
+
|
|
479
|
+
const state = (columns[3] ?? '').toUpperCase();
|
|
480
|
+
const peerPort = Number.parseInt(peerPortHex ?? '', 16);
|
|
481
|
+
const hasPeer = Number.isFinite(peerPort) && peerPort > 0;
|
|
482
|
+
|
|
483
|
+
const toAddress = (hex: string): string =>
|
|
484
|
+
ipVersion === 'v6' ? hexToIpv6(hex) : hexToIpv4(hex);
|
|
485
|
+
|
|
486
|
+
results.push({
|
|
487
|
+
inode: Number.parseInt(columns[9], 10) || 0,
|
|
488
|
+
socket: makeSocket({
|
|
489
|
+
protocol,
|
|
490
|
+
local: { address: toAddress(localHex), port },
|
|
491
|
+
peer: hasPeer ? { address: toAddress(peerHex), port: peerPort } : null,
|
|
492
|
+
state:
|
|
493
|
+
state === PROC_STATE_LISTEN
|
|
494
|
+
? 'LISTEN'
|
|
495
|
+
: state === PROC_STATE_ESTABLISHED
|
|
496
|
+
? 'ESTABLISHED'
|
|
497
|
+
: state,
|
|
498
|
+
pid: null,
|
|
499
|
+
processName: null,
|
|
500
|
+
user: null,
|
|
501
|
+
ipVersion
|
|
502
|
+
})
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
return results;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** `ls -l /proc/<pid>/fd/` output → which process holds which socket inode. */
|
|
510
|
+
export function parseProcFdInodes(stdout: string): Map<number, number> {
|
|
511
|
+
const owners = new Map<number, number>();
|
|
512
|
+
let pid: number | null = null;
|
|
513
|
+
|
|
514
|
+
for (const line of stdout.split('\n')) {
|
|
515
|
+
const header = line.match(/^\/proc\/(\d+)\/fd\/?:$/);
|
|
516
|
+
if (header) {
|
|
517
|
+
pid = Number.parseInt(header[1], 10);
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (pid === null) continue;
|
|
521
|
+
|
|
522
|
+
const socket = line.match(/socket:\[(\d+)\]/);
|
|
523
|
+
if (!socket) continue;
|
|
524
|
+
const inode = Number.parseInt(socket[1], 10);
|
|
525
|
+
// First writer wins: a forked child inherits the same inode, and the
|
|
526
|
+
// listing walks pids in ascending order, so that is the parent.
|
|
527
|
+
if (Number.isFinite(inode) && !owners.has(inode)) owners.set(inode, pid);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
return owners;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// ---------------------------------------------------------------------------
|
|
534
|
+
// Probe selection
|
|
535
|
+
// ---------------------------------------------------------------------------
|
|
536
|
+
|
|
537
|
+
const PIDS_NEED_ROOT: PortLimitation = {
|
|
538
|
+
code: 'pids-need-root',
|
|
539
|
+
message:
|
|
540
|
+
'Some sockets are owned by other users. The kernel only names the owning process for your own, so those rows have no owner.'
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
function ranWithoutOwners(sockets: PortSocket[]): boolean {
|
|
544
|
+
if (sockets.length === 0) return false;
|
|
545
|
+
return sockets.some((socket) => socket.pid === null);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Read the socket table with whichever probe this host can actually run.
|
|
550
|
+
*
|
|
551
|
+
* The chain matters on locked-down hosts. Shared hosting and container images
|
|
552
|
+
* routinely ship without `ss`, without `netstat`, or with both present but
|
|
553
|
+
* outside the PATH a non-interactive SSH session is given — and some strip
|
|
554
|
+
* `lsof` too. The kernel's own `/proc/net` tables need nothing installed at
|
|
555
|
+
* all, so a Linux host can always be read even when every tool is missing;
|
|
556
|
+
* only the owning process needs a second lookup there.
|
|
557
|
+
*/
|
|
558
|
+
export async function scanSockets(
|
|
559
|
+
runner: CommandRunner,
|
|
560
|
+
platform: ProbePlatform,
|
|
561
|
+
/** Remembers which probe worked, so the chain is walked once per host. */
|
|
562
|
+
memo: ProbeMemo = {}
|
|
563
|
+
): Promise<SocketScan> {
|
|
564
|
+
const limitations: PortLimitation[] = [];
|
|
565
|
+
const tried: string[] = [];
|
|
566
|
+
let probe = 'none';
|
|
567
|
+
let lastArgv: string[] = [];
|
|
568
|
+
let lastParse: (stdout: string) => PortSocket[] = parseLsof;
|
|
569
|
+
|
|
570
|
+
const attempt = async (
|
|
571
|
+
argv: string[],
|
|
572
|
+
parse: (stdout: string) => PortSocket[]
|
|
573
|
+
): Promise<PortSocket[] | null> => {
|
|
574
|
+
const name = argv.find((part) => !part.includes('=') && part !== 'env') ?? argv[0];
|
|
575
|
+
tried.push(name);
|
|
576
|
+
probe = name;
|
|
577
|
+
lastArgv = argv;
|
|
578
|
+
lastParse = parse;
|
|
579
|
+
try {
|
|
580
|
+
const result = await runner.run(argv);
|
|
581
|
+
// `ss` and `netstat` exit non-zero on a missing binary but also when
|
|
582
|
+
// they merely could not resolve some rows, so output wins over status.
|
|
583
|
+
const sockets = parse(result.stdout);
|
|
584
|
+
if (sockets.length > 0) return sockets;
|
|
585
|
+
if (result.code === 0) return sockets;
|
|
586
|
+
return null;
|
|
587
|
+
} catch (error) {
|
|
588
|
+
debug.log('ports', `probe ${argv[0]} failed on ${runner.label}:`, error);
|
|
589
|
+
return null;
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
|
|
593
|
+
/** The kernel's own tables, plus a best-effort owner for each socket. */
|
|
594
|
+
const attemptProcNet = async (): Promise<PortSocket[] | null> => {
|
|
595
|
+
tried.push('/proc/net');
|
|
596
|
+
probe = '/proc/net';
|
|
597
|
+
try {
|
|
598
|
+
const result = await runner.run(PROC_NET_ARGV);
|
|
599
|
+
const rows = parseProcNet(result.stdout);
|
|
600
|
+
if (rows.length === 0) return null;
|
|
601
|
+
|
|
602
|
+
let owners = new Map<number, number>();
|
|
603
|
+
try {
|
|
604
|
+
const fds = await runner.run(PROC_FD_ARGV);
|
|
605
|
+
owners = parseProcFdInodes(fds.stdout);
|
|
606
|
+
} catch (error) {
|
|
607
|
+
// Ports without an owner still answer "what is in use", which is
|
|
608
|
+
// the question that brought the user here.
|
|
609
|
+
debug.log('ports', `/proc fd scan failed on ${runner.label}:`, error);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
return rows.map(({ socket, inode }) => ({ ...socket, pid: owners.get(inode) ?? null }));
|
|
613
|
+
} catch (error) {
|
|
614
|
+
debug.log('ports', `/proc/net read failed on ${runner.label}:`, error);
|
|
615
|
+
return null;
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
|
|
619
|
+
const noteFallback = (message: string): void => {
|
|
620
|
+
limitations.push({ code: 'probe-fallback', message });
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
let sockets: PortSocket[] | null = null;
|
|
624
|
+
|
|
625
|
+
// A host that has already answered is asked the same way again. Walking the
|
|
626
|
+
// whole chain every tick means four failed commands a second on a host that
|
|
627
|
+
// has none of the tools — which on an SSH connection is four channels spent
|
|
628
|
+
// re-learning something that cannot change.
|
|
629
|
+
if (memo.probe) {
|
|
630
|
+
sockets = memo.probe === '/proc/net' ? await attemptProcNet() : await attempt(memo.argv ?? [], memo.parse ?? parseLsof);
|
|
631
|
+
if (sockets) {
|
|
632
|
+
for (const limitation of memo.limitations ?? []) limitations.push(limitation);
|
|
633
|
+
if (platform !== 'win32' && ranWithoutOwners(sockets)) limitations.push(PIDS_NEED_ROOT);
|
|
634
|
+
return { sockets, limitations, probe: memo.probe };
|
|
635
|
+
}
|
|
636
|
+
// The tool went away, or the host changed under us. Fall through and
|
|
637
|
+
// re-derive rather than reporting an empty table.
|
|
638
|
+
memo.probe = undefined;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
if (platform === 'win32') {
|
|
642
|
+
sockets = await attempt(NETSTAT_WINDOWS_ARGV, parseNetstatWindows);
|
|
643
|
+
} else if (platform === 'darwin') {
|
|
644
|
+
sockets = await attempt(LSOF_ARGV, parseLsof);
|
|
645
|
+
if (!sockets) {
|
|
646
|
+
sockets = await attempt(NETSTAT_UNIX_ARGV, parseNetstatUnix);
|
|
647
|
+
if (sockets) noteFallback('`lsof` is unavailable here, so `netstat` was used instead.');
|
|
648
|
+
}
|
|
649
|
+
} else {
|
|
650
|
+
sockets = await attempt(SS_ARGV, parseSs);
|
|
651
|
+
|
|
652
|
+
if (!sockets) {
|
|
653
|
+
sockets = await attempt(NETSTAT_UNIX_ARGV, parseNetstatUnix);
|
|
654
|
+
if (sockets) noteFallback('`ss` is unavailable here, so `netstat` was used instead.');
|
|
655
|
+
}
|
|
656
|
+
if (!sockets) {
|
|
657
|
+
sockets = await attempt(LSOF_ARGV, parseLsof);
|
|
658
|
+
if (sockets) noteFallback('Neither `ss` nor `netstat` is available here, so `lsof` was used instead.');
|
|
659
|
+
}
|
|
660
|
+
if (!sockets) {
|
|
661
|
+
sockets = await attemptProcNet();
|
|
662
|
+
if (sockets) {
|
|
663
|
+
noteFallback(
|
|
664
|
+
'No port tool is installed here, so the kernel’s own /proc/net tables were read directly. Process names are unavailable that way.'
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
if (!sockets) {
|
|
671
|
+
throw new Error(
|
|
672
|
+
platform === 'unknown'
|
|
673
|
+
? `Could not tell what operating system ${runner.label} runs, so no port probe could be chosen.`
|
|
674
|
+
: `Could not read the port table on ${runner.label}. Tried: ${tried.join(', ')}.`
|
|
675
|
+
);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
memo.probe = probe;
|
|
679
|
+
memo.argv = lastArgv;
|
|
680
|
+
memo.parse = lastParse;
|
|
681
|
+
// Kept so a remembered probe still reports the same caveats it earned.
|
|
682
|
+
memo.limitations = [...limitations];
|
|
683
|
+
|
|
684
|
+
if (platform !== 'win32' && ranWithoutOwners(sockets)) limitations.push(PIDS_NEED_ROOT);
|
|
685
|
+
|
|
686
|
+
return { sockets, limitations, probe };
|
|
687
|
+
}
|