Debian Codegraph @

src/shared/firewall-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <endian.h>
4 #include <linux/netfilter/nf_tables.h>
5 #include <linux/netfilter_ipv4.h>
6 #include <netinet/ip.h>
7 #include <netinet/ip6.h>
8 #include <stdlib.h>
9 #include <string.h>
10
11 #include "sd-netlink.h"
12
13 #include "alloc-util.h"
14 #include "escape.h"
15 #include "extract-word.h"
16 #include "firewall-util.h"
17 #include "in-addr-util.h"
18 #include "log.h"
19 #include "netlink-internal.h"
20 #include "parse-util.h"
21 #include "socket-util.h"
22 #include "string-table.h"
23 #include "string-util.h"
24 #include "time-util.h"
25
26 #define NFT_SYSTEMD_DNAT_MAP_NAME "map_port_ipport"
27 #define NFT_SYSTEMD_TABLE_NAME "io.systemd.nat"
28 #define NFT_SYSTEMD_MASQ_SET_NAME "masq_saddr"
29
30 #define NFNL_DEFAULT_TIMEOUT_USECS (1ULL * USEC_PER_SEC)
31
32 #define UDP_DPORT_OFFSET 2
33
34 /* for test-firewall-util */
35 static const char* nft_table_name(void) {
36 static const char *cached = NULL;
37
38 if (!cached)
39 cached = secure_getenv("SYSTEMD_FIREWALL_UTIL_NFT_TABLE_NAME") ?: NFT_SYSTEMD_TABLE_NAME;
40
41 return cached;
42 }
43
44 static const char* dnat_map_name(void) {
45 static const char *cached = NULL;
46
47 if (!cached)
48 cached = secure_getenv("SYSTEMD_FIREWALL_UTIL_DNAT_MAP_NAME") ?: NFT_SYSTEMD_DNAT_MAP_NAME;
49
50 return cached;
51 }
52
53 static DEFINE_POINTER_ARRAY_CLEAR_FUNC(sd_netlink_message*, sd_netlink_message_unref);
54
55 static int nfnl_open_expr_container(sd_netlink_message *m, const char *name) {
56 int r;
57
58 assert(m);
59 assert(name);
60
61 r = sd_netlink_message_open_array(m, NFTA_LIST_ELEM);
62 if (r < 0)
63 return r;
64
65 return sd_netlink_message_open_container_union(m, NFTA_EXPR_DATA, name);
66 }
67
68 static int nfnl_close_expr_container(sd_netlink_message *m) {
69 int r;
70
71 assert(m);
72
73 r = sd_netlink_message_close_container(m); /* NFTA_EXPR_DATA */
74 if (r < 0)
75 return r;
76
77 return sd_netlink_message_close_container(m); /* NFTA_LIST_ELEM */
78 }
79
80 static int nfnl_add_expr_fib(
81 sd_netlink_message *m,
82 uint32_t nft_fib_flags,
83 enum nft_fib_result result,
84 enum nft_registers dreg) {
85
86 int r;
87
88 assert(m);
89
90 r = nfnl_open_expr_container(m, "fib");
91 if (r < 0)
92 return r;
93
94 r = sd_netlink_message_append_u32(m, NFTA_FIB_FLAGS, htobe32(nft_fib_flags));
95 if (r < 0)
96 return r;
97
98 r = sd_netlink_message_append_u32(m, NFTA_FIB_RESULT, htobe32(result));
99 if (r < 0)
100 return r;
101
102 r = sd_netlink_message_append_u32(m, NFTA_FIB_DREG, htobe32(dreg));
103 if (r < 0)
104 return r;
105
106 return nfnl_close_expr_container(m);
107 }
108
109 static int nfnl_add_expr_meta(
110 sd_netlink_message *m,
111 enum nft_meta_keys key,
112 enum nft_registers dreg) {
113
114 int r;
115
116 assert(m);
117
118 r = nfnl_open_expr_container(m, "meta");
119 if (r < 0)
120 return r;
121
122 r = sd_netlink_message_append_u32(m, NFTA_META_KEY, htobe32(key));
123 if (r < 0)
124 return r;
125
126 r = sd_netlink_message_append_u32(m, NFTA_META_DREG, htobe32(dreg));
127 if (r < 0)
128 return r;
129
130 return nfnl_close_expr_container(m);
131 }
132
133 static int nfnl_add_expr_payload(
134 sd_netlink_message *m,
135 enum nft_payload_bases pb,
136 uint32_t offset,
137 uint32_t len,
138 enum nft_registers dreg) {
139
140 int r;
141
142 assert(m);
143
144 r = nfnl_open_expr_container(m, "payload");
145 if (r < 0)
146 return r;
147
148 r = sd_netlink_message_append_u32(m, NFTA_PAYLOAD_DREG, htobe32(dreg));
149 if (r < 0)
150 return r;
151
152 r = sd_netlink_message_append_u32(m, NFTA_PAYLOAD_BASE, htobe32(pb));
153 if (r < 0)
154 return r;
155
156 r = sd_netlink_message_append_u32(m, NFTA_PAYLOAD_OFFSET, htobe32(offset));
157 if (r < 0)
158 return r;
159
160 r = sd_netlink_message_append_u32(m, NFTA_PAYLOAD_LEN, htobe32(len));
161 if (r < 0)
162 return r;
163
164 return nfnl_close_expr_container(m);
165 }
166
167 static int nfnl_add_expr_lookup(
168 sd_netlink_message *m,
169 const char *set_name,
170 enum nft_registers sreg,
171 enum nft_registers dreg) {
172
173 int r;
174
175 assert(m);
176 assert(set_name);
177
178 r = nfnl_open_expr_container(m, "lookup");
179 if (r < 0)
180 return r;
181
182 r = sd_netlink_message_append_string(m, NFTA_LOOKUP_SET, set_name);
183 if (r < 0)
184 return r;
185
186 r = sd_netlink_message_append_u32(m, NFTA_LOOKUP_SREG, htobe32(sreg));
187 if (r < 0)
188 return r;
189
190 if (dreg != 0) {
191 r = sd_netlink_message_append_u32(m, NFTA_LOOKUP_DREG, htobe32(dreg));
192 if (r < 0)
193 return r;
194 }
195
196 return nfnl_close_expr_container(m);
197 }
198
199 static int nfnl_add_expr_cmp(
200 sd_netlink_message *m,
201 enum nft_cmp_ops cmp_op,
202 enum nft_registers sreg,
203 const void *data,
204 size_t dlen) {
205
206 int r;
207
208 assert(m);
209 assert(data);
210
211 r = nfnl_open_expr_container(m, "cmp");
212 if (r < 0)
213 return r;
214
215 r = sd_netlink_message_append_u32(m, NFTA_CMP_OP, htobe32(cmp_op));
216 if (r < 0)
217 return r;
218
219 r = sd_netlink_message_append_u32(m, NFTA_CMP_SREG, htobe32(sreg));
220 if (r < 0)
221 return r;
222
223 r = sd_netlink_message_append_container_data(m, NFTA_CMP_DATA, NFTA_DATA_VALUE, data, dlen);
224 if (r < 0)
225 return r;
226
227 return nfnl_close_expr_container(m);
228 }
229
230 static int nfnl_add_expr_bitwise(
231 sd_netlink_message *m,
232 enum nft_registers sreg,
233 enum nft_registers dreg,
234 const void *and,
235 const void *xor,
236 uint32_t len) {
237
238 int r;
239
240 assert(m);
241 assert(and);
242 assert(xor);
243
244 r = nfnl_open_expr_container(m, "bitwise");
245 if (r < 0)
246 return r;
247
248 r = sd_netlink_message_append_u32(m, NFTA_BITWISE_SREG, htobe32(sreg));
249 if (r < 0)
250 return r;
251
252 r = sd_netlink_message_append_u32(m, NFTA_BITWISE_DREG, htobe32(dreg));
253 if (r < 0)
254 return r;
255
256 r = sd_netlink_message_append_u32(m, NFTA_BITWISE_LEN, htobe32(len));
257 if (r < 0)
258 return r;
259
260 r = sd_netlink_message_append_container_data(m, NFTA_BITWISE_MASK, NFTA_DATA_VALUE, and, len);
261 if (r < 0)
262 return r;
263
264 r = sd_netlink_message_append_container_data(m, NFTA_BITWISE_XOR, NFTA_DATA_VALUE, xor, len);
265 if (r < 0)
266 return r;
267
268 return nfnl_close_expr_container(m);
269 }
270
271 static int nfnl_add_expr_dnat(
272 sd_netlink_message *m,
273 int family,
274 enum nft_registers areg,
275 enum nft_registers preg) {
276
277 int r;
278
279 assert(m);
280
281 r = nfnl_open_expr_container(m, "nat");
282 if (r < 0)
283 return r;
284
285 r = sd_netlink_message_append_u32(m, NFTA_NAT_TYPE, htobe32(NFT_NAT_DNAT));
286 if (r < 0)
287 return r;
288
289 r = sd_netlink_message_append_u32(m, NFTA_NAT_FAMILY, htobe32(family));
290 if (r < 0)
291 return r;
292
293 r = sd_netlink_message_append_u32(m, NFTA_NAT_REG_ADDR_MIN, htobe32(areg));
294 if (r < 0)
295 return r;
296
297 r = sd_netlink_message_append_u32(m, NFTA_NAT_REG_PROTO_MIN, htobe32(preg));
298 if (r < 0)
299 return r;
300
301 return nfnl_close_expr_container(m);
302 }
303
304 static int nfnl_add_expr_masq(sd_netlink_message *m) {
305 int r;
306
307 r = sd_netlink_message_open_array(m, NFTA_LIST_ELEM);
308 if (r < 0)
309 return r;
310
311 r = sd_netlink_message_append_string(m, NFTA_EXPR_NAME, "masq");
312 if (r < 0)
313 return r;
314
315 return sd_netlink_message_close_container(m); /* NFTA_LIST_ELEM */
316 }
317
318 static int sd_nfnl_message_new_masq_rule(
319 sd_netlink *nfnl,
320 sd_netlink_message **ret,
321 int family,
322 const char *chain) {
323
324 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
325 int r;
326
327 /* -t nat -A POSTROUTING -p protocol -s source/pflen -o out_interface -d destination/pflen -j MASQUERADE */
328
329 assert(nfnl);
330 assert(ret);
331 assert(IN_SET(family, AF_INET, AF_INET6));
332 assert(chain);
333
334 r = sd_nfnl_nft_message_new_rule(nfnl, &m, family, nft_table_name(), chain);
335 if (r < 0)
336 return r;
337
338 r = sd_netlink_message_open_container(m, NFTA_RULE_EXPRESSIONS);
339 if (r < 0)
340 return r;
341
342 /* 1st statement: ip saddr @masq_saddr. Place iph->saddr in reg1, resp. ipv6 in reg1..reg4. */
343 if (family == AF_INET)
344 r = nfnl_add_expr_payload(m, NFT_PAYLOAD_NETWORK_HEADER, offsetof(struct iphdr, saddr),
345 sizeof(uint32_t), NFT_REG32_01);
346 else
347 r = nfnl_add_expr_payload(m, NFT_PAYLOAD_NETWORK_HEADER, offsetof(struct ip6_hdr, ip6_src.s6_addr),
348 sizeof(struct in6_addr), NFT_REG32_01);
349 if (r < 0)
350 return r;
351
352 /* 1st statement: use reg1 content to make lookup in @masq_saddr set. */
353 r = nfnl_add_expr_lookup(m, NFT_SYSTEMD_MASQ_SET_NAME, NFT_REG32_01, 0);
354 if (r < 0)
355 return r;
356
357 /* 2nd statement: masq. Only executed by kernel if the previous lookup was successful. */
358 r = nfnl_add_expr_masq(m);
359 if (r < 0)
360 return r;
361
362 r = sd_netlink_message_close_container(m); /* NFTA_RULE_EXPRESSIONS */
363 if (r < 0)
364 return r;
365
366 *ret = TAKE_PTR(m);
367 return 0;
368 }
369
370 static int sd_nfnl_message_new_dnat_rule_pre(
371 sd_netlink *nfnl,
372 sd_netlink_message **ret,
373 int family,
374 const char *chain) {
375
376 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
377 enum nft_registers proto_reg;
378 uint32_t local = RTN_LOCAL;
379 int r;
380
381 /* -t nat -A PREROUTING -p protocol --dport local_port -i in_interface -s source/pflen
382 * -d destination/pflen -j DNAT --to-destination remote_addr:remote_port */
383
384 assert(nfnl);
385 assert(ret);
386 assert(IN_SET(family, AF_INET, AF_INET6));
387 assert(chain);
388
389 r = sd_nfnl_nft_message_new_rule(nfnl, &m, family, nft_table_name(), chain);
390 if (r < 0)
391 return r;
392
393 r = sd_netlink_message_open_container(m, NFTA_RULE_EXPRESSIONS);
394 if (r < 0)
395 return r;
396
397 /* 1st statement: fib daddr type local */
398 r = nfnl_add_expr_fib(m, NFTA_FIB_F_DADDR, NFT_FIB_RESULT_ADDRTYPE, NFT_REG32_01);
399 if (r < 0)
400 return r;
401
402 /* 1st statement (cont.): compare RTN_LOCAL */
403 r = nfnl_add_expr_cmp(m, NFT_CMP_EQ, NFT_REG32_01, &local, sizeof(local));
404 if (r < 0)
405 return r;
406
407 /* 2nd statement: lookup local port in map, fetch address:dport to map to */
408 r = nfnl_add_expr_meta(m, NFT_META_L4PROTO, NFT_REG32_01);
409 if (r < 0)
410 return r;
411
412 r = nfnl_add_expr_payload(m, NFT_PAYLOAD_TRANSPORT_HEADER, UDP_DPORT_OFFSET,
413 sizeof(uint16_t), NFT_REG32_02);
414 if (r < 0)
415 return r;
416
417 /* 3rd statement: lookup 'l4proto . dport', e.g. 'tcp . 22' as key and
418 * store address and port for the dnat mapping in REG1/REG2. */
419 r = nfnl_add_expr_lookup(m, dnat_map_name(), NFT_REG32_01, NFT_REG32_01);
420 if (r < 0)
421 return r;
422
423 proto_reg = family == AF_INET ? NFT_REG32_02 : NFT_REG32_05;
424 r = nfnl_add_expr_dnat(m, family, NFT_REG32_01, proto_reg);
425 if (r < 0)
426 return r;
427
428 r = sd_netlink_message_close_container(m); /* NFTA_RULE_EXPRESSIONS */
429 if (r < 0)
430 return r;
431
432 *ret = TAKE_PTR(m);
433 return 0;
434 }
435
436 static int sd_nfnl_message_new_dnat_rule_out(
437 sd_netlink *nfnl,
438 sd_netlink_message **ret,
439 int family,
440 const char *chain) {
441
442 static const uint32_t zero = 0, one = 1;
443 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
444 enum nft_registers proto_reg;
445 int r;
446
447 assert(nfnl);
448 assert(ret);
449 assert(IN_SET(family, AF_INET, AF_INET6));
450 assert(chain);
451
452 r = sd_nfnl_nft_message_new_rule(nfnl, &m, family, nft_table_name(), chain);
453 if (r < 0)
454 return r;
455
456 r = sd_netlink_message_open_container(m, NFTA_RULE_EXPRESSIONS);
457 if (r < 0)
458 return r;
459
460 /* 1st statement: exclude 127.0.0.1/8: ip daddr != 127.0.0.1/8, resp. avoid ::1 */
461 if (family == AF_INET) {
462 uint32_t lonet = htobe32(UINT32_C(0x7F000000)), lomask = htobe32(UINT32_C(0xff000000));
463
464 r = nfnl_add_expr_payload(m, NFT_PAYLOAD_NETWORK_HEADER, offsetof(struct iphdr, daddr),
465 sizeof(lonet), NFT_REG32_01);
466 if (r < 0)
467 return r;
468 /* 1st statement (cont.): bitops/prefix */
469 r = nfnl_add_expr_bitwise(m, NFT_REG32_01, NFT_REG32_01, &lomask, &zero, sizeof(lomask));
470 if (r < 0)
471 return r;
472
473 /* 1st statement (cont.): compare reg1 with 127/8 */
474 r = nfnl_add_expr_cmp(m, NFT_CMP_NEQ, NFT_REG32_01, &lonet, sizeof(lonet));
475 } else {
476 struct in6_addr loaddr = IN6ADDR_LOOPBACK_INIT;
477
478 r = nfnl_add_expr_payload(m, NFT_PAYLOAD_NETWORK_HEADER, offsetof(struct ip6_hdr, ip6_dst.s6_addr),
479 sizeof(loaddr), NFT_REG32_01);
480 if (r < 0)
481 return r;
482
483 r = nfnl_add_expr_cmp(m, NFT_CMP_NEQ, NFT_REG32_01, &loaddr, sizeof(loaddr));
484 }
485 if (r < 0)
486 return r;
487
488 /* 2nd statement: meta oif lo */
489 r = nfnl_add_expr_meta(m, NFT_META_OIF, NFT_REG32_01);
490 if (r < 0)
491 return r;
492
493 /* 2nd statement (cont.): compare to lo ifindex (1) */
494 r = nfnl_add_expr_cmp(m, NFT_CMP_EQ, NFT_REG32_01, &one, sizeof(one));
495 if (r < 0)
496 return r;
497
498 /* 3rd statement: meta l4proto . th dport dnat ip . port to map @map_port_ipport */
499 r = nfnl_add_expr_meta(m, NFT_META_L4PROTO, NFT_REG32_01);
500 if (r < 0)
501 return r;
502
503 /* 3rd statement (cont): store the port number in reg2 */
504 r = nfnl_add_expr_payload(m, NFT_PAYLOAD_TRANSPORT_HEADER, UDP_DPORT_OFFSET,
505 sizeof(uint16_t), NFT_REG32_02);
506 if (r < 0)
507 return r;
508
509 /* 3rd statement (cont): use reg1 and reg2 and retrieve
510 * the new destination ip and port number.
511 *
512 * reg1 and reg2 are clobbered and will then contain the new
513 * address/port number. */
514 r = nfnl_add_expr_lookup(m, dnat_map_name(), NFT_REG32_01, NFT_REG32_01);
515 if (r < 0)
516 return r;
517
518 /* 4th statement: dnat connection to address/port retrieved by the
519 * preceding expression. */
520 proto_reg = family == AF_INET ? NFT_REG32_02 : NFT_REG32_05;
521 r = nfnl_add_expr_dnat(m, family, NFT_REG32_01, proto_reg);
522 if (r < 0)
523 return r;
524
525 r = sd_netlink_message_close_container(m); /* NFTA_RULE_EXPRESSIONS */
526 if (r < 0)
527 return r;
528
529 *ret = TAKE_PTR(m);
530 return 0;
531 }
532
533 static int nft_new_set(
534 struct sd_netlink *nfnl,
535 sd_netlink_message **ret,
536 int family,
537 const char *set_name,
538 uint32_t set_id,
539 uint32_t flags,
540 uint32_t type,
541 uint32_t klen) {
542
543 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
544 int r;
545
546 assert(nfnl);
547 assert(ret);
548 assert(IN_SET(family, AF_INET, AF_INET6));
549 assert(set_name);
550
551 r = sd_nfnl_nft_message_new_set(nfnl, &m, family, nft_table_name(), set_name, set_id, klen);
552 if (r < 0)
553 return r;
554
555 if (flags != 0) {
556 r = sd_netlink_message_append_u32(m, NFTA_SET_FLAGS, htobe32(flags));
557 if (r < 0)
558 return r;
559 }
560
561 r = sd_netlink_message_append_u32(m, NFTA_SET_KEY_TYPE, htobe32(type));
562 if (r < 0)
563 return r;
564
565 *ret = TAKE_PTR(m);
566 return r;
567 }
568
569 static int nft_new_map(
570 struct sd_netlink *nfnl,
571 sd_netlink_message **ret,
572 int family,
573 const char *set_name,
574 uint32_t set_id,
575 uint32_t flags,
576 uint32_t type,
577 uint32_t klen,
578 uint32_t dtype,
579 uint32_t dlen) {
580
581 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
582 int r;
583
584 assert(nfnl);
585 assert(ret);
586 assert(IN_SET(family, AF_INET, AF_INET6));
587 assert(set_name);
588
589 r = nft_new_set(nfnl, &m, family, set_name, set_id, flags | NFT_SET_MAP, type, klen);
590 if (r < 0)
591 return r;
592
593 r = sd_netlink_message_append_u32(m, NFTA_SET_DATA_TYPE, htobe32(dtype));
594 if (r < 0)
595 return r;
596
597 r = sd_netlink_message_append_u32(m, NFTA_SET_DATA_LEN, htobe32(dlen));
598 if (r < 0)
599 return r;
600
601 *ret = TAKE_PTR(m);
602 return 0;
603 }
604
605 static int nft_add_element(
606 sd_netlink *nfnl,
607 sd_netlink_message **ret,
608 int nfproto,
609 const char *table_name,
610 const char *set_name,
611 const void *key,
612 uint32_t klen,
613 const void *data,
614 uint32_t dlen) {
615
616 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
617 int r;
618
619 assert(nfnl);
620 assert(ret);
621 assert(nfproto_is_valid(nfproto));
622 assert(table_name);
623 assert(set_name);
624 assert(key);
625 assert(data || dlen == 0);
626
627 /*
628 * Ideally there would be an API that provides:
629 *
630 * 1) an init function to add the main ruleset skeleton
631 * 2) a function that populates the sets with all known address/port pairs to s/dnat for
632 * 3) a function that can remove address/port pairs again.
633 *
634 * At this time, the existing API is used which is built on a
635 * 'add/delete a rule' paradigm.
636 *
637 * This replicated here and each element gets added to the set
638 * one-by-one.
639 */
640 r = sd_nfnl_nft_message_new_setelems(nfnl, &m, /* add= */ true, nfproto, table_name, set_name);
641 if (r < 0)
642 return r;
643
644 r = sd_netlink_message_open_container(m, NFTA_SET_ELEM_LIST_ELEMENTS);
645 if (r < 0)
646 return r;
647
648 r = sd_nfnl_nft_message_append_setelem(m, 0, key, klen, data, dlen, 0);
649 if (r < 0)
650 return r;
651
652 /* could theoretically append more set elements to add here */
653
654 r = sd_netlink_message_close_container(m); /* NFTA_SET_ELEM_LIST_ELEMENTS */
655 if (r < 0)
656 return r;
657
658 *ret = TAKE_PTR(m);
659 return 0;
660 }
661
662 static int nft_del_element(
663 sd_netlink *nfnl,
664 sd_netlink_message **ret,
665 int nfproto,
666 const char *table_name,
667 const char *set_name,
668 const void *key,
669 uint32_t klen,
670 const void *data,
671 uint32_t dlen) {
672
673 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
674 int r;
675
676 assert(nfnl);
677 assert(ret);
678 assert(nfproto_is_valid(nfproto));
679 assert(table_name);
680 assert(set_name);
681 assert(key);
682 assert(data || dlen == 0);
683
684 r = sd_nfnl_nft_message_new_setelems(nfnl, &m, /* add= */ false, nfproto, table_name, set_name);
685 if (r < 0)
686 return r;
687
688 r = sd_netlink_message_open_container(m, NFTA_SET_ELEM_LIST_ELEMENTS);
689 if (r < 0)
690 return r;
691
692 r = sd_nfnl_nft_message_append_setelem(m, 0, key, klen, data, dlen, 0);
693 if (r < 0)
694 return r;
695
696 r = sd_netlink_message_close_container(m); /* NFTA_SET_ELEM_LIST_ELEMENTS */
697 if (r < 0)
698 return r;
699
700 *ret = TAKE_PTR(m);
701 return 0;
702 }
703
704 /* This is needed so 'nft' userspace tool can properly format the contents
705 * of the set/map when someone uses 'nft' to inspect their content.
706 *
707 * The values cannot be changed, they are part of the nft tool type identifier ABI. */
708 #define TYPE_BITS 6
709
710 enum nft_key_types {
711 TYPE_IPADDR = 7,
712 TYPE_IP6ADDR = 8,
713 TYPE_INET_PROTOCOL = 12,
714 TYPE_INET_SERVICE = 13,
715 };
716
717 static uint32_t concat_types2(enum nft_key_types a, enum nft_key_types b) {
718 uint32_t type = (uint32_t)a;
719
720 type <<= TYPE_BITS;
721 type |= (uint32_t)b;
722
723 return type;
724 }
725
726 static int fw_nftables_init_family(sd_netlink *nfnl, int family) {
727 sd_netlink_message *messages[10] = {};
728 CLEANUP_ELEMENTS(messages, sd_netlink_message_unref_array_clear);
729 size_t msgcnt = 0, ip_type_size;
730 uint32_t set_id = 0;
731 int ip_type, r;
732
733 assert(nfnl);
734 assert(IN_SET(family, AF_INET, AF_INET6));
735
736 /* Set F_EXCL so table add fails if the table already exists. */
737 r = sd_nfnl_nft_message_new_table(nfnl, &messages[msgcnt++], family, nft_table_name());
738 if (r < 0)
739 return r;
740
741 r = sd_nfnl_nft_message_new_basechain(nfnl, &messages[msgcnt++], family, nft_table_name(),
742 "prerouting", "nat",
743 NF_INET_PRE_ROUTING, NF_IP_PRI_NAT_DST + 1);
744 if (r < 0)
745 return r;
746
747 r = sd_nfnl_nft_message_new_basechain(nfnl, &messages[msgcnt++], family, nft_table_name(),
748 "output", "nat",
749 NF_INET_LOCAL_OUT, NF_IP_PRI_NAT_DST + 1);
750 if (r < 0)
751 return r;
752
753 r = sd_nfnl_nft_message_new_basechain(nfnl, &messages[msgcnt++], family, nft_table_name(),
754 "postrouting", "nat",
755 NF_INET_POST_ROUTING, NF_IP_PRI_NAT_SRC + 1);
756 if (r < 0)
757 return r;
758
759 if (family == AF_INET) {
760 ip_type_size = sizeof(uint32_t);
761 ip_type = TYPE_IPADDR;
762 } else {
763 assert(family == AF_INET6);
764 ip_type_size = sizeof(struct in6_addr);
765 ip_type = TYPE_IP6ADDR;
766 }
767 /* set to store ip address ranges we should masquerade for */
768 r = nft_new_set(nfnl, &messages[msgcnt++], family, NFT_SYSTEMD_MASQ_SET_NAME, ++set_id, NFT_SET_INTERVAL, ip_type, ip_type_size);
769 if (r < 0)
770 return r;
771
772 /*
773 * map to store ip address:port pair to dnat to. elements in concatenation
774 * are rounded up to 4 bytes.
775 *
776 * Example: ip protocol . tcp daddr is sizeof(uint32_t) + sizeof(uint32_t), not
777 * sizeof(uint8_t) + sizeof(uint16_t).
778 */
779 r = nft_new_map(nfnl, &messages[msgcnt++], family, dnat_map_name(), ++set_id, 0,
780 concat_types2(TYPE_INET_PROTOCOL, TYPE_INET_SERVICE), sizeof(uint32_t) * 2,
781 concat_types2(ip_type, TYPE_INET_SERVICE), ip_type_size + sizeof(uint32_t));
782 if (r < 0)
783 return r;
784
785 r = sd_nfnl_message_new_dnat_rule_pre(nfnl, &messages[msgcnt++], family, "prerouting");
786 if (r < 0)
787 return r;
788
789 r = sd_nfnl_message_new_dnat_rule_out(nfnl, &messages[msgcnt++], family, "output");
790 if (r < 0)
791 return r;
792
793 r = sd_nfnl_message_new_masq_rule(nfnl, &messages[msgcnt++], family, "postrouting");
794 if (r < 0)
795 return r;
796
797 assert(msgcnt < ELEMENTSOF(messages));
798 r = sd_nfnl_call_batch(nfnl, messages, msgcnt, NFNL_DEFAULT_TIMEOUT_USECS);
799 if (r < 0 && r != -EEXIST)
800 return r;
801
802 return 0;
803 }
804
805 static int nft_message_append_setelem_iprange(
806 sd_netlink_message *m,
807 const union in_addr_union *source,
808 unsigned prefixlen) {
809
810 uint32_t mask, start, end;
811 unsigned nplen;
812 int r;
813
814 assert(m);
815 assert(source);
816 assert(prefixlen <= 32);
817
818 nplen = 32 - prefixlen;
819
820 mask = (1U << nplen) - 1U;
821 mask = htobe32(~mask);
822 start = source->in.s_addr & mask;
823
824 r = sd_netlink_message_open_container(m, NFTA_SET_ELEM_LIST_ELEMENTS);
825 if (r < 0)
826 return r;
827
828 r = sd_nfnl_nft_message_append_setelem(m, 0, &start, sizeof(start), NULL, 0, 0);
829 if (r < 0)
830 return r;
831
832 end = be32toh(start) + (1U << nplen);
833 if (end < be32toh(start))
834 end = 0U;
835 end = htobe32(end);
836
837 r = sd_nfnl_nft_message_append_setelem(m, 1, &end, sizeof(end), NULL, 0, NFT_SET_ELEM_INTERVAL_END);
838 if (r < 0)
839 return r;
840
841 return sd_netlink_message_close_container(m); /* NFTA_SET_ELEM_LIST_ELEMENTS */
842 }
843
844 static int nft_message_append_setelem_ip6range(
845 sd_netlink_message *m,
846 const union in_addr_union *source,
847 unsigned prefixlen) {
848
849 union in_addr_union start, end;
850 int r;
851
852 assert(m);
853 assert(source);
854
855 r = in_addr_prefix_range(AF_INET6, source, prefixlen, &start, &end);
856 if (r < 0)
857 return r;
858
859 r = sd_netlink_message_open_container(m, NFTA_SET_ELEM_LIST_ELEMENTS);
860 if (r < 0)
861 return r;
862
863 r = sd_nfnl_nft_message_append_setelem(m, 0, &start.in6, sizeof(start.in6), NULL, 0, 0);
864 if (r < 0)
865 return r;
866
867 r = sd_nfnl_nft_message_append_setelem(m, 1, &end.in6, sizeof(end.in6), NULL, 0, NFT_SET_ELEM_INTERVAL_END);
868 if (r < 0)
869 return r;
870
871 return sd_netlink_message_close_container(m); /* NFTA_SET_ELEM_LIST_ELEMENTS */
872 }
873
874 int nft_set_element_modify_iprange(
875 sd_netlink *nfnl,
876 bool add,
877 int nfproto,
878 int af,
879 const char *table,
880 const char *set,
881 const union in_addr_union *source,
882 unsigned source_prefixlen) {
883
884 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
885 int r;
886
887 assert(nfnl);
888 assert(IN_SET(af, AF_INET, AF_INET6));
889 assert(nfproto_is_valid(nfproto));
890 assert(table);
891 assert(set);
892
893 if (!source || source_prefixlen == 0)
894 return -EINVAL;
895
896 if (af == AF_INET6 && source_prefixlen < 8)
897 return -EINVAL;
898
899 r = sd_nfnl_nft_message_new_setelems(nfnl, &m, add, nfproto, table, set);
900 if (r < 0)
901 return r;
902
903 if (af == AF_INET)
904 r = nft_message_append_setelem_iprange(m, source, source_prefixlen);
905 else
906 r = nft_message_append_setelem_ip6range(m, source, source_prefixlen);
907 if (r < 0)
908 return r;
909
910 return sd_nfnl_call_batch(nfnl, &m, 1, NFNL_DEFAULT_TIMEOUT_USECS);
911 }
912
913 int nft_set_element_modify_ip(
914 sd_netlink *nfnl,
915 bool add,
916 int nfproto,
917 int af,
918 const char *table,
919 const char *set,
920 const union in_addr_union *source) {
921
922 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
923 int r;
924
925 assert(nfnl);
926 assert(IN_SET(af, AF_INET, AF_INET6));
927 assert(nfproto_is_valid(nfproto));
928 assert(table);
929 assert(set);
930
931 if (!source)
932 return -EINVAL;
933
934 r = sd_nfnl_nft_message_new_setelems(nfnl, &m, add, nfproto, table, set);
935 if (r < 0)
936 return r;
937
938 r = sd_netlink_message_open_container(m, NFTA_SET_ELEM_LIST_ELEMENTS);
939 if (r < 0)
940 return r;
941
942 r = sd_nfnl_nft_message_append_setelem(m, 0, source, FAMILY_ADDRESS_SIZE(af), NULL, 0, 0);
943 if (r < 0)
944 return r;
945
946 r = sd_netlink_message_close_container(m); /* NFTA_SET_ELEM_LIST_ELEMENTS */
947 if (r < 0)
948 return r;
949
950 return sd_nfnl_call_batch(nfnl, &m, 1, NFNL_DEFAULT_TIMEOUT_USECS);
951 }
952
953 int nft_set_element_modify_any(
954 sd_netlink *nfnl,
955 bool add,
956 int nfproto,
957 const char *table,
958 const char *set,
959 const void *element,
960 size_t element_size) {
961
962 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
963 int r;
964
965 assert(nfnl);
966 assert(nfproto_is_valid(nfproto));
967 assert(table);
968 assert(set);
969 assert(element);
970
971 if (add)
972 r = nft_add_element(nfnl, &m, nfproto, table, set, element, element_size, NULL, 0);
973 else
974 r = nft_del_element(nfnl, &m, nfproto, table, set, element, element_size, NULL, 0);
975 if (r < 0)
976 return r;
977
978 return sd_nfnl_call_batch(nfnl, &m, 1, NFNL_DEFAULT_TIMEOUT_USECS);
979 }
980
981 static int af_to_nfproto(int af) {
982 assert(IN_SET(af, AF_INET, AF_INET6));
983
984 switch (af) {
985 case AF_INET:
986 return NFPROTO_IPV4;
987 case AF_INET6:
988 return NFPROTO_IPV6;
989 default:
990 assert_not_reached();
991 }
992 }
993
994 int fw_nftables_add_masquerade(
995 sd_netlink *nfnl,
996 bool add,
997 int af,
998 const union in_addr_union *source,
999 unsigned source_prefixlen) {
1000
1001 int r;
1002
1003 assert(nfnl);
1004 assert(IN_SET(af, AF_INET, AF_INET6));
1005
1006 if (!socket_ipv6_is_supported() && af == AF_INET6)
1007 return -EOPNOTSUPP;
1008
1009 r = nft_set_element_modify_iprange(nfnl, add, af_to_nfproto(af), af, nft_table_name(), NFT_SYSTEMD_MASQ_SET_NAME,
1010 source, source_prefixlen);
1011 if (r != -ENOENT)
1012 return r;
1013
1014 /* When someone runs 'nft flush ruleset' in the same net namespace this will also tear down the
1015 * systemd nat table.
1016 *
1017 * Unlike iptables -t nat -F (which will remove all rules added by the systemd iptables
1018 * backend, iptables has builtin chains that cannot be deleted -- the next add operation will
1019 * 'just work'.
1020 *
1021 * In the nftables case, everything gets removed. The next add operation will yield -ENOENT.
1022 *
1023 * If we see -ENOENT on add, replay the initial table setup. If that works, re-do the add
1024 * operation.
1025 *
1026 * Note that this doesn't protect against external sabotage such as a
1027 * 'while true; nft flush ruleset; done'. There is nothing that could be done about that short
1028 * of extending the kernel to allow tables to be owned by stystemd-networkd and making them
1029 * non-deletable except by the 'owning process'. */
1030
1031 r = fw_nftables_init_family(nfnl, af);
1032 if (r < 0)
1033 return r;
1034
1035 return nft_set_element_modify_iprange(nfnl, add, af_to_nfproto(af), af, nft_table_name(), NFT_SYSTEMD_MASQ_SET_NAME,
1036 source, source_prefixlen);
1037 }
1038
1039 static int fw_nftables_add_local_dnat_internal(
1040 sd_netlink *nfnl,
1041 bool add,
1042 int af,
1043 int protocol,
1044 uint16_t local_port,
1045 const union in_addr_union *remote,
1046 uint16_t remote_port,
1047 const union in_addr_union *previous_remote) {
1048
1049 sd_netlink_message *messages[3] = {};
1050 CLEANUP_ELEMENTS(messages, sd_netlink_message_unref_array_clear);
1051 uint32_t data[5], key[2], dlen;
1052 size_t msgcnt = 0;
1053 int r;
1054
1055 assert(nfnl);
1056 assert(add || !previous_remote);
1057 assert(IN_SET(af, AF_INET, AF_INET6));
1058
1059 if (!IN_SET(protocol, IPPROTO_TCP, IPPROTO_UDP))
1060 return -EPROTONOSUPPORT;
1061
1062 if (local_port <= 0)
1063 return -EINVAL;
1064
1065 key[0] = protocol;
1066 key[1] = htobe16(local_port);
1067
1068 if (!remote)
1069 return -EOPNOTSUPP;
1070
1071 if (remote_port <= 0)
1072 return -EINVAL;
1073
1074 if (af == AF_INET) {
1075 dlen = 8;
1076 data[1] = htobe16(remote_port);
1077 } else {
1078 assert(af == AF_INET6);
1079 dlen = sizeof(data);
1080 data[4] = htobe16(remote_port);
1081 }
1082
1083 /* If a previous remote is set, remove its entry */
1084 if (add && previous_remote && !in_addr_equal(af, previous_remote, remote)) {
1085 if (af == AF_INET)
1086 data[0] = previous_remote->in.s_addr;
1087 else
1088 memcpy(data, &previous_remote->in6, sizeof(previous_remote->in6));
1089
1090 r = nft_del_element(nfnl, &messages[msgcnt++], af, nft_table_name(), dnat_map_name(),
1091 key, sizeof(key), data, dlen);
1092 if (r < 0)
1093 return r;
1094 }
1095
1096 if (af == AF_INET)
1097 data[0] = remote->in.s_addr;
1098 else
1099 memcpy(data, &remote->in6, sizeof(remote->in6));
1100
1101 if (add)
1102 r = nft_add_element(nfnl, &messages[msgcnt++], af_to_nfproto(af), nft_table_name(), dnat_map_name(),
1103 key, sizeof(key), data, dlen);
1104 else
1105 r = nft_del_element(nfnl, &messages[msgcnt++], af_to_nfproto(af), nft_table_name(), dnat_map_name(),
1106 key, sizeof(key), data, dlen);
1107 if (r < 0)
1108 return r;
1109
1110 assert(msgcnt < ELEMENTSOF(messages));
1111 r = sd_nfnl_call_batch(nfnl, messages, msgcnt, NFNL_DEFAULT_TIMEOUT_USECS);
1112 if (r < 0)
1113 return r;
1114
1115 return 0;
1116 }
1117
1118 int fw_nftables_add_local_dnat(
1119 sd_netlink *nfnl,
1120 bool add,
1121 int af,
1122 int protocol,
1123 uint16_t local_port,
1124 const union in_addr_union *remote,
1125 uint16_t remote_port,
1126 const union in_addr_union *previous_remote) {
1127
1128 int r;
1129
1130 assert(nfnl);
1131 assert(IN_SET(af, AF_INET, AF_INET6));
1132
1133 if (!socket_ipv6_is_supported() && af == AF_INET6)
1134 return -EOPNOTSUPP;
1135
1136 r = fw_nftables_add_local_dnat_internal(nfnl, add, af, protocol, local_port, remote, remote_port, previous_remote);
1137 if (r != -ENOENT)
1138 return r;
1139
1140 /* See comment in fw_nftables_add_masquerade(). */
1141 r = fw_nftables_init_family(nfnl, af);
1142 if (r < 0)
1143 return r;
1144
1145 /* table created anew; previous address already gone */
1146 return fw_nftables_add_local_dnat_internal(nfnl, add, af, protocol, local_port, remote, remote_port, NULL);
1147 }
1148
1149 static const char *const nfproto_table[] = {
1150 [NFPROTO_ARP] = "arp",
1151 [NFPROTO_BRIDGE] = "bridge",
1152 [NFPROTO_INET] = "inet",
1153 [NFPROTO_IPV4] = "ip",
1154 [NFPROTO_IPV6] = "ip6",
1155 [NFPROTO_NETDEV] = "netdev",
1156 };
1157
1158 DEFINE_STRING_TABLE_LOOKUP(nfproto, int);
1159
1160 static const char *const nft_set_source_table[] = {
1161 [NFT_SET_SOURCE_ADDRESS] = "address",
1162 [NFT_SET_SOURCE_PREFIX] = "prefix",
1163 [NFT_SET_SOURCE_IFINDEX] = "ifindex",
1164 [NFT_SET_SOURCE_CGROUP] = "cgroup",
1165 [NFT_SET_SOURCE_USER] = "user",
1166 [NFT_SET_SOURCE_GROUP] = "group",
1167 };
1168
1169 DEFINE_STRING_TABLE_LOOKUP(nft_set_source, int);
1170
1171 void nft_set_context_clear(NFTSetContext *s) {
1172 assert(s);
1173
1174 FOREACH_ARRAY(nft_set, s->sets, s->n_sets) {
1175 free(nft_set->table);
1176 free(nft_set->set);
1177 }
1178
1179 s->n_sets = 0;
1180 s->sets = mfree(s->sets);
1181 }
1182
1183 int nft_set_add(NFTSetContext *s, NFTSetSource source, int nfproto, const char *table, const char *set) {
1184 _cleanup_free_ char *table_dup = NULL, *set_dup = NULL;
1185
1186 assert(s);
1187 assert(IN_SET(source, NFT_SET_SOURCE_ADDRESS, NFT_SET_SOURCE_PREFIX, NFT_SET_SOURCE_IFINDEX, NFT_SET_SOURCE_CGROUP, NFT_SET_SOURCE_USER, NFT_SET_SOURCE_GROUP));
1188 assert(nfproto_is_valid(nfproto));
1189 assert(table);
1190 assert(set);
1191
1192 table_dup = strdup(table);
1193 if (!table_dup)
1194 return -ENOMEM;
1195
1196 set_dup = strdup(set);
1197 if (!set_dup)
1198 return -ENOMEM;
1199
1200 if (!GREEDY_REALLOC(s->sets, s->n_sets + 1))
1201 return -ENOMEM;
1202
1203 s->sets[s->n_sets++] = (NFTSet) {
1204 .source = source,
1205 .nfproto = nfproto,
1206 .table = TAKE_PTR(table_dup),
1207 .set = TAKE_PTR(set_dup),
1208 };
1209
1210 return 0;
1211 }
1212
1213 int nft_set_context_dup(const NFTSetContext *src, NFTSetContext *dst) {
1214 int r;
1215 _cleanup_(nft_set_context_clear) NFTSetContext d = (NFTSetContext) {};
1216
1217 assert(src);
1218 assert(dst);
1219
1220 FOREACH_ARRAY(nft_set, src->sets, src->n_sets) {
1221 r = nft_set_add(&d, nft_set->source, nft_set->nfproto, nft_set->table, nft_set->set);
1222 if (r < 0)
1223 return r;
1224 }
1225
1226 *dst = TAKE_STRUCT(d);
1227
1228 return 0;
1229 }
1230
1231 int config_parse_nft_set(
1232 const char *unit,
1233 const char *filename,
1234 unsigned line,
1235 const char *section,
1236 unsigned section_line,
1237 const char *lvalue,
1238 int ltype,
1239 const char *rvalue,
1240 void *data,
1241 void *userdata) {
1242
1243 NFTSetContext *nft_set_context = ASSERT_PTR(data);
1244 int r;
1245
1246 assert(IN_SET(ltype, NFT_SET_PARSE_NETWORK, NFT_SET_PARSE_CGROUP));
1247
1248 if (isempty(rvalue)) {
1249 nft_set_context_clear(nft_set_context);
1250 return 1;
1251 }
1252
1253 for (const char *p = rvalue;;) {
1254 _cleanup_free_ char *tuple = NULL, *source_str = NULL, *family_str = NULL, *table = NULL, *set = NULL;
1255 const char *q = NULL;
1256 int nfproto;
1257 NFTSetSource source;
1258
1259 r = extract_first_word(&p, &tuple, NULL, EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE);
1260 if (r < 0)
1261 return log_syntax_parse_error(unit, filename, line, r, lvalue, rvalue);
1262 if (r == 0)
1263 return 1;
1264
1265 q = tuple;
1266 r = extract_many_words(&q, ":", EXTRACT_CUNESCAPE, &source_str, &family_str, &table, &set);
1267 if (r == -ENOMEM)
1268 return log_oom();
1269 if (r != 4 || !isempty(q)) {
1270 _cleanup_free_ char *esc = NULL;
1271
1272 esc = cescape(tuple);
1273 return log_syntax(unit, LOG_WARNING, filename, line, 0, "Failed to parse NFT set %s, ignoring", strna(esc));
1274 }
1275
1276 assert(source_str);
1277 assert(family_str);
1278 assert(table);
1279 assert(set);
1280
1281 source = nft_set_source_from_string(source_str);
1282 if (source < 0 ||
1283 (ltype == NFT_SET_PARSE_NETWORK && !IN_SET(source, NFT_SET_SOURCE_ADDRESS, NFT_SET_SOURCE_PREFIX, NFT_SET_SOURCE_IFINDEX)) ||
1284 (ltype == NFT_SET_PARSE_CGROUP && !IN_SET(source, NFT_SET_SOURCE_CGROUP, NFT_SET_SOURCE_USER, NFT_SET_SOURCE_GROUP))) {
1285 _cleanup_free_ char *esc = NULL;
1286
1287 esc = cescape(source_str);
1288 return log_syntax(unit, LOG_WARNING, filename, line, 0, "Unknown NFT source %s, ignoring", strna(esc));
1289 }
1290
1291 nfproto = nfproto_from_string(family_str);
1292 if (nfproto < 0) {
1293 _cleanup_free_ char *esc = NULL;
1294
1295 esc = cescape(family_str);
1296 return log_syntax(unit, LOG_WARNING, filename, line, 0, "Unknown NFT protocol family %s, ignoring", strna(esc));
1297 }
1298
1299 if (!nft_identifier_valid(table)) {
1300 _cleanup_free_ char *esc = NULL;
1301
1302 esc = cescape(table);
1303 return log_syntax(unit, LOG_WARNING, filename, line, 0, "Invalid table name %s, ignoring", strna(esc));
1304 }
1305
1306 if (!nft_identifier_valid(set)) {
1307 _cleanup_free_ char *esc = NULL;
1308
1309 esc = cescape(set);
1310 return log_syntax(unit, LOG_WARNING, filename, line, 0, "Invalid set name %s, ignoring", strna(esc));
1311 }
1312
1313 r = nft_set_add(nft_set_context, source, nfproto, table, set);
1314 if (r < 0)
1315 return log_oom();
1316 }
1317
1318 assert_not_reached();
1319 }