Imported Upstream version 1.35
[platform/upstream/connman.git] / src / firewall-nftables.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2016  BMW Car IT GmbH.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 /*
23  * This file is based on the libnftnl examples:
24  *   https://git.netfilter.org/libnftnl/tree/examples
25  * by Pablo Neira Ayuso. and inspiration from systemd nft implemention
26  *   https://github.com/zonque/systemd/blob/rfc-nftnl/src/shared/firewall-util.c
27  * by Daniel Mack.
28  */
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33
34 #include <stdlib.h>
35 #include <time.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <stdint.h>
39 #include <alloca.h>
40 #include <netinet/in.h>
41 #include <netinet/ip.h>
42
43 #include <sys/types.h>
44 #include <pwd.h>
45
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49
50 #include <linux/netfilter.h>
51 #include <linux/netfilter/nfnetlink.h>
52 #include <linux/netfilter/nf_nat.h>
53 #include <linux/netfilter/nf_tables.h>
54
55 #include <libmnl/libmnl.h>
56 #include <libnftnl/table.h>
57 #include <libnftnl/chain.h>
58 #include <libnftnl/rule.h>
59 #include <libnftnl/expr.h>
60
61 #include <glib.h>
62
63 #include "connman.h"
64
65 #define CONNMAN_TABLE "connman"
66 #define CONNMAN_CHAIN_NAT_PRE "nat-prerouting"
67 #define CONNMAN_CHAIN_NAT_POST "nat-postrouting"
68 #define CONNMAN_CHAIN_ROUTE_OUTPUT "route-output"
69
70 static bool debug_enabled = true;
71
72 struct firewall_handle {
73         uint64_t handle;
74         const char *chain;
75 };
76
77 struct firewall_context {
78         struct firewall_handle rule;
79 };
80
81 struct nftables_info {
82         struct firewall_handle ct;
83 };
84
85 static struct nftables_info *nft_info;
86
87 enum callback_return_type {
88         CALLBACK_RETURN_NONE = 0,
89         CALLBACK_RETURN_HANDLE,
90         CALLBACK_RETURN_BYTE_COUNTER,
91         _CALLBACK_RETURN_MAX,
92 };
93
94 struct callback_data {
95         enum callback_return_type type;
96         uint64_t value;
97         bool success;
98 };
99
100 static void debug_netlink_dump_rule(struct nftnl_rule *nlr)
101 {
102         char buf[4096];
103
104         if (!debug_enabled)
105                 return;
106
107         nftnl_rule_snprintf(buf, sizeof(buf), nlr, 0, 0);
108         fprintf(stdout, "%s\n", buf);
109 }
110
111 static void debug_mnl_dump_rule(const void *req, size_t req_size)
112 {
113         if (!debug_enabled)
114                 return;
115
116         mnl_nlmsg_fprintf(stdout, req, req_size, 0);
117         printf("\n");
118 }
119
120 static int rule_expr_cb(struct nftnl_expr *expr, void *data) {
121
122         struct callback_data *cb = data;
123         const char *name;
124
125         name = nftnl_expr_get_str(expr, NFTNL_EXPR_NAME);
126
127         if (strcmp(name, "counter")) {
128                 cb->value = nftnl_expr_get_u64(expr, NFTNL_EXPR_CTR_BYTES);
129                 cb->success = true;
130         }
131
132         return 0;
133 }
134
135 static int rule_cb(const struct nlmsghdr *nlh, int event,
136                 struct callback_data *cb)
137 {
138         struct nftnl_rule *rule;
139
140         rule = nftnl_rule_alloc();
141         if (!rule)
142                 return MNL_CB_OK;
143
144         if (nftnl_rule_nlmsg_parse(nlh, rule) < 0)
145                 goto out;
146
147         switch (cb->type) {
148         case CALLBACK_RETURN_HANDLE:
149                 cb->value = nftnl_rule_get_u64(rule, NFTNL_RULE_HANDLE);
150                 cb->success = true;
151                 break;
152
153         case CALLBACK_RETURN_BYTE_COUNTER:
154                 nftnl_expr_foreach(rule, rule_expr_cb, cb);
155                 break;
156
157         default:
158                 DBG("unhandled callback type %d\n", cb->type);
159                 break;
160         }
161
162 out:
163         nftnl_rule_free(rule);
164         return MNL_CB_STOP;
165 }
166
167 static int chain_cb(const struct nlmsghdr *nlh, int event,
168                         struct callback_data *cb)
169 {
170         struct nftnl_chain *chain;
171
172         chain = nftnl_chain_alloc();
173         if (!chain)
174                 return MNL_CB_OK;
175
176         if (nftnl_chain_nlmsg_parse(nlh, chain) < 0)
177                 goto out;
178
179         switch (cb->type) {
180         case CALLBACK_RETURN_HANDLE:
181                 cb->value = nftnl_chain_get_u64(chain, NFTNL_CHAIN_HANDLE);
182                 cb->success = true;
183                 break;
184
185         default:
186                 DBG("unhandled callback type %d\n", cb->type);
187                 break;
188         }
189
190 out:
191         nftnl_chain_free(chain);
192         return MNL_CB_OK;
193 }
194
195 static const char *event_to_str(enum nf_tables_msg_types type)
196 {
197         const char *table[] = {
198                 "NFT_MSG_NEWTABLE",
199                 "NFT_MSG_GETTABLE",
200                 "NFT_MSG_DELTABLE",
201                 "NFT_MSG_NEWCHAIN",
202                 "NFT_MSG_GETCHAIN",
203                 "NFT_MSG_DELCHAIN",
204                 "NFT_MSG_NEWRULE",
205                 "NFT_MSG_GETRULE",
206                 "NFT_MSG_DELRULE",
207                 "NFT_MSG_NEWSET",
208                 "NFT_MSG_GETSET",
209                 "NFT_MSG_DELSET",
210                 "NFT_MSG_NEWSETELEM",
211                 "NFT_MSG_GETSETELEM",
212                 "NFT_MSG_DELSETELEM",
213                 "NFT_MSG_NEWGEN",
214                 "NFT_MSG_GETGEN",
215                 "NFT_MSG_TRACE"
216         };
217
218         if (type < sizeof(table)/sizeof(table[0]))
219                 return table[type];
220
221         return "unknown";
222 }
223
224 static int events_cb(const struct nlmsghdr *nlh, void *data)
225 {
226         int event = NFNL_MSG_TYPE(nlh->nlmsg_type);
227         struct callback_data *cb = data;
228         int err = MNL_CB_OK;
229
230         if (!cb || cb->type == CALLBACK_RETURN_NONE)
231                 return err;
232
233         DBG("handle event %s", event_to_str(event));
234
235         switch(event) {
236         case NFT_MSG_NEWCHAIN:
237                 err = chain_cb(nlh, event, cb);
238                 break;
239
240         case NFT_MSG_NEWRULE:
241                 err = rule_cb(nlh, event, cb);
242                 break;
243         default:
244                 DBG("unhandled event type %s", event_to_str(event));
245                 break;
246         }
247
248         return err;
249 }
250
251 static int socket_open_and_bind(struct mnl_socket **n)
252 {
253
254         struct mnl_socket *nl = NULL;
255         int err;
256
257         nl = mnl_socket_open(NETLINK_NETFILTER);
258         if (!nl)
259                 return -errno;
260
261         err = mnl_socket_bind(nl, 1 << (NFNLGRP_NFTABLES-1),
262                                 MNL_SOCKET_AUTOPID);
263         if (err < 0) {
264                 err = errno;
265                 mnl_socket_close(nl);
266                 return -err;
267         }
268
269         *n = nl;
270         return 0;
271 }
272
273 static int send_and_dispatch(struct mnl_socket *nl, const void *req,
274                 size_t req_size, enum callback_return_type callback_type,
275                 uint64_t *callback_value)
276 {
277         struct callback_data cb = {};
278         uint32_t portid;
279         int err;
280
281         debug_mnl_dump_rule(req, req_size);
282
283         err = mnl_socket_sendto(nl, req, req_size);
284         if (err < 0)
285                 return -errno;
286
287         portid = mnl_socket_get_portid(nl);
288         cb.type = callback_type;
289
290         for (;;) {
291                 char buf[MNL_SOCKET_BUFFER_SIZE];
292
293                 err = mnl_socket_recvfrom(nl, buf, sizeof(buf));
294                 if (err <= 0)
295                         break;
296
297                 err = mnl_cb_run(buf, err, 0, portid, events_cb, &cb);
298                 if (err <= 0)
299                         break;
300         }
301
302         if (err < 0)
303                 return -errno;
304
305         if (callback_type == CALLBACK_RETURN_NONE)
306                 return 0;
307
308         if (cb.success) {
309                 if (callback_value)
310                         *callback_value = cb.value;
311
312                 return 0;
313         }
314
315         return -ENOENT;
316 }
317
318 static void put_batch_headers(char *buf, uint16_t type, uint32_t seq)
319 {
320
321         struct nlmsghdr *nlh;
322         struct nfgenmsg *nfg;
323
324         nlh = mnl_nlmsg_put_header(buf);
325         nlh->nlmsg_type = type;
326         nlh->nlmsg_flags = NLM_F_REQUEST;
327         nlh->nlmsg_seq = seq;
328
329         nfg = mnl_nlmsg_put_extra_header(nlh, sizeof(*nfg));
330         nfg->nfgen_family = AF_INET;
331         nfg->version = NFNETLINK_V0;
332         nfg->res_id = NFNL_SUBSYS_NFTABLES;
333 }
334
335 static int add_payload(struct nftnl_rule *rule, uint32_t base,
336                         uint32_t dreg, uint32_t offset, uint32_t len)
337 {
338         struct nftnl_expr *expr;
339
340         expr = nftnl_expr_alloc("payload");
341         if (!expr)
342                 return -ENOMEM;
343
344         nftnl_expr_set_u32(expr, NFTNL_EXPR_PAYLOAD_BASE, base);
345         nftnl_expr_set_u32(expr, NFTNL_EXPR_PAYLOAD_DREG, dreg);
346         nftnl_expr_set_u32(expr, NFTNL_EXPR_PAYLOAD_OFFSET, offset);
347         nftnl_expr_set_u32(expr, NFTNL_EXPR_PAYLOAD_LEN, len);
348
349         nftnl_rule_add_expr(rule, expr);
350
351         return 0;
352 }
353
354 static int add_bitwise(struct nftnl_rule *rule, int reg, const void *mask,
355                         size_t len)
356 {
357         struct nftnl_expr *expr;
358         uint8_t *xor;
359
360         expr = nftnl_expr_alloc("bitwise");
361         if (!expr)
362                 return -ENOMEM;
363
364         xor = alloca(len);
365         memset(xor, 0, len);
366
367         nftnl_expr_set_u32(expr, NFTNL_EXPR_BITWISE_SREG, reg);
368         nftnl_expr_set_u32(expr, NFTNL_EXPR_BITWISE_DREG, reg);
369         nftnl_expr_set_u32(expr, NFTNL_EXPR_BITWISE_LEN, len);
370         nftnl_expr_set(expr, NFTNL_EXPR_BITWISE_MASK, mask, len);
371         nftnl_expr_set(expr, NFTNL_EXPR_BITWISE_XOR, xor, len);
372
373         nftnl_rule_add_expr(rule, expr);
374
375         return 0;
376 }
377
378 static int add_cmp(struct nftnl_rule *rule, uint32_t sreg, uint32_t op,
379                         const void *data, uint32_t data_len)
380 {
381         struct nftnl_expr *expr;
382
383         expr = nftnl_expr_alloc("cmp");
384         if (!expr)
385                 return -ENOMEM;
386
387         nftnl_expr_set_u32(expr, NFTNL_EXPR_CMP_SREG, sreg);
388         nftnl_expr_set_u32(expr, NFTNL_EXPR_CMP_OP, op);
389         nftnl_expr_set(expr, NFTNL_EXPR_CMP_DATA, data, data_len);
390
391         nftnl_rule_add_expr(rule, expr);
392
393         return 0;
394 }
395
396 static int table_cmd(struct mnl_socket *nl, struct nftnl_table *t,
397                 uint16_t cmd, uint16_t family, uint16_t type)
398 {
399         char buf[MNL_SOCKET_BUFFER_SIZE];
400         struct mnl_nlmsg_batch *batch;
401         struct nlmsghdr *nlh;
402         uint32_t seq = 0;
403         int err;
404
405         batch = mnl_nlmsg_batch_start(buf, sizeof(buf));
406         nftnl_batch_begin(mnl_nlmsg_batch_current(batch), seq++);
407         mnl_nlmsg_batch_next(batch);
408
409         nlh = nftnl_table_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
410                                 cmd, family, type, seq++);
411         nftnl_table_nlmsg_build_payload(nlh, t);
412         nftnl_table_free(t);
413         mnl_nlmsg_batch_next(batch);
414
415         nftnl_batch_end(mnl_nlmsg_batch_current(batch), seq++);
416         mnl_nlmsg_batch_next(batch);
417
418         /* The current table commands do not support any callback returns. */
419         err = send_and_dispatch(nl, mnl_nlmsg_batch_head(batch),
420                                 mnl_nlmsg_batch_size(batch), 0, NULL);
421
422         mnl_nlmsg_batch_stop(batch);
423         return err;
424 }
425
426 static int chain_cmd(struct mnl_socket *nl, struct nftnl_chain *chain,
427                 uint16_t cmd, int family, uint16_t type,
428                 enum callback_return_type cb_type, uint64_t *cb_val)
429 {
430         char buf[MNL_SOCKET_BUFFER_SIZE];
431         struct mnl_nlmsg_batch *batch;
432         struct nlmsghdr *nlh;
433         uint32_t seq = 0;
434         int err;
435
436         batch = mnl_nlmsg_batch_start(buf, sizeof(buf));
437         nftnl_batch_begin(mnl_nlmsg_batch_current(batch), seq++);
438         mnl_nlmsg_batch_next(batch);
439
440         nlh = nftnl_chain_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
441                                         cmd, family, type, seq++);
442         nftnl_chain_nlmsg_build_payload(nlh, chain);
443         nftnl_chain_free(chain);
444         mnl_nlmsg_batch_next(batch);
445
446         nftnl_batch_end(mnl_nlmsg_batch_current(batch), seq++);
447         mnl_nlmsg_batch_next(batch);
448
449         err = send_and_dispatch(nl, mnl_nlmsg_batch_head(batch),
450                         mnl_nlmsg_batch_size(batch), cb_type, cb_val);
451
452         mnl_nlmsg_batch_stop(batch);
453         return err;
454 }
455
456 static int rule_cmd(struct mnl_socket *nl, struct nftnl_rule *rule,
457                         uint16_t cmd, uint16_t family, uint16_t type,
458                         enum callback_return_type callback_type,
459                         uint64_t *callback_value)
460 {
461
462         char buf[MNL_SOCKET_BUFFER_SIZE];
463         struct mnl_nlmsg_batch *batch;
464         struct nlmsghdr *nlh;
465         uint32_t seq = 0;
466         int err;
467
468         debug_netlink_dump_rule(rule);
469
470         batch = mnl_nlmsg_batch_start(buf, sizeof(buf));
471         put_batch_headers(mnl_nlmsg_batch_current(batch),
472                                 NFNL_MSG_BATCH_BEGIN, seq++);
473         mnl_nlmsg_batch_next(batch);
474
475         nlh = nftnl_rule_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
476                                         cmd, family, type, seq++);
477         nftnl_rule_nlmsg_build_payload(nlh, rule);
478         mnl_nlmsg_batch_next(batch);
479
480         put_batch_headers(mnl_nlmsg_batch_current(batch),
481                                 NFNL_MSG_BATCH_END, seq++);
482         mnl_nlmsg_batch_next(batch);
483
484         err = send_and_dispatch(nl, mnl_nlmsg_batch_head(batch),
485                                 mnl_nlmsg_batch_size(batch),
486                                 callback_type, callback_value);
487         mnl_nlmsg_batch_stop(batch);
488
489         return err;
490 }
491
492 static int rule_delete(struct firewall_handle *handle)
493 {
494         struct nftnl_rule *rule;
495         struct mnl_socket *nl;
496         int err;
497
498         DBG("");
499
500         rule = nftnl_rule_alloc();
501         if (!rule)
502                 return -ENOMEM;
503
504         nftnl_rule_set(rule, NFTNL_RULE_TABLE, CONNMAN_TABLE);
505         nftnl_rule_set(rule, NFTNL_RULE_CHAIN, handle->chain);
506         nftnl_rule_set_u64(rule, NFTNL_RULE_HANDLE, handle->handle);
507
508         err = socket_open_and_bind(&nl);
509         if (err < 0) {
510                 nftnl_rule_free(rule);
511                 return err;
512         }
513
514         err = rule_cmd(nl, rule, NFT_MSG_DELRULE, NFPROTO_IPV4,
515                         NLM_F_ACK, 0, NULL);
516         nftnl_rule_free(rule);
517         mnl_socket_close(nl);
518
519         return err;
520 }
521
522 struct firewall_context *__connman_firewall_create(void)
523 {
524         struct firewall_context *ctx;
525
526         DBG("");
527
528         ctx = g_new0(struct firewall_context, 1);
529
530         return ctx;
531 }
532
533 void __connman_firewall_destroy(struct firewall_context *ctx)
534 {
535         DBG("");
536
537         g_free(ctx);
538 }
539
540 static int build_rule_nat(const char *address, unsigned char prefixlen,
541                                 const char *interface, struct nftnl_rule **res)
542 {
543         struct nftnl_rule *rule;
544         struct in_addr ipv4_addr, ipv4_mask;
545         struct nftnl_expr *expr;
546         int err;
547
548         /*
549          * # nft --debug netlink add rule connman nat-postrouting       \
550          *      oifname eth0 ip saddr 10.10.0.0/24 masquerade
551          *
552          *      ip connman nat-postrouting
553          *        [ meta load oifname => reg 1 ]
554          *        [ cmp eq reg 1 0x30687465 0x00000000 0x00000000 0x00000000 ]
555          *        [ payload load 4b @ network header + 12 => reg 1 ]
556          *        [ bitwise reg 1 = (reg=1 & 0x00ffffff ) ^ 0x00000000 ]
557          *        [ cmp eq reg 1 0x00000a0a ]
558          *        [ masq ]
559          */
560
561         rule = nftnl_rule_alloc();
562         if (!rule)
563                 return -ENOMEM;
564
565         nftnl_rule_set(rule, NFTNL_RULE_TABLE, CONNMAN_TABLE);
566         nftnl_rule_set(rule, NFTNL_RULE_CHAIN, CONNMAN_CHAIN_NAT_POST);
567
568         /* family ipv4 */
569         nftnl_rule_set_u32(rule, NFTNL_RULE_FAMILY, NFPROTO_IPV4);
570
571         /* oifname */
572         expr = nftnl_expr_alloc("meta");
573         if (!expr)
574                 goto err;
575         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_KEY, NFT_META_OIFNAME);
576         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_DREG, NFT_REG_1);
577         nftnl_rule_add_expr(rule, expr);
578         err = add_cmp(rule, NFT_REG_1, NFT_CMP_EQ, interface,
579                         strlen(interface) + 1);
580         if (err < 0)
581                 goto err;
582
583         /* source */
584         ipv4_mask.s_addr = htonl((0xffffffff << (32 - prefixlen)) & 0xffffffff);
585         ipv4_addr.s_addr = inet_addr(address);
586         ipv4_addr.s_addr &= ipv4_mask.s_addr;
587
588         err = add_payload(rule, NFT_PAYLOAD_NETWORK_HEADER, NFT_REG_1,
589                         offsetof(struct iphdr, saddr), sizeof(struct in_addr));
590         if (err < 0)
591                 goto err;
592         err = add_bitwise(rule, NFT_REG_1, &ipv4_mask.s_addr,
593                                 sizeof(struct in_addr));
594         if (err < 0)
595                 goto err;
596         err = add_cmp(rule, NFT_REG_1, NFT_CMP_EQ, &ipv4_addr.s_addr,
597                         sizeof(struct in_addr));
598         if (err < 0)
599                 goto err;
600
601         /* masquerade */
602         expr = nftnl_expr_alloc("masq");
603         if (!expr)
604                 goto err;
605         nftnl_rule_add_expr(rule, expr);
606
607         *res = rule;
608         return 0;
609
610 err:
611         nftnl_rule_free(rule);
612         return -ENOMEM;
613 }
614
615 int __connman_firewall_enable_nat(struct firewall_context *ctx,
616                                         char *address, unsigned char prefixlen,
617                                         char *interface)
618 {
619         struct mnl_socket *nl;
620         struct nftnl_rule *rule;
621         int err;
622
623         DBG("address %s/%d interface %s", address, (int)prefixlen, interface);
624
625         err = socket_open_and_bind(&nl);
626         if (err < 0)
627                 return err;
628
629         err = build_rule_nat(address, prefixlen, interface, &rule);
630         if (err)
631                 goto out;
632
633         ctx->rule.chain = CONNMAN_CHAIN_NAT_POST;
634         err = rule_cmd(nl, rule, NFT_MSG_NEWRULE, NFPROTO_IPV4,
635                         NLM_F_APPEND|NLM_F_CREATE|NLM_F_ACK,
636                         CALLBACK_RETURN_HANDLE, &ctx->rule.handle);
637         nftnl_rule_free(rule);
638 out:
639         mnl_socket_close(nl);
640         return err;
641 }
642
643 int __connman_firewall_disable_nat(struct firewall_context *ctx)
644 {
645         return rule_delete(&ctx->rule);
646 }
647
648 static int build_rule_snat(int index, const char *address,
649                                 struct nftnl_rule **res)
650 {
651         struct nftnl_rule *rule;
652         struct nftnl_expr *expr;
653         uint32_t snat;
654         int err;
655
656         /*
657          * # nft --debug netlink add rule connman nat-postrouting \
658          *      oif eth0 snat 1.2.3.4
659          *      ip connman nat-postrouting
660          *        [ meta load oif => reg 1 ]
661          *        [ cmp eq reg 1 0x0000000b ]
662          *        [ immediate reg 1 0x04030201 ]
663          *        [ nat snat ip addr_min reg 1 addr_max reg 0 ]
664          */
665
666         rule = nftnl_rule_alloc();
667         if (!rule)
668                 return -ENOMEM;
669
670         nftnl_rule_set(rule, NFTNL_RULE_TABLE, CONNMAN_TABLE);
671         nftnl_rule_set(rule, NFTNL_RULE_CHAIN, CONNMAN_CHAIN_NAT_POST);
672
673         /* IOF */
674         expr = nftnl_expr_alloc("meta");
675         if (!expr)
676                 goto err;
677         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_KEY, NFT_META_OIF);
678         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_DREG, NFT_REG_1);
679         nftnl_rule_add_expr(rule, expr);
680         err = add_cmp(rule, NFT_REG_1, NFT_CMP_EQ, &index, sizeof(index));
681         if (err < 0)
682                 goto err;
683
684         /* snat */
685         expr = nftnl_expr_alloc("immediate");
686         if (!expr)
687                 goto err;
688         snat = inet_addr(address);
689         nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_DREG, NFT_REG_1);
690         nftnl_expr_set(expr, NFTNL_EXPR_IMM_DATA, &snat, sizeof(snat));
691         nftnl_rule_add_expr(rule, expr);
692
693         expr = nftnl_expr_alloc("nat");
694         if (!expr)
695                 goto err;
696         nftnl_expr_set_u32(expr, NFTNL_EXPR_NAT_TYPE, NFT_NAT_SNAT);
697         nftnl_expr_set_u32(expr, NFTNL_EXPR_NAT_FAMILY, NFPROTO_IPV4);
698         nftnl_expr_set_u32(expr, NFTNL_EXPR_NAT_REG_ADDR_MIN, NFT_REG_1);
699         nftnl_rule_add_expr(rule, expr);
700
701         *res = rule;
702         return 0;
703
704 err:
705         nftnl_rule_free(rule);
706         return -ENOMEM;
707 }
708
709 int __connman_firewall_enable_snat(struct firewall_context *ctx,
710                                 int index, const char *ifname, const char *addr)
711 {
712         struct nftnl_rule *rule;
713         struct mnl_socket *nl;
714         int err;
715
716         DBG("");
717
718         err = socket_open_and_bind(&nl);
719         if (err < 0)
720                 return err;
721
722         err = build_rule_snat(index, addr, &rule);
723         if (err)
724                 goto out;
725
726         ctx->rule.chain = CONNMAN_CHAIN_NAT_POST;
727         err = rule_cmd(nl, rule, NFT_MSG_NEWRULE, NFPROTO_IPV4,
728                         NLM_F_APPEND|NLM_F_CREATE|NLM_F_ACK,
729                         CALLBACK_RETURN_HANDLE, &ctx->rule.handle);
730         nftnl_rule_free(rule);
731 out:
732         mnl_socket_close(nl);
733         return err;
734 }
735
736 int __connman_firewall_disable_snat(struct firewall_context *ctx)
737 {
738         DBG("");
739
740         return rule_delete(&ctx->rule);
741 }
742
743 static int build_rule_marking(uid_t uid, uint32_t mark, struct nftnl_rule **res)
744 {
745         struct nftnl_rule *rule;
746         struct nftnl_expr *expr;
747         int err;
748
749         /*
750          * http://wiki.nftables.org/wiki-nftables/index.php/Setting_packet_metainformation
751          * http://wiki.nftables.org/wiki-nftables/index.php/Matching_packet_metainformation
752          *
753          * # nft --debug netlink add rule connman route-output  \
754          *      meta skuid wagi mark set 1234
755          *
756          *      ip connman route-output
757          *        [ meta load skuid => reg 1 ]
758          *        [ cmp eq reg 1 0x000003e8 ]
759          *        [ immediate reg 1 0x000004d2 ]
760          *        [ meta set mark with reg 1 ]
761          */
762
763         rule = nftnl_rule_alloc();
764         if (!rule)
765                 return -ENOMEM;
766
767         nftnl_rule_set(rule, NFTNL_RULE_TABLE, CONNMAN_TABLE);
768         nftnl_rule_set(rule, NFTNL_RULE_CHAIN, CONNMAN_CHAIN_ROUTE_OUTPUT);
769
770         expr = nftnl_expr_alloc("meta");
771         if (!expr)
772                 goto err;
773         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_KEY, NFT_META_SKUID);
774         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_DREG, NFT_REG_1);
775         nftnl_rule_add_expr(rule, expr);
776         err = add_cmp(rule, NFT_REG_1, NFT_CMP_EQ, &uid, sizeof(uid));
777         if (err < 0)
778                 goto err;
779
780         expr = nftnl_expr_alloc("immediate");
781         if (!expr)
782                 goto err;
783         nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_DREG, NFT_REG_1);
784         nftnl_expr_set(expr, NFTNL_EXPR_IMM_DATA, &mark, sizeof(mark));
785         nftnl_rule_add_expr(rule, expr);
786
787         expr = nftnl_expr_alloc("meta");
788         if (!expr)
789                 goto err;
790         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_KEY, NFT_META_MARK);
791         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_SREG, NFT_REG_1);
792         nftnl_rule_add_expr(rule, expr);
793
794         *res = rule;
795         return 0;
796
797 err:
798         return -ENOMEM;
799 }
800
801 static int build_rule_src_ip(const char *src_ip, uint32_t mark, struct nftnl_rule **res)
802 {
803         struct nftnl_rule *rule;
804         struct nftnl_expr *expr;
805         int err;
806         in_addr_t s_addr;
807
808         /*
809          * # nft --debug netlink add rule connman route-output \
810          *      ip saddr 192.168.10.31 mark set 1234
811          *
812          *      ip connman route-output
813          *        [ payload load 4b @ network header + 12 => reg 1 ]
814          *        [ cmp eq reg 1 0x1f0aa8c0 ]
815          *        [ immediate reg 1 0x000004d2 ]
816          *        [ meta set mark with reg 1 ]
817          */
818
819         rule = nftnl_rule_alloc();
820         if (!rule)
821                 return -ENOMEM;
822
823         nftnl_rule_set(rule, NFTNL_RULE_TABLE, CONNMAN_TABLE);
824         nftnl_rule_set(rule, NFTNL_RULE_CHAIN, CONNMAN_CHAIN_ROUTE_OUTPUT);
825
826         /* family ipv4 */
827         nftnl_rule_set_u32(rule, NFTNL_RULE_FAMILY, NFPROTO_IPV4);
828
829         /* source IP */
830         err = add_payload(rule, NFT_PAYLOAD_NETWORK_HEADER, NFT_REG_1,
831                         offsetof(struct iphdr, saddr), sizeof(struct in_addr));
832         if (err < 0)
833                 goto err;
834
835         s_addr = inet_addr(src_ip);
836         err = add_cmp(rule, NFT_REG_1, NFT_CMP_EQ, &s_addr, sizeof(s_addr));
837         if (err < 0)
838                 goto err;
839
840         expr = nftnl_expr_alloc("immediate");
841         if (!expr)
842                 goto err;
843         nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_DREG, NFT_REG_1);
844         nftnl_expr_set(expr, NFTNL_EXPR_IMM_DATA, &mark, sizeof(mark));
845         nftnl_rule_add_expr(rule, expr);
846
847         expr = nftnl_expr_alloc("meta");
848         if (!expr)
849                 goto err;
850         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_KEY, NFT_META_MARK);
851         nftnl_expr_set_u32(expr, NFTNL_EXPR_META_SREG, NFT_REG_1);
852         nftnl_rule_add_expr(rule, expr);
853
854         *res = rule;
855         return 0;
856
857 err:
858         return -ENOMEM;
859 }
860
861 int __connman_firewall_enable_marking(struct firewall_context *ctx,
862                                         enum connman_session_id_type id_type,
863                                         char *id, const char *src_ip,
864                                         uint32_t mark)
865 {
866         struct nftnl_rule *rule;
867         struct mnl_socket *nl;
868         struct passwd *pw;
869         uid_t uid;
870         int err;
871
872         DBG("");
873
874         if (id_type == CONNMAN_SESSION_ID_TYPE_UID) {
875                 pw = getpwnam(id);
876                 if (!pw)
877                         return -EINVAL;
878                 uid = pw->pw_uid;
879         }
880         else if (!src_ip)
881                 return -ENOTSUP;
882
883         err = socket_open_and_bind(&nl);
884         if (err < 0)
885                 return err;
886
887         if (id_type == CONNMAN_SESSION_ID_TYPE_UID) {
888                 err = build_rule_marking(uid, mark, &rule);
889                 if (err < 0)
890                         goto out;
891
892                 ctx->rule.chain = CONNMAN_CHAIN_ROUTE_OUTPUT;
893                 err = rule_cmd(nl, rule, NFT_MSG_NEWRULE, NFPROTO_IPV4,
894                                 NLM_F_APPEND|NLM_F_CREATE|NLM_F_ACK,
895                                 CALLBACK_RETURN_HANDLE, &ctx->rule.handle);
896
897                 nftnl_rule_free(rule);
898         }
899
900         if (src_ip) {
901                 err = build_rule_src_ip(src_ip, mark, &rule);
902                 if (err < 0)
903                         goto out;
904
905                 ctx->rule.chain = CONNMAN_CHAIN_ROUTE_OUTPUT;
906                 err = rule_cmd(nl, rule, NFT_MSG_NEWRULE, NFPROTO_IPV4,
907                                 NLM_F_APPEND|NLM_F_CREATE|NLM_F_ACK,
908                                 CALLBACK_RETURN_HANDLE, &ctx->rule.handle);
909
910                 nftnl_rule_free(rule);
911         }
912 out:
913         mnl_socket_close(nl);
914         return err;
915 }
916
917 int __connman_firewall_disable_marking(struct firewall_context *ctx)
918 {
919         int err;
920
921         DBG("");
922
923         err = rule_delete(&ctx->rule);
924         return err;
925 }
926
927 static struct nftnl_table *build_table(const char *name, uint16_t family)
928 {
929         struct nftnl_table *table;
930
931         table = nftnl_table_alloc();
932         if (!table)
933                 return NULL;
934
935         nftnl_table_set_u32(table, NFTNL_TABLE_FAMILY, family);
936         nftnl_table_set_str(table, NFTNL_TABLE_NAME, name);
937
938         return table;
939 }
940
941
942 static struct nftnl_chain *build_chain(const char *name, const char *table,
943                                 const char *type, int hooknum, int prio)
944 {
945         struct nftnl_chain *chain;
946
947         chain = nftnl_chain_alloc();
948         if (!chain)
949                 return NULL;
950
951         nftnl_chain_set(chain, NFTNL_CHAIN_TABLE, table);
952         nftnl_chain_set(chain, NFTNL_CHAIN_NAME, name);
953
954         if (type)
955                 nftnl_chain_set_str(chain, NFTNL_CHAIN_TYPE, type);
956
957         if (hooknum >= 0)
958                 nftnl_chain_set_u32(chain, NFTNL_CHAIN_HOOKNUM, hooknum);
959
960         if (prio >= 0)
961                 nftnl_chain_set_u32(chain, NFTNL_CHAIN_PRIO, prio);
962
963         return chain;
964 }
965
966 static int create_table_and_chains(struct nftables_info *nft_info)
967 {
968         struct mnl_socket *nl;
969         struct nftnl_table *table;
970         struct nftnl_chain *chain;
971         int err;
972
973
974         DBG("");
975
976         err = socket_open_and_bind(&nl);
977         if (err < 0)
978                 return err;
979
980         /*
981          * Add table
982          * http://wiki.nftables.org/wiki-nftables/index.php/Configuring_tables
983          */
984
985         /*
986          * # nft add table connman
987          */
988         table = build_table(CONNMAN_TABLE, NFPROTO_IPV4);
989         if (!table) {
990                 err = -ENOMEM;
991                 goto out;
992         }
993
994         err = table_cmd(nl, table, NFT_MSG_NEWTABLE, NFPROTO_IPV4,
995                         NLM_F_CREATE|NLM_F_ACK);
996         if (err < 0)
997                 goto out;
998
999         /*
1000          * Add basic chains
1001          * http://wiki.nftables.org/wiki-nftables/index.php/Configuring_chains
1002          */
1003
1004         /*
1005          * # nft add chain connman nat-prerouting               \
1006          *      { type nat hook prerouting priortiy 0 ; }
1007          */
1008         chain = build_chain(CONNMAN_CHAIN_NAT_PRE, CONNMAN_TABLE,
1009                                 "nat", NF_INET_PRE_ROUTING, 0);
1010         if (!chain) {
1011                 err = -ENOMEM;
1012                 goto out;
1013         }
1014
1015         err = chain_cmd(nl, chain, NFT_MSG_NEWCHAIN,
1016                         NFPROTO_IPV4, NLM_F_CREATE | NLM_F_ACK,
1017                         CALLBACK_RETURN_NONE, NULL);
1018         if (err < 0)
1019                 goto out;
1020
1021         /*
1022          * # nft add chain connman nat-postrouting              \
1023          *      { type nat hook postrouting priortiy 0 ; }
1024          */
1025         chain = build_chain(CONNMAN_CHAIN_NAT_POST, CONNMAN_TABLE,
1026                                 "nat", NF_INET_POST_ROUTING, 0);
1027         if (!chain) {
1028                 err = -ENOMEM;
1029                 goto out;
1030         }
1031
1032         err = chain_cmd(nl, chain, NFT_MSG_NEWCHAIN,
1033                         NFPROTO_IPV4, NLM_F_CREATE | NLM_F_ACK,
1034                         CALLBACK_RETURN_NONE, NULL);
1035         if (err < 0)
1036                 goto out;
1037
1038         /*
1039          * # nft add chain connman route-output         \
1040          *      { type route hook output priority 0 ; }
1041          */
1042         chain = build_chain(CONNMAN_CHAIN_ROUTE_OUTPUT, CONNMAN_TABLE,
1043                                 "route", NF_INET_LOCAL_OUT, 0);
1044         if (!chain) {
1045                 err = -ENOMEM;
1046                 goto out;
1047         }
1048
1049         err = chain_cmd(nl, chain, NFT_MSG_NEWCHAIN,
1050                         NFPROTO_IPV4, NLM_F_CREATE | NLM_F_ACK,
1051                         CALLBACK_RETURN_NONE, NULL);
1052         if (err < 0)
1053                 goto out;
1054
1055 out:
1056         if (err)
1057                 connman_warn("Failed to create basic chains: %s",
1058                                 strerror(-err));
1059         mnl_socket_close(nl);
1060         return err;
1061 }
1062
1063 static int cleanup_table_and_chains(void)
1064 {
1065         struct nftnl_table *table;
1066         struct mnl_socket *nl;
1067         int err;
1068
1069         DBG("");
1070
1071         err = socket_open_and_bind(&nl);
1072         if (err < 0)
1073                 return -ENOMEM;
1074
1075         /*
1076          * Cleanup everythying in one go. There is little point in
1077          * step-by-step removal of rules and chains if you can get it
1078          * as simple as this.
1079          */
1080         /*
1081          * # nft delete table connman
1082          */
1083         table = build_table(CONNMAN_TABLE, NFPROTO_IPV4);
1084         err = table_cmd(nl, table, NFT_MSG_DELTABLE, NFPROTO_IPV4, NLM_F_ACK);
1085
1086         mnl_socket_close(nl);
1087         return err;
1088 }
1089
1090 int __connman_firewall_init(void)
1091 {
1092         int err;
1093
1094         DBG("");
1095
1096         if (getenv("CONNMAN_NFTABLES_DEBUG"))
1097                 debug_enabled = true;
1098
1099         /*
1100          * EAFNOSUPPORT is return whenever the nf_tables_ipv4 hasn't been
1101          * loaded yet. ENOENT is return in case the table is missing.
1102          */
1103         err = cleanup_table_and_chains();
1104         if (err < 0 && (err != EAFNOSUPPORT && err != -ENOENT)) {
1105                 connman_warn("initializing nftable failed with '%s' %d. Check if kernel module nf_tables_ipv4 is missing\n",
1106                         strerror(-err), err);
1107                 return err;
1108         }
1109
1110         nft_info = g_new0(struct nftables_info, 1);
1111         err = create_table_and_chains(nft_info);
1112         if (err) {
1113                 g_free(nft_info);
1114                 nft_info = NULL;
1115         }
1116
1117         return err;
1118 }
1119
1120 void __connman_firewall_cleanup(void)
1121 {
1122         int err;
1123
1124         DBG("");
1125
1126         err = cleanup_table_and_chains();
1127         if (err < 0)
1128                 connman_warn("cleanup table and chains failed with '%s' %d\n",
1129                         strerror(-err), err);
1130
1131         g_free(nft_info);
1132         nft_info = NULL;
1133 }