iptables: Adding capability to insert a rule
[framework/connectivity/connman.git] / src / iptables.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  Intel Corporation. All rights reserved.
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 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <getopt.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/errno.h>
32 #include <sys/socket.h>
33 #include <xtables.h>
34
35 #include <linux/netfilter_ipv4/ip_tables.h>
36
37 #include "connman.h"
38
39
40 static const char *hooknames[] = {
41         [NF_IP_PRE_ROUTING]     = "PREROUTING",
42         [NF_IP_LOCAL_IN]        = "INPUT",
43         [NF_IP_FORWARD]         = "FORWARD",
44         [NF_IP_LOCAL_OUT]       = "OUTPUT",
45         [NF_IP_POST_ROUTING]    = "POSTROUTING",
46 };
47
48 #define LABEL_ACCEPT  "ACCEPT"
49 #define LABEL_DROP    "DROP"
50 #define LABEL_QUEUE   "QUEUE"
51 #define LABEL_RETURN  "RETURN"
52
53 /* fn returns 0 to continue iteration */
54 #define _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, n, fn, args...) \
55 ({                                                              \
56         unsigned int __i;                                       \
57         int __n;                                                \
58         int __ret = 0;                                          \
59         type *__entry;                                          \
60                                                                 \
61         for (__i = 0, __n = 0; __i < (size);                    \
62              __i += __entry->next_offset, __n++) {              \
63                 __entry = (void *)(entries) + __i;              \
64                 if (__n < n)                                    \
65                         continue;                               \
66                                                                 \
67                 __ret = fn(__entry,  ## args);                  \
68                 if (__ret != 0)                                 \
69                         break;                                  \
70         }                                                       \
71         __ret;                                                  \
72 })
73
74 /* fn returns 0 to continue iteration */
75 #define _XT_ENTRY_ITERATE(type, entries, size, fn, args...) \
76         _XT_ENTRY_ITERATE_CONTINUE(type, entries, size, 0, fn, args)
77
78 #define ENTRY_ITERATE(entries, size, fn, args...) \
79         _XT_ENTRY_ITERATE(struct ipt_entry, entries, size, fn, ## args)
80
81 #define MIN_ALIGN (__alignof__(struct ipt_entry))
82
83 #define ALIGN(s) (((s) + ((MIN_ALIGN)-1)) & ~((MIN_ALIGN)-1))
84
85 struct error_target {
86         struct xt_entry_target t;
87         char error[IPT_TABLE_MAXNAMELEN];
88 };
89
90 struct connman_iptables_entry {
91         int offset;
92         int builtin;
93
94         struct ipt_entry *entry;
95 };
96
97 struct connman_iptables {
98         int ipt_sock;
99
100         struct ipt_getinfo *info;
101         struct ipt_get_entries *blob_entries;
102
103         unsigned int num_entries;
104         unsigned int old_entries;
105         unsigned int size;
106
107         unsigned int underflow[NF_INET_NUMHOOKS];
108         unsigned int hook_entry[NF_INET_NUMHOOKS];
109
110         GList *entries;
111 };
112
113 static GHashTable *table_hash = NULL;
114
115 static struct ipt_entry *get_entry(struct connman_iptables *table,
116                                         unsigned int offset)
117 {
118         return (struct ipt_entry *)((char *)table->blob_entries->entrytable +
119                                                                         offset);
120 }
121
122 static int is_hook_entry(struct connman_iptables *table,
123                                 struct ipt_entry *entry)
124 {
125         unsigned int i;
126
127         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
128                 if ((table->info->valid_hooks & (1 << i))
129                 && get_entry(table, table->info->hook_entry[i]) == entry)
130                         return i;
131         }
132
133         return -1;
134 }
135
136 static unsigned long entry_to_offset(struct connman_iptables *table,
137                                         struct ipt_entry *entry)
138 {
139         return (void *)entry - (void *)table->blob_entries->entrytable;
140 }
141
142 static int target_to_verdict(char *target_name)
143 {
144         if (!strcmp(target_name, LABEL_ACCEPT))
145                 return -NF_ACCEPT - 1;
146
147         if (!strcmp(target_name, LABEL_DROP))
148                 return -NF_DROP - 1;
149
150         if (!strcmp(target_name, LABEL_QUEUE))
151                 return -NF_QUEUE - 1;
152
153         if (!strcmp(target_name, LABEL_RETURN))
154                 return XT_RETURN;
155
156         return 0;
157 }
158
159 static gboolean is_builtin_target(char *target_name)
160 {
161         if (!strcmp(target_name, LABEL_ACCEPT) ||
162                 !strcmp(target_name, LABEL_DROP) ||
163                 !strcmp(target_name, LABEL_QUEUE) ||
164                 !strcmp(target_name, LABEL_RETURN))
165                 return TRUE;
166
167         return FALSE;
168 }
169
170 static gboolean is_jump(struct connman_iptables_entry *e)
171 {
172         struct xt_entry_target *target;
173
174         target = ipt_get_target(e->entry);
175
176         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
177                 struct xt_standard_target *t;
178
179                 t = (struct xt_standard_target *)target;
180
181                 switch (t->verdict) {
182                 case XT_RETURN:
183                 case -NF_ACCEPT - 1:
184                 case -NF_DROP - 1:
185                 case -NF_QUEUE - 1:
186                 case -NF_STOP - 1:
187                         return false;
188
189                 default:
190                         return true;
191                 }
192         }
193
194         return false;
195 }
196
197 static gboolean is_chain(struct connman_iptables *table,
198                                 struct connman_iptables_entry *e)
199 {
200         struct ipt_entry *entry;
201         struct xt_entry_target *target;
202
203         entry = e->entry;
204         if (e->builtin >= 0)
205                 return TRUE;
206
207         target = ipt_get_target(entry);
208         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET))
209                 return TRUE;
210
211         return FALSE;
212 }
213
214 static GList *find_chain_head(struct connman_iptables *table,
215                                 char *chain_name)
216 {
217         GList *list;
218         struct connman_iptables_entry *head;
219         struct ipt_entry *entry;
220         struct xt_entry_target *target;
221         int builtin;
222
223         for (list = table->entries; list; list = list->next) {
224                 head = list->data;
225                 entry = head->entry;
226
227                 /* Buit-in chain */
228                 builtin = head->builtin;
229                 if (builtin >= 0 && !strcmp(hooknames[builtin], chain_name))
230                         break;
231
232                 /* User defined chain */
233                 target = ipt_get_target(entry);
234                 if (!strcmp(target->u.user.name, IPT_ERROR_TARGET) &&
235                     !strcmp((char *)target->data, chain_name))
236                         break;
237         }
238
239         return list;
240 }
241
242 static GList *find_chain_tail(struct connman_iptables *table,
243                                 char *chain_name)
244 {
245         struct connman_iptables_entry *tail;
246         GList *chain_head, *list;
247
248         chain_head = find_chain_head(table, chain_name);
249         if (chain_head == NULL)
250                 return NULL;
251
252         /* Then we look for the next chain */
253         for (list = chain_head->next; list; list = list->next) {
254                 tail = list->data;
255
256                 if (is_chain(table, tail))
257                         return list;
258         }
259
260         /* Nothing found, we return the table end */
261         return g_list_last(table->entries);
262 }
263
264
265 static void update_offsets(struct connman_iptables *table)
266 {
267         GList *list, *prev;
268         struct connman_iptables_entry *entry, *prev_entry;
269
270         for (list = table->entries; list; list = list->next) {
271                 entry = list->data;
272
273                 if (list == table->entries) {
274                         entry->offset = 0;
275
276                         continue;
277                 }
278
279                 prev = list->prev;
280                 prev_entry = prev->data;
281
282                 entry->offset = prev_entry->offset +
283                                         prev_entry->entry->next_offset;
284         }
285 }
286
287 static int iptables_add_entry(struct connman_iptables *table,
288                                 struct ipt_entry *entry, GList *before,
289                                         int builtin)
290 {
291         GList *list;
292         struct connman_iptables_entry *e, *tmp, *entry_before;
293         struct xt_standard_target *t;
294
295         if (table == NULL)
296                 return -1;
297
298         e = g_try_malloc0(sizeof(struct connman_iptables_entry));
299         if (e == NULL)
300                 return -1;
301
302         e->entry = entry;
303         e->builtin = builtin;
304
305         table->entries = g_list_insert_before(table->entries, before, e);
306         table->num_entries++;
307         table->size += entry->next_offset;
308
309         if (before == NULL) {
310                 e->offset = table->size - entry->next_offset;
311
312                 return 0;
313         }
314
315         entry_before = before->data;
316
317         /*
318          * We've just insterted a new entry. All references before it
319          * should be bumped accordingly.
320          */
321         for (list = table->entries; list != before; list = list->next) {
322                 tmp = list->data;
323
324                 if (!is_jump(tmp))
325                         continue;
326
327                 t = (struct xt_standard_target *)ipt_get_target(tmp->entry);
328
329                 if (t->verdict >= entry_before->offset)
330                         t->verdict += entry->next_offset;
331         }
332
333         update_offsets(table);
334
335         return 0;
336 }
337
338 static int remove_table_entry(struct connman_iptables *table,
339                                 struct connman_iptables_entry *entry)
340 {
341         int removed = 0;
342
343         table->num_entries--;
344         table->size -= entry->entry->next_offset;
345         removed = entry->entry->next_offset;
346
347         g_free(entry->entry);
348
349         table->entries = g_list_remove(table->entries, entry);
350
351         return removed;
352 }
353
354 static int iptables_flush_chain(struct connman_iptables *table,
355                                                 char *name)
356 {
357         GList *chain_head, *chain_tail, *list, *next;
358         struct connman_iptables_entry *entry;
359         int builtin, removed = 0;
360
361         chain_head = find_chain_head(table, name);
362         if (chain_head == NULL)
363                 return -EINVAL;
364
365         chain_tail = find_chain_tail(table, name);
366         if (chain_tail == NULL)
367                 return -EINVAL;
368
369         entry = chain_head->data;
370         builtin = entry->builtin;
371
372         if (builtin >= 0)
373                 list = chain_head;
374         else
375                 list = chain_head->next;
376
377         if (list == chain_tail->prev)
378                 return 0;
379
380         while (list != chain_tail->prev) {
381                 entry = list->data;
382                 next = g_list_next(list);
383
384                 removed += remove_table_entry(table, entry);
385
386                 list = next;
387         }
388
389         if (builtin >= 0) {
390                 struct connman_iptables_entry *e;
391
392                 entry = list->data;
393
394                 entry->builtin = builtin;
395
396                 table->underflow[builtin] -= removed;
397
398                 for (list = chain_tail; list; list = list->next) {
399                         e = list->data;
400
401                         builtin = e->builtin;
402                         if (builtin < 0)
403                                 continue;
404
405                         table->hook_entry[builtin] -= removed;
406                         table->underflow[builtin] -= removed;
407                 }
408         }
409
410         update_offsets(table);
411
412         return 0;
413 }
414
415 static int iptables_add_chain(struct connman_iptables *table,
416                                         char *name)
417 {
418         GList *last;
419         struct ipt_entry *entry_head;
420         struct ipt_entry *entry_return;
421         struct error_target *error;
422         struct ipt_standard_target *standard;
423         u_int16_t entry_head_size, entry_return_size;
424
425         last = g_list_last(table->entries);
426
427         /*
428          * An empty chain is composed of:
429          * - A head entry, with no match and an error target.
430          *   The error target data is the chain name.
431          * - A tail entry, with no match and a standard target.
432          *   The standard target verdict is XT_RETURN (return to the
433          *   caller).
434          */
435
436         /* head entry */
437         entry_head_size = sizeof(struct ipt_entry) +
438                                 sizeof(struct error_target);
439         entry_head = g_try_malloc0(entry_head_size);
440         if (entry_head == NULL)
441                 goto err_head;
442
443         memset(entry_head, 0, entry_head_size);
444
445         entry_head->target_offset = sizeof(struct ipt_entry);
446         entry_head->next_offset = entry_head_size;
447
448         error = (struct error_target *) entry_head->elems;
449         strcpy(error->t.u.user.name, IPT_ERROR_TARGET);
450         error->t.u.user.target_size = ALIGN(sizeof(struct error_target));
451         strcpy(error->error, name);
452
453         if (iptables_add_entry(table, entry_head, last, -1) < 0)
454                 goto err_head;
455
456         /* tail entry */
457         entry_return_size = sizeof(struct ipt_entry) +
458                                 sizeof(struct ipt_standard_target);
459         entry_return = g_try_malloc0(entry_return_size);
460         if (entry_return == NULL)
461                 goto err;
462
463         memset(entry_return, 0, entry_return_size);
464
465         entry_return->target_offset = sizeof(struct ipt_entry);
466         entry_return->next_offset = entry_return_size;
467
468         standard = (struct ipt_standard_target *) entry_return->elems;
469         standard->target.u.user.target_size =
470                                 ALIGN(sizeof(struct ipt_standard_target));
471         standard->verdict = XT_RETURN;
472
473         if (iptables_add_entry(table, entry_return, last, -1) < 0)
474                 goto err;
475
476         return 0;
477
478 err:
479         g_free(entry_return);
480 err_head:
481         g_free(entry_head);
482
483         return -ENOMEM;
484 }
485
486 static int iptables_delete_chain(struct connman_iptables *table, char *name)
487 {
488         struct connman_iptables_entry *entry;
489         GList *chain_head, *chain_tail;
490
491         chain_head = find_chain_head(table, name);
492         if (chain_head == NULL)
493                 return -EINVAL;
494
495         entry = chain_head->data;
496
497         /* We cannot remove builtin chain */
498         if (entry->builtin >= 0)
499                 return -EINVAL;
500
501         chain_tail = find_chain_tail(table, name);
502         if (chain_tail == NULL)
503                 return -EINVAL;
504
505         /* Chain must be flushed */
506         if (chain_head->next != chain_tail->prev)
507                 return -EINVAL;
508
509         remove_table_entry(table, entry);
510
511         entry = chain_tail->prev->data;
512         remove_table_entry(table, entry);
513
514         update_offsets(table);
515
516         return 0;
517 }
518
519 static struct ipt_entry *
520 new_rule(struct connman_iptables *table, struct ipt_ip *ip,
521                 char *target_name, struct xtables_target *xt_t,
522                 char *match_name, struct xtables_match *xt_m)
523 {
524         struct ipt_entry *new_entry;
525         size_t match_size, target_size;
526         int is_builtin = is_builtin_target(target_name);
527
528         if (xt_m)
529                 match_size = xt_m->m->u.match_size;
530         else
531                 match_size = 0;
532
533         if (xt_t)
534                 target_size = ALIGN(xt_t->t->u.target_size);
535         else
536                 target_size = ALIGN(sizeof(struct xt_standard_target));
537
538         new_entry = g_try_malloc0(sizeof(struct ipt_entry) + target_size +
539                                                                 match_size);
540         if (new_entry == NULL)
541                 return NULL;
542
543         memcpy(&new_entry->ip, ip, sizeof(struct ipt_ip));
544
545         new_entry->target_offset = sizeof(struct ipt_entry) + match_size;
546         new_entry->next_offset = sizeof(struct ipt_entry) + target_size +
547                                                                 match_size;
548         if (xt_m) {
549                 struct xt_entry_match *entry_match;
550
551                 entry_match = (struct xt_entry_match *)new_entry->elems;
552                 memcpy(entry_match, xt_m->m, match_size);
553         }
554
555         if (xt_t) {
556                 struct xt_entry_target *entry_target;
557
558                 if (is_builtin) {
559                         struct xt_standard_target *target;
560
561                         target = (struct xt_standard_target *)(xt_t->t);
562                         strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
563                         target->verdict = target_to_verdict(target_name);
564                 }
565
566                 entry_target = ipt_get_target(new_entry);
567                 memcpy(entry_target, xt_t->t, target_size);
568         } else {
569                 struct connman_iptables_entry *target_rule;
570                 struct xt_standard_target *target;
571                 GList *chain_head;
572
573                 /*
574                  * This is a user defined target, i.e. a chain jump.
575                  * We search for the chain head, and the target verdict
576                  * is the first rule's offset on this chain.
577                  * The offset is from the beginning of the table.
578                  */
579
580                 chain_head = find_chain_head(table, target_name);
581                 if (chain_head == NULL || chain_head->next == NULL) {
582                         g_free(new_entry);
583                         return NULL;
584                 }
585
586                 target_rule = chain_head->next->data;
587
588                 target = (struct xt_standard_target *)ipt_get_target(new_entry);
589                 strcpy(target->target.u.user.name, IPT_STANDARD_TARGET);
590                 target->target.u.user.target_size = target_size;
591                 target->verdict = target_rule->offset;
592         }
593
594         return new_entry;
595 }
596
597 static void update_hooks(struct connman_iptables *table, GList *chain_head,
598                                 struct ipt_entry *entry)
599 {
600         GList *list;
601         struct connman_iptables_entry *head, *e;
602         int builtin;
603
604         if (chain_head == NULL)
605                 return;
606
607         head = chain_head->data;
608
609         builtin = head->builtin;
610         if (builtin < 0)
611                 return;
612
613         table->underflow[builtin] += entry->next_offset;
614
615         for (list = chain_head->next; list; list = list->next) {
616                 e = list->data;
617
618                 builtin = e->builtin;
619                 if (builtin < 0)
620                         continue;
621
622                 table->hook_entry[builtin] += entry->next_offset;
623                 table->underflow[builtin] += entry->next_offset;
624         }
625 }
626
627 static struct ipt_entry *prepare_rule_inclusion(struct connman_iptables *table,
628                                 struct ipt_ip *ip, char *chain_name,
629                                 char *target_name, struct xtables_target *xt_t,
630                                 char *match_name, struct xtables_match *xt_m,
631                                 int *builtin)
632 {
633         GList *chain_tail, *chain_head;
634         struct ipt_entry *new_entry;
635         struct connman_iptables_entry *head;
636
637         chain_head = find_chain_head(table, chain_name);
638         if (chain_head == NULL)
639                 return NULL;
640
641         chain_tail = find_chain_tail(table, chain_name);
642         if (chain_tail == NULL)
643                 return NULL;
644
645         new_entry = new_rule(table, ip, target_name, xt_t, match_name, xt_m);
646         if (new_entry == NULL)
647                 return NULL;
648
649         update_hooks(table, chain_head, new_entry);
650
651         /*
652          * If the chain is builtin, and does not have any rule,
653          * then the one that we're inserting is becoming the head
654          * and thus needs the builtin flag.
655          */
656         head = chain_head->data;
657         if (head->builtin < 0)
658                 *builtin = -1;
659         else if (chain_head == chain_tail->prev) {
660                 *builtin = head->builtin;
661                 head->builtin = -1;
662         }
663
664         return new_entry;
665 }
666
667 static int
668 iptables_add_rule(struct connman_iptables *table,
669                                 struct ipt_ip *ip, char *chain_name,
670                                 char *target_name, struct xtables_target *xt_t,
671                                 char *match_name, struct xtables_match *xt_m)
672 {
673         GList *chain_tail;
674         struct ipt_entry *new_entry;
675         int builtin = -1, ret;
676
677         DBG("");
678
679         chain_tail = find_chain_tail(table, chain_name);
680         if (chain_tail == NULL)
681                 return -EINVAL;
682
683         new_entry = prepare_rule_inclusion(table, ip, chain_name,
684                         target_name, xt_t, match_name, xt_m, &builtin);
685         if (new_entry == NULL)
686                 return -EINVAL;
687
688         ret = iptables_add_entry(table, new_entry, chain_tail->prev, builtin);
689         if (ret < 0)
690                 g_free(new_entry);
691
692         return ret;
693 }
694
695 static int iptables_insert_rule(struct connman_iptables *table,
696                                 struct ipt_ip *ip, char *chain_name,
697                                 char *target_name, struct xtables_target *xt_t,
698                                 char *match_name, struct xtables_match *xt_m)
699 {
700         struct ipt_entry *new_entry;
701         int builtin = -1, ret;
702         GList *chain_head;
703
704         chain_head = find_chain_head(table, chain_name);
705         if (chain_head == NULL)
706                 return -EINVAL;
707
708         new_entry = prepare_rule_inclusion(table, ip, chain_name,
709                         target_name, xt_t, match_name, xt_m, &builtin);
710         if (new_entry == NULL)
711                 return -EINVAL;
712
713         ret = iptables_add_entry(table, new_entry, chain_head->next, builtin);
714         if (ret < 0)
715                 g_free(new_entry);
716
717         return ret;
718 }
719
720 static struct ipt_replace *
721 iptables_blob(struct connman_iptables *table)
722 {
723         struct ipt_replace *r;
724         GList *list;
725         struct connman_iptables_entry *e;
726         unsigned char *entry_index;
727
728         r = g_try_malloc0(sizeof(struct ipt_replace) + table->size);
729         if (r == NULL)
730                 return NULL;
731
732         memset(r, 0, sizeof(*r) + table->size);
733
734         r->counters = g_try_malloc0(sizeof(struct xt_counters)
735                                 * table->old_entries);
736         if (r->counters == NULL) {
737                 g_free(r);
738                 return NULL;
739         }
740
741         strcpy(r->name, table->info->name);
742         r->num_entries = table->num_entries;
743         r->size = table->size;
744
745         r->num_counters = table->old_entries;
746         r->valid_hooks  = table->info->valid_hooks;
747
748         memcpy(r->hook_entry, table->hook_entry, sizeof(table->hook_entry));
749         memcpy(r->underflow, table->underflow, sizeof(table->underflow));
750
751         entry_index = (unsigned char *)r->entries;
752         for (list = table->entries; list; list = list->next) {
753                 e = list->data;
754
755                 memcpy(entry_index, e->entry, e->entry->next_offset);
756                 entry_index += e->entry->next_offset;
757         }
758
759         return r;
760 }
761
762 static void dump_ip(struct ipt_entry *entry)
763 {
764         struct ipt_ip *ip = &entry->ip;
765         char ip_string[INET6_ADDRSTRLEN];
766         char ip_mask[INET6_ADDRSTRLEN];
767
768         if (strlen(ip->iniface))
769                 connman_info("\tin %s", ip->iniface);
770
771         if (strlen(ip->outiface))
772                 connman_info("\tout %s", ip->outiface);
773
774         if (inet_ntop(AF_INET, &ip->src, ip_string, INET6_ADDRSTRLEN) != NULL &&
775                         inet_ntop(AF_INET, &ip->smsk,
776                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
777                 connman_info("\tsrc %s/%s", ip_string, ip_mask);
778
779         if (inet_ntop(AF_INET, &ip->dst, ip_string, INET6_ADDRSTRLEN) != NULL &&
780                         inet_ntop(AF_INET, &ip->dmsk,
781                                         ip_mask, INET6_ADDRSTRLEN) != NULL)
782                 connman_info("\tdst %s/%s", ip_string, ip_mask);
783 }
784
785 static void dump_target(struct connman_iptables *table,
786                                 struct ipt_entry *entry)
787
788 {
789         struct xtables_target *xt_t;
790         struct xt_entry_target *target;
791
792         target = ipt_get_target(entry);
793
794         if (!strcmp(target->u.user.name, IPT_STANDARD_TARGET)) {
795                 struct xt_standard_target *t;
796
797                 t = (struct xt_standard_target *)target;
798
799                 switch (t->verdict) {
800                 case XT_RETURN:
801                         connman_info("\ttarget RETURN");
802                         break;
803
804                 case -NF_ACCEPT - 1:
805                         connman_info("\ttarget ACCEPT");
806                         break;
807
808                 case -NF_DROP - 1:
809                         connman_info("\ttarget DROP");
810                         break;
811
812                 case -NF_QUEUE - 1:
813                         connman_info("\ttarget QUEUE");
814                         break;
815
816                 case -NF_STOP - 1:
817                         connman_info("\ttarget STOP");
818                         break;
819
820                 default:
821                         connman_info("\tJUMP @%p (0x%x)",
822                                 (char*)table->blob_entries->entrytable +
823                                 t->verdict, t->verdict);
824                         break;
825                 }
826
827                 xt_t = xtables_find_target(IPT_STANDARD_TARGET,
828                                                 XTF_LOAD_MUST_SUCCEED);
829
830                 if(xt_t->print != NULL)
831                         xt_t->print(NULL, target, 1);
832         } else {
833                 xt_t = xtables_find_target(target->u.user.name, XTF_TRY_LOAD);
834                 if (xt_t == NULL) {
835                         connman_info("\ttarget %s", target->u.user.name);
836                         return;
837                 }
838
839                 if(xt_t->print != NULL) {
840                         connman_info("\ttarget ");
841                         xt_t->print(NULL, target, 1);
842                 }
843         }
844 }
845
846 static void dump_match(struct connman_iptables *table, struct ipt_entry *entry)
847 {
848         struct xtables_match *xt_m;
849         struct xt_entry_match *match;
850
851         if (entry->elems == (unsigned char *)entry + entry->target_offset)
852                 return;
853
854         match = (struct xt_entry_match *) entry->elems;
855
856         if (!strlen(match->u.user.name))
857                 return;
858
859         xt_m = xtables_find_match(match->u.user.name, XTF_TRY_LOAD, NULL);
860         if (xt_m == NULL)
861                 goto out;
862
863         if(xt_m->print != NULL) {
864                 connman_info("\tmatch ");
865                 xt_m->print(NULL, match, 1);
866
867                 return;
868         }
869
870 out:
871         connman_info("\tmatch %s", match->u.user.name);
872
873 }
874
875 static int dump_entry(struct ipt_entry *entry,
876                                 struct connman_iptables *table)
877 {
878         struct xt_entry_target *target;
879         unsigned int offset;
880         int builtin;
881
882         offset = (char *)entry - (char *)table->blob_entries->entrytable;
883         target = ipt_get_target(entry);
884         builtin = is_hook_entry(table, entry);
885
886         if (entry_to_offset(table, entry) + entry->next_offset ==
887                                         table->blob_entries->size) {
888                 connman_info("End of CHAIN 0x%x", offset);
889                 return 0;
890         }
891
892         if (!strcmp(target->u.user.name, IPT_ERROR_TARGET)) {
893                 connman_info("USER CHAIN (%s) %p  match %p  target %p  size %d",
894                         target->data, entry, entry->elems,
895                         (char *)entry + entry->target_offset,
896                                 entry->next_offset);
897
898                 return 0;
899         } else if (builtin >= 0) {
900                 connman_info("CHAIN (%s) %p  match %p  target %p  size %d",
901                         hooknames[builtin], entry, entry->elems,
902                         (char *)entry + entry->target_offset,
903                                 entry->next_offset);
904         } else {
905                 connman_info("RULE %p  match %p  target %p  size %d", entry,
906                         entry->elems,
907                         (char *)entry + entry->target_offset,
908                                 entry->next_offset);
909         }
910
911         dump_match(table, entry);
912         dump_target(table, entry);
913         dump_ip(entry);
914
915         return 0;
916 }
917
918 static void iptables_dump(struct connman_iptables *table)
919 {
920         connman_info("%s valid_hooks=0x%08x, num_entries=%u, size=%u",
921                         table->info->name,
922                         table->info->valid_hooks, table->info->num_entries,
923                                 table->info->size);
924
925         ENTRY_ITERATE(table->blob_entries->entrytable,
926                         table->blob_entries->size,
927                         dump_entry, table);
928
929 }
930
931 static int iptables_get_entries(struct connman_iptables *table)
932 {
933         socklen_t entry_size;
934
935         entry_size = sizeof(struct ipt_get_entries) + table->info->size;
936
937         return getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_ENTRIES,
938                                 table->blob_entries, &entry_size);
939 }
940
941 static int iptables_replace(struct connman_iptables *table,
942                                         struct ipt_replace *r)
943 {
944         return setsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_SET_REPLACE, r,
945                          sizeof(*r) + r->size);
946 }
947
948 static int add_entry(struct ipt_entry *entry, struct connman_iptables *table)
949 {
950         struct ipt_entry *new_entry;
951         int builtin;
952
953         new_entry = g_try_malloc0(entry->next_offset);
954         if (new_entry == NULL)
955                 return -ENOMEM;
956
957         memcpy(new_entry, entry, entry->next_offset);
958
959         builtin = is_hook_entry(table, entry);
960
961         return iptables_add_entry(table, new_entry, NULL, builtin);
962 }
963
964 static void table_cleanup(struct connman_iptables *table)
965 {
966         GList *list;
967         struct connman_iptables_entry *entry;
968
969         close(table->ipt_sock);
970
971         for (list = table->entries; list; list = list->next) {
972                 entry = list->data;
973
974                 g_free(entry->entry);
975                 g_free(entry);
976         }
977
978         g_list_free(table->entries);
979         g_free(table->info);
980         g_free(table->blob_entries);
981         g_free(table);
982 }
983
984 static struct connman_iptables *iptables_init(char *table_name)
985 {
986         struct connman_iptables *table;
987         socklen_t s;
988
989         DBG("%s", table_name);
990
991         table = g_hash_table_lookup(table_hash, table_name);
992         if (table != NULL)
993                 return table;
994
995         table = g_try_new0(struct connman_iptables, 1);
996         if (table == NULL)
997                 return NULL;
998
999         table->info = g_try_new0(struct ipt_getinfo, 1);
1000         if (table->info == NULL)
1001                 goto err;
1002
1003         table->ipt_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
1004         if (table->ipt_sock < 0)
1005                 goto err;
1006
1007         s = sizeof(*table->info);
1008         strcpy(table->info->name, table_name);
1009         if (getsockopt(table->ipt_sock, IPPROTO_IP, IPT_SO_GET_INFO,
1010                                                 table->info, &s) < 0)
1011                 goto err;
1012
1013         table->blob_entries = g_try_malloc0(sizeof(struct ipt_get_entries) +
1014                                                 table->info->size);
1015         if (table->blob_entries == NULL)
1016                 goto err;
1017
1018         strcpy(table->blob_entries->name, table_name);
1019         table->blob_entries->size = table->info->size;
1020
1021         if (iptables_get_entries(table) < 0)
1022                 goto err;
1023
1024         table->num_entries = 0;
1025         table->old_entries = table->info->num_entries;
1026         table->size = 0;
1027
1028         memcpy(table->underflow, table->info->underflow,
1029                                 sizeof(table->info->underflow));
1030         memcpy(table->hook_entry, table->info->hook_entry,
1031                                 sizeof(table->info->hook_entry));
1032
1033         ENTRY_ITERATE(table->blob_entries->entrytable,
1034                         table->blob_entries->size,
1035                                 add_entry, table);
1036
1037         g_hash_table_insert(table_hash, g_strdup(table_name), table);
1038
1039         return table;
1040
1041 err:
1042
1043         table_cleanup(table);
1044
1045         return NULL;
1046 }
1047
1048 static struct option iptables_opts[] = {
1049         {.name = "append",        .has_arg = 1, .val = 'A'},
1050         {.name = "flush-chain",   .has_arg = 1, .val = 'F'},
1051         {.name = "insert",        .has_arg = 1, .val = 'I'},
1052         {.name = "list",          .has_arg = 2, .val = 'L'},
1053         {.name = "new-chain",     .has_arg = 1, .val = 'N'},
1054         {.name = "delete-chain",  .has_arg = 1, .val = 'X'},
1055         {.name = "destination",   .has_arg = 1, .val = 'd'},
1056         {.name = "in-interface",  .has_arg = 1, .val = 'i'},
1057         {.name = "jump",          .has_arg = 1, .val = 'j'},
1058         {.name = "match",         .has_arg = 1, .val = 'm'},
1059         {.name = "out-interface", .has_arg = 1, .val = 'o'},
1060         {.name = "source",        .has_arg = 1, .val = 's'},
1061         {.name = "table",         .has_arg = 1, .val = 't'},
1062         {NULL},
1063 };
1064
1065 struct xtables_globals iptables_globals = {
1066         .option_offset = 0,
1067         .opts = iptables_opts,
1068         .orig_opts = iptables_opts,
1069 };
1070
1071 static int iptables_command(int argc, char *argv[])
1072 {
1073         struct connman_iptables *table;
1074         struct xtables_match *xt_m;
1075         struct xtables_target *xt_t;
1076         struct ipt_ip ip;
1077         char *table_name, *chain, *new_chain, *match_name, *target_name;
1078         char *flush_chain, *delete_chain;
1079         int c, ret, in_len, out_len;
1080         size_t size;
1081         gboolean dump, invert, insert;
1082         struct in_addr src, dst;
1083
1084         if (argc == 0)
1085                 return -EINVAL;
1086
1087         dump = FALSE;
1088         invert = FALSE;
1089         insert = FALSE;
1090         table_name = chain = new_chain = match_name = target_name = NULL;
1091         flush_chain = delete_chain = NULL;
1092         memset(&ip, 0, sizeof(struct ipt_ip));
1093         table = NULL;
1094         xt_m = NULL;
1095         xt_t = NULL;
1096         ret = 0;
1097
1098         optind = 0;
1099
1100         while ((c = getopt_long(argc, argv, "-A:F:I:L::N:X:d:j:i:m:o:s:t:",
1101                                         iptables_globals.opts, NULL)) != -1) {
1102                 switch (c) {
1103                 case 'A':
1104                         /* It is either -A, -D or -I at once */
1105                         if (chain)
1106                                 goto out;
1107
1108                         chain = optarg;
1109                         break;
1110
1111                 case 'F':
1112                         flush_chain = optarg;
1113                         break;
1114
1115                 case 'I':
1116                         /* It is either -A, -D or -I at once */
1117                         if (chain)
1118                                 goto out;
1119
1120                         chain = optarg;
1121                         insert = TRUE;
1122                         break;
1123
1124                 case 'L':
1125                         dump = TRUE;
1126                         break;
1127
1128                 case 'N':
1129                         new_chain = optarg;
1130                         break;
1131
1132                 case 'X':
1133                         delete_chain = optarg;
1134                         break;
1135
1136                 case 'd':
1137                         if (!inet_pton(AF_INET, optarg, &dst))
1138                                 break;
1139
1140                         ip.dst = dst;
1141                         inet_pton(AF_INET, "255.255.255.255", &ip.dmsk);
1142
1143                         if (invert)
1144                                 ip.invflags |= IPT_INV_DSTIP;
1145
1146                         break;
1147
1148                 case 'i':
1149                         in_len = strlen(optarg);
1150
1151                         if (in_len + 1 > IFNAMSIZ)
1152                                 break;
1153
1154                         strcpy(ip.iniface, optarg);
1155                         memset(ip.iniface_mask, 0xff, in_len + 1);
1156
1157                         if (invert)
1158                                 ip.invflags |= IPT_INV_VIA_IN;
1159
1160                         break;
1161
1162                 case 'j':
1163                         target_name = optarg;
1164                         xt_t = xtables_find_target(target_name, XTF_TRY_LOAD);
1165
1166                         if (xt_t == NULL)
1167                                 break;
1168
1169                         size = ALIGN(sizeof(struct ipt_entry_target)) +
1170                                                                 xt_t->size;
1171
1172                         xt_t->t = g_try_malloc0(size);
1173                         if (xt_t->t == NULL)
1174                                 goto out;
1175                         xt_t->t->u.target_size = size;
1176                         strcpy(xt_t->t->u.user.name, target_name);
1177                         xt_t->t->u.user.revision = xt_t->revision;
1178                         if (xt_t->init != NULL)
1179                                 xt_t->init(xt_t->t);
1180                         iptables_globals.opts =
1181                                 xtables_merge_options(
1182 #if XTABLES_VERSION_CODE > 5
1183                                                      iptables_globals.orig_opts,
1184 #endif
1185                                                      iptables_globals.opts,
1186                                                      xt_t->extra_opts,
1187                                                      &xt_t->option_offset);
1188                         if (iptables_globals.opts == NULL)
1189                                 goto out;
1190
1191                         break;
1192
1193                 case 'm':
1194                         match_name = optarg;
1195
1196                         xt_m = xtables_find_match(optarg, XTF_LOAD_MUST_SUCCEED, NULL);
1197                         size = ALIGN(sizeof(struct ipt_entry_match)) +
1198                                                                 xt_m->size;
1199                         xt_m->m = g_try_malloc0(size);
1200                         if (xt_m == NULL)
1201                                 goto out;
1202                         xt_m->m->u.match_size = size;
1203                         strcpy(xt_m->m->u.user.name, xt_m->name);
1204                         xt_m->m->u.user.revision = xt_m->revision;
1205                         if (xt_m->init != NULL)
1206                                 xt_m->init(xt_m->m);
1207                         if (xt_m != xt_m->next) {
1208                                 iptables_globals.opts =
1209                                 xtables_merge_options(
1210 #if XTABLES_VERSION_CODE > 5
1211                                                 iptables_globals.orig_opts,
1212 #endif
1213                                                 iptables_globals.opts,
1214                                                 xt_m->extra_opts,
1215                                                 &xt_m->option_offset);
1216                                 if (iptables_globals.opts == NULL)
1217                                         goto out;
1218                         }
1219
1220                         break;
1221
1222                 case 'o':
1223                         out_len = strlen(optarg);
1224
1225                         if (out_len + 1 > IFNAMSIZ)
1226                                 break;
1227
1228                         strcpy(ip.outiface, optarg);
1229                         memset(ip.outiface_mask, 0xff, out_len + 1);
1230
1231                         if (invert)
1232                                 ip.invflags |= IPT_INV_VIA_OUT;
1233
1234                         break;
1235
1236                 case 's':
1237                         if (!inet_pton(AF_INET, optarg, &src))
1238                                 break;
1239
1240                         ip.src = src;
1241                         inet_pton(AF_INET, "255.255.255.255", &ip.smsk);
1242
1243                         if (invert)
1244                                 ip.invflags |= IPT_INV_SRCIP;
1245
1246                         break;
1247
1248                 case 't':
1249                         table_name = optarg;
1250                         break;
1251
1252                 case 1:
1253                         if (optarg[0] == '!' && optarg[1] == '\0') {
1254                                 invert = TRUE;
1255                                 optarg[0] = '\0';
1256                                 continue;
1257                         }
1258
1259                         connman_error("Invalid option");
1260
1261                         ret = -EINVAL;
1262                         goto out;
1263
1264                 default:
1265                         if (xt_t == NULL || xt_t->parse == NULL ||
1266                             !xt_t->parse(c - xt_t->option_offset, argv, invert,
1267                                         &xt_t->tflags, NULL, &xt_t->t)) {
1268                                 if (xt_m == NULL || xt_m->parse == NULL)
1269                                         break;
1270
1271                                 xt_m->parse(c - xt_m->option_offset, argv,
1272                                         invert, &xt_m->mflags, NULL, &xt_m->m);
1273                         }
1274
1275                         break;
1276                 }
1277
1278                 invert = FALSE;
1279         }
1280
1281         if (table_name == NULL)
1282                 table_name = "filter";
1283
1284         table = iptables_init(table_name);
1285         if (table == NULL) {
1286                 ret = -EINVAL;
1287                 goto out;
1288         }
1289
1290         if (delete_chain != NULL) {
1291                 printf("Delete chain %s\n", delete_chain);
1292
1293                 iptables_delete_chain(table, delete_chain);
1294
1295                 goto out;
1296         }
1297
1298         if (dump) {
1299                 iptables_dump(table);
1300
1301                 ret = 0;
1302                 goto out;
1303         }
1304
1305         if (flush_chain) {
1306                 DBG("Flush chain %s", flush_chain);
1307
1308                 iptables_flush_chain(table, flush_chain);
1309
1310                 goto out;
1311         }
1312
1313         if (chain && new_chain) {
1314                 ret = -EINVAL;
1315                 goto out;
1316         }
1317
1318         if (new_chain) {
1319                 DBG("New chain %s", new_chain);
1320
1321                 ret = iptables_add_chain(table, new_chain);
1322                 goto out;
1323         }
1324
1325         if (chain) {
1326                 if (target_name == NULL)
1327                         return -1;
1328
1329                 if (insert == TRUE) {
1330                         DBG("Inserting %s to %s (match %s)",
1331                                         target_name, chain, match_name);
1332
1333                         ret = iptables_insert_rule(table, &ip, chain,
1334                                         target_name, xt_t, match_name, xt_m);
1335
1336                         goto out;
1337                 } else {
1338                         DBG("Adding %s to %s (match %s)",
1339                                         target_name, chain, match_name);
1340
1341                         ret = iptables_add_rule(table, &ip, chain,
1342                                         target_name, xt_t, match_name, xt_m);
1343
1344                         goto out;
1345                 }
1346         }
1347
1348 out:
1349         if (xt_t)
1350                 g_free(xt_t->t);
1351
1352         if (xt_m)
1353                 g_free(xt_m->m);
1354
1355         return ret;
1356 }
1357
1358 int __connman_iptables_command(const char *format, ...)
1359 {
1360         char **argv, **arguments, *command;
1361         int argc, i, ret;
1362         va_list args;
1363
1364         if (format == NULL)
1365                 return -EINVAL;
1366
1367         va_start(args, format);
1368
1369         command = g_strdup_vprintf(format, args);
1370
1371         va_end(args);
1372
1373         if (command == NULL)
1374                 return -ENOMEM;
1375
1376         arguments = g_strsplit_set(command, " ", -1);
1377
1378         for (argc = 0; arguments[argc]; argc++);
1379         ++argc;
1380
1381         DBG("command %s argc %d", command, argc);
1382
1383         argv = g_try_malloc0(argc * sizeof(char *));
1384         if (argv == NULL) {
1385                 g_free(command);
1386                 g_strfreev(arguments);
1387                 return -ENOMEM;
1388         }
1389
1390         argv[0] = "iptables";
1391         for (i = 1; i < argc; i++)
1392                 argv[i] = arguments[i - 1];
1393
1394         ret = iptables_command(argc, argv);
1395
1396         g_free(command);
1397         g_strfreev(arguments);
1398         g_free(argv);
1399
1400         return ret;
1401 }
1402
1403
1404 int __connman_iptables_commit(const char *table_name)
1405 {
1406         struct connman_iptables *table;
1407         struct ipt_replace *repl;
1408         int err;
1409
1410         DBG("%s", table_name);
1411
1412         table = g_hash_table_lookup(table_hash, table_name);
1413         if (table == NULL)
1414                 return -EINVAL;
1415
1416         repl = iptables_blob(table);
1417
1418         err = iptables_replace(table, repl);
1419
1420         g_free(repl->counters);
1421         g_free(repl);
1422
1423         if (err < 0)
1424             return err;
1425
1426         g_hash_table_remove(table_hash, table_name);
1427
1428         return 0;
1429 }
1430
1431 static void remove_table(gpointer user_data)
1432 {
1433         struct connman_iptables *table = user_data;
1434
1435         table_cleanup(table);
1436 }
1437
1438 int __connman_iptables_init(void)
1439 {
1440         DBG("");
1441
1442         table_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
1443                                                 g_free, remove_table);
1444
1445         xtables_init_all(&iptables_globals, NFPROTO_IPV4);
1446
1447         return 0;
1448
1449 }
1450
1451 void __connman_iptables_cleanup(void)
1452 {
1453         DBG("");
1454
1455         g_hash_table_destroy(table_hash);
1456
1457         xtables_free_opts(1);
1458 }