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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
| | // SPDX-License-Identifier: GPL-2.0-or-later
/* PASST - Plug A Simple Socket Transport
* for qemu/UNIX domain socket mode
*
* PASTA - Pack A Subtle Tap Abstraction
* for network namespace/tap device mode
*
* PESTO - Programmable Extensible Socket Translation Orchestrator
* front-end for passt(1) and pasta(1) forwarding configuration
*
* ports.c - Parse port options
*
* Copyright (c) 2026 Red Hat GmbH
* Author: Stefano Brivio <sbrivio@redhat.com>
* Author: David Gibson <david@gibson.dropbear.id.au>
*/
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <string.h>
#include <sched.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include "lineread.h"
#include "common.h"
#include "ports.h"
#include "fwd_rule.h"
#include "log.h"
#include "pesto.h"
/* Ephemeral port range: values from RFC 6335 */
static in_port_t fwd_ephemeral_min = (1 << 15) + (1 << 14);
static in_port_t fwd_ephemeral_max = NUM_PORTS - 1;
#define PORT_RANGE_SYSCTL "/proc/sys/net/ipv4/ip_local_port_range"
/** fwd_probe_ephemeral() - Determine what ports this host considers ephemeral
*
* Work out what ports the host thinks are emphemeral and record it for later
* use by fwd_port_is_ephemeral(). If we're unable to probe, assume the range
* recommended by RFC 6335.
*/
void fwd_probe_ephemeral(void)
{
char *line, *tab, *end;
struct lineread lr;
long min, max;
ssize_t len;
int fd;
fd = open(PORT_RANGE_SYSCTL, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
warn_perror("Unable to open %s", PORT_RANGE_SYSCTL);
return;
}
lineread_init(&lr, fd);
len = lineread_get(&lr, &line);
close(fd);
if (len < 0)
goto parse_err;
tab = strchr(line, '\t');
if (!tab)
goto parse_err;
*tab = '\0';
errno = 0;
min = strtol(line, &end, 10);
if (*end || errno)
goto parse_err;
errno = 0;
max = strtol(tab + 1, &end, 10);
if (*end || errno)
goto parse_err;
if (min < 0 || min >= (long)NUM_PORTS ||
max < 0 || max >= (long)NUM_PORTS)
goto parse_err;
fwd_ephemeral_min = min;
fwd_ephemeral_max = max;
return;
parse_err:
warn("Unable to parse %s", PORT_RANGE_SYSCTL);
}
/**
* fwd_port_is_ephemeral() - Is port number ephemeral?
* @port: Port number
*
* Return: true if @port is ephemeral, that is may be allocated by the kernel as
* a local port for outgoing connections or datagrams, but should not be
* used for binding services to.
*/
bool fwd_port_is_ephemeral(in_port_t port)
{
return (port >= fwd_ephemeral_min) && (port <= fwd_ephemeral_max);
}
/**
* next_chunk() - Return the next piece of a string delimited by a character
* @s: String to search
* @c: Delimiter character
*
* Return: if another @c is found in @s, returns a pointer to the
* character *after* the delimiter, if no further @c is in @s,
* return NULL
*/
static char *next_chunk(const char *s, char c)
{
char *sep = strchr(s, c);
return sep ? sep + 1 : NULL;
}
/**
* port_range() - Represents a non-empty range of ports
* @first: First port number in the range
* @last: Last port number in the range (inclusive)
*
* Invariant: @last >= @first
*/
struct port_range {
in_port_t first, last;
};
/**
* parse_port_range() - Parse a range of port numbers '<first>[-<last>]'
* @s: String to parse
* @endptr: Update to the character after the parsed range (similar to
* strtol() etc.)
* @range: Update with the parsed values on success
*
* Return: -EINVAL on parsing error, -ERANGE on out of range port
* numbers, 0 on success
*/
static int parse_port_range(const char *s, char **endptr,
struct port_range *range)
{
unsigned long first, last;
last = first = strtoul(s, endptr, 10);
if (*endptr == s) /* Parsed nothing */
return -EINVAL;
if (**endptr == '-') { /* we have a last value too */
const char *lasts = *endptr + 1;
last = strtoul(lasts, endptr, 10);
if (*endptr == lasts) /* Parsed nothing */
return -EINVAL;
}
if ((last < first) || (last >= NUM_PORTS))
return -ERANGE;
range->first = first;
range->last = last;
return 0;
}
/**
* conf_ports_range_except() - Set up forwarding for a range of ports minus a
* bitmap of exclusions
* @optname: Short option name, t, T, u, or U
* @optarg: Option argument (port specification)
* @fwd: Forwarding table to be updated
* @addr: Listening address
* @ifname: Listening interface
* @first: First port to forward
* @last: Last port to forward
* @exclude: Bitmap of ports to exclude (may be NULL)
* @to: Port to translate @first to when forwarding
* @flags: Flags for forwarding entries
* @can_bindtodevice SO_BINDTODEVICE is available
* @v4_enabled IPv4 is enabled
* @v6_enabled IPv6 is enabled
*/
void conf_ports_range_except(char optname, const char *optarg,
struct fwd_table *fwd,
const union inany_addr *addr, const char *ifname,
uint16_t first, uint16_t last,
const uint8_t *exclude, uint16_t to, uint8_t flags,
bool can_bindtodevice,
bool v4_enabled, bool v6_enabled)
{
unsigned delta = to - first;
unsigned base, i;
uint8_t proto;
if (first == 0) {
die("Can't forward port 0 for option '-%c %s'",
optname, optarg);
}
if (optname == 't' || optname == 'T')
proto = IPPROTO_TCP;
else if (optname == 'u' || optname == 'U')
proto = IPPROTO_UDP;
else
assert(0);
if (addr) {
if (!v4_enabled && inany_v4(addr)) {
die("IPv4 is disabled, can't use -%c %s",
optname, optarg);
} else if (!v6_enabled && !inany_v4(addr)) {
die("IPv6 is disabled, can't use -%c %s",
optname, optarg);
}
}
for (base = first; base <= last; base++) {
if (exclude && bitmap_isset(exclude, base))
continue;
for (i = base; i <= last; i++) {
if (exclude && bitmap_isset(exclude, i))
break;
}
if ((optname == 'T' || optname == 'U') && !can_bindtodevice) {
/* FIXME: Once the fwd bitmaps are removed, move this
* workaround to the caller
*/
assert(!addr && ifname && !strcmp(ifname, "lo"));
warn(
"SO_BINDTODEVICE unavailable, forwarding only 127.0.0.1 and ::1 for '-%c %s'",
optname, optarg);
if (v4_enabled) {
fwd_rule_add(fwd, proto, flags,
&inany_loopback4, NULL,
base, i - 1, base + delta);
}
if (v6_enabled) {
fwd_rule_add(fwd, proto, flags,
&inany_loopback6, NULL,
base, i - 1, base + delta);
}
} else {
fwd_rule_add(fwd, proto, flags, addr, ifname,
base, i - 1, base + delta);
}
base = i - 1;
}
}
/**
* conf_ports() - Parse port configuration options, initialise UDP/TCP sockets
* @optname: Short option name, t, T, u, or U
* @optarg: Option argument (port specification)
* @fwd: Forwarding table to be updated
* @mode: Overall port forwarding mode (updated)
* @can_bindtodevice Whether SO_BINDTODEVICE is available
* @v4_enabled IPv4 is enabled
* @v6_enabled IPv6 is enabled
*/
void conf_ports(char optname, const char *optarg, struct fwd_table *fwd,
enum fwd_mode *mode, bool can_bindtodevice,
bool v4_enabled, bool v6_enabled)
{
union inany_addr addr_buf = inany_any6, *addr = &addr_buf;
char buf[BUFSIZ], *spec, *ifname = NULL, *p;
uint8_t exclude[PORT_BITMAP_SIZE] = { 0 };
bool exclude_only = true;
unsigned i;
if (!strcmp(optarg, "none")) {
if (*mode)
goto mode_conflict;
*mode = FWD_MODE_NONE;
return;
}
if (!strcmp(optarg, "auto")) {
if (*mode)
goto mode_conflict;
if ((optname == 'T' || optname == 'U') && can_bindtodevice) {
warn(
"'-%c auto' enabled without unprivileged SO_BINDTODEVICE", optname);
warn(
"Forwarding from addresses other than 127.0.0.1 will not work");
}
*mode = FWD_MODE_AUTO;
return;
}
if (!strcmp(optarg, "all")) {
if (*mode)
goto mode_conflict;
*mode = FWD_MODE_ALL;
/* Exclude ephemeral ports */
for (i = 0; i < NUM_PORTS; i++)
if (fwd_port_is_ephemeral(i))
bitmap_set(exclude, i);
conf_ports_range_except(optname, optarg, fwd, NULL, NULL,
1, NUM_PORTS - 1, exclude, 1, FWD_WEAK,
can_bindtodevice,
v4_enabled, v6_enabled);
return;
}
if (*mode > FWD_MODE_SPEC)
die("Specific ports cannot be specified together with all/none/auto");
*mode = FWD_MODE_SPEC;
strncpy(buf, optarg, sizeof(buf) - 1);
if ((spec = strchr(buf, '/'))) {
*spec = 0;
spec++;
if (optname != 't' && optname != 'u')
goto bad;
if ((ifname = strchr(buf, '%'))) {
*ifname = 0;
ifname++;
/* spec is already advanced one past the '/',
* so the length of the given ifname is:
* (spec - ifname - 1)
*/
if (spec - ifname - 1 >= IFNAMSIZ)
goto bad;
}
if (ifname == buf + 1) { /* Interface without address */
addr = NULL;
} else {
p = buf;
/* Allow square brackets for IPv4 too for convenience */
if (*p == '[' && p[strlen(p) - 1] == ']') {
p[strlen(p) - 1] = '\0';
p++;
}
if (!inany_pton(p, addr))
goto bad;
}
} else {
spec = buf;
addr = NULL;
}
/* Mark all exclusions first, they might be given after base ranges */
p = spec;
do {
struct port_range xrange;
if (*p != '~') {
/* Not an exclude range, parse later */
exclude_only = false;
continue;
}
p++;
if (parse_port_range(p, &p, &xrange))
goto bad;
if ((*p != '\0') && (*p != ',')) /* Garbage after the range */
goto bad;
for (i = xrange.first; i <= xrange.last; i++) {
if (bitmap_isset(exclude, i))
die("Overlapping excluded ranges %s", optarg);
bitmap_set(exclude, i);
}
} while ((p = next_chunk(p, ',')));
if (ifname && !can_bindtodevice) {
die(
"Device binding for '-%c %s' unsupported (requires kernel 5.7+)",
optname, optarg);
}
/* Outbound forwards come from guest loopback */
if ((optname == 'T' || optname == 'U') && !ifname)
ifname = "lo";
if (exclude_only) {
/* Exclude ephemeral ports */
for (i = 0; i < NUM_PORTS; i++)
if (fwd_port_is_ephemeral(i))
bitmap_set(exclude, i);
conf_ports_range_except(optname, optarg, fwd, addr, ifname,
1, NUM_PORTS - 1, exclude, 1, FWD_WEAK,
can_bindtodevice,
v4_enabled, v6_enabled);
return;
}
/* Now process base ranges, skipping exclusions */
p = spec;
do {
struct port_range orig_range, mapped_range;
if (*p == '~')
/* Exclude range, already parsed */
continue;
if (parse_port_range(p, &p, &orig_range))
goto bad;
if (*p == ':') { /* There's a range to map to as well */
if (parse_port_range(p + 1, &p, &mapped_range))
goto bad;
if ((mapped_range.last - mapped_range.first) !=
(orig_range.last - orig_range.first))
goto bad;
} else {
mapped_range = orig_range;
}
if ((*p != '\0') && (*p != ',')) /* Garbage after the ranges */
goto bad;
conf_ports_range_except(optname, optarg, fwd, addr, ifname,
orig_range.first, orig_range.last,
exclude, mapped_range.first, 0,
can_bindtodevice,
v4_enabled, v6_enabled);
} while ((p = next_chunk(p, ',')));
return;
bad:
die("Invalid port specifier %s", optarg);
mode_conflict:
die("Port forwarding mode '%s' conflicts with previous mode", optarg);
}
|