iptables-xml.c 16.2 KB
Newer Older
1
2
3
4
5
6
7
/* Code to convert iptables-save format to xml format,
 * (C) 2006 Ufo Mechanic <azez@ufomechanic.net>
 * based on iptables-restore (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
 * based on previous code from Rusty Russell <rusty@linuxcare.com.au>
 *
 * This code is distributed under the terms of GNU GPL v2
 */
8
#include "config.h"
9
#include <getopt.h>
10
#include <errno.h>
11
12
13
14
15
16
17
18
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "iptables.h"
#include "libiptc/libiptc.h"
#include "xtables-multi.h"
#include <xtables.h>
19
#include "xshared.h"
20
21
22

struct xtables_globals iptables_xml_globals = {
	.option_offset = 0,
23
	.program_version = PACKAGE_VERSION,
24
25
26
27
28
29
30
31
	.program_name = "iptables-xml",
};
#define prog_name iptables_xml_globals.program_name
#define prog_vers iptables_xml_globals.program_version

static void print_usage(const char *name, const char *version)
	    __attribute__ ((noreturn));

32
static int verbose;
33
/* Whether to combine actions of sequential rules with identical conditions */
34
static int combine;
35
/* Keeping track of external matches and targets.  */
36
static const struct option options[] = {
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
	{"verbose", 0, NULL, 'v'},
	{"combine", 0, NULL, 'c'},
	{"help", 0, NULL, 'h'},
	{ .name = NULL }
};

static void
print_usage(const char *name, const char *version)
{
	fprintf(stderr, "Usage: %s [-c] [-v] [-h]\n"
		"          [--combine ]\n"
		"	   [ --verbose ]\n" "	   [ --help ]\n", name);

	exit(1);
}

#define XT_CHAIN_MAXNAMELEN XT_TABLE_MAXNAMELEN
static char closeActionTag[XT_TABLE_MAXNAMELEN + 1];
static char closeRuleTag[XT_TABLE_MAXNAMELEN + 1];
static char curTable[XT_TABLE_MAXNAMELEN + 1];
static char curChain[XT_CHAIN_MAXNAMELEN + 1];

struct chain {
	char *chain;
	char *policy;
	struct xt_counters count;
	int created;
};

#define maxChains 10240		/* max chains per table */
static struct chain chains[maxChains];
68
static int nextChain;
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210

/* like puts but with xml encoding */
static void
xmlEncode(char *text)
{
	while (text && *text) {
		if ((unsigned char) (*text) >= 127)
			printf("&#%d;", (unsigned char) (*text));
		else if (*text == '&')
			printf("&amp;");
		else if (*text == '<')
			printf("&lt;");
		else if (*text == '>')
			printf("&gt;");
		else if (*text == '"')
			printf("&quot;");
		else
			putchar(*text);
		text++;
	}
}

/* Output text as a comment, avoiding a double hyphen */
static void
xmlCommentEscape(char *comment)
{
	int h_count = 0;

	while (comment && *comment) {
		if (*comment == '-') {
			h_count++;
			if (h_count >= 2) {
				h_count = 0;
				putchar(' ');
			}
			putchar('*');
		}
		/* strip trailing newline */
		if (*comment == '\n' && *(comment + 1) == 0);
		else
			putchar(*comment);
		comment++;
	}
}

static void
xmlComment(char *comment)
{
	printf("<!-- ");
	xmlCommentEscape(comment);
	printf(" -->\n");
}

static void
xmlAttrS(char *name, char *value)
{
	printf("%s=\"", name);
	xmlEncode(value);
	printf("\" ");
}

static void
xmlAttrI(char *name, long long int num)
{
	printf("%s=\"%lld\" ", name, num);
}

static void
closeChain(void)
{
	if (curChain[0] == 0)
		return;

	if (closeActionTag[0])
		printf("%s\n", closeActionTag);
	closeActionTag[0] = 0;
	if (closeRuleTag[0])
		printf("%s\n", closeRuleTag);
	closeRuleTag[0] = 0;
	if (curChain[0])
		printf("    </chain>\n");
	curChain[0] = 0;
	//lastRule[0]=0;
}

static void
openChain(char *chain, char *policy, struct xt_counters *ctr, char close)
{
	closeChain();

	strncpy(curChain, chain, XT_CHAIN_MAXNAMELEN);
	curChain[XT_CHAIN_MAXNAMELEN] = '\0';

	printf("    <chain ");
	xmlAttrS("name", curChain);
	if (strcmp(policy, "-") != 0)
		xmlAttrS("policy", policy);
	xmlAttrI("packet-count", (unsigned long long) ctr->pcnt);
	xmlAttrI("byte-count", (unsigned long long) ctr->bcnt);
	if (close) {
		printf("%c", close);
		curChain[0] = 0;
	}
	printf(">\n");
}

static int
existsChain(char *chain)
{
	/* open a saved chain */
	int c = 0;

	if (0 == strcmp(curChain, chain))
		return 1;
	for (c = 0; c < nextChain; c++)
		if (chains[c].chain && strcmp(chains[c].chain, chain) == 0)
			return 1;
	return 0;
}

static void
needChain(char *chain)
{
	/* open a saved chain */
	int c = 0;

	if (0 == strcmp(curChain, chain))
		return;

	for (c = 0; c < nextChain; c++)
		if (chains[c].chain && strcmp(chains[c].chain, chain) == 0) {
			openChain(chains[c].chain, chains[c].policy,
				  &(chains[c].count), '\0');
			/* And, mark it as done so we don't create 
			   an empty chain at table-end time */
			chains[c].created = 1;
		}
}

static void
saveChain(char *chain, char *policy, struct xt_counters *ctr)
{
211
	if (nextChain >= maxChains)
212
213
214
		xtables_error(PARAMETER_PROBLEM,
			   "%s: line %u chain name invalid\n",
			   prog_name, line);
215

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
	chains[nextChain].chain = strdup(chain);
	chains[nextChain].policy = strdup(policy);
	chains[nextChain].count = *ctr;
	chains[nextChain].created = 0;
	nextChain++;
}

static void
finishChains(void)
{
	int c;

	for (c = 0; c < nextChain; c++)
		if (!chains[c].created) {
			openChain(chains[c].chain, chains[c].policy,
				  &(chains[c].count), '/');
			free(chains[c].chain);
			free(chains[c].policy);
		}
	nextChain = 0;
}

static void
closeTable(void)
{
	closeChain();
	finishChains();
	if (curTable[0])
		printf("  </table>\n");
	curTable[0] = 0;
}

static void
openTable(char *table)
{
	closeTable();

	strncpy(curTable, table, XT_TABLE_MAXNAMELEN);
	curTable[XT_TABLE_MAXNAMELEN] = '\0';

	printf("  <table ");
	xmlAttrS("name", curTable);
	printf(">\n");
}

// is char* -j --jump -g or --goto
static int
isTarget(char *arg)
{
	return ((arg)
		&& (strcmp((arg), "-j") == 0 || strcmp((arg), "--jump") == 0
		    || strcmp((arg), "-g") == 0
		    || strcmp((arg), "--goto") == 0));
}

// is it a terminating target like -j ACCEPT, etc
// (or I guess -j SNAT in nat table, but we don't check for that yet
static int
isTerminatingTarget(char *arg)
{
	return ((arg)
		&& (strcmp((arg), "ACCEPT") == 0
		    || strcmp((arg), "DROP") == 0
		    || strcmp((arg), "QUEUE") == 0
		    || strcmp((arg), "RETURN") == 0));
}

// part=-1 means do conditions, part=1 means do rules, part=0 means do both
static void
do_rule_part(char *leveltag1, char *leveltag2, int part, int argc,
	     char *argv[], int argvattr[])
{
	int i;
	int arg = 2;		// ignore leading -A <chain>
	char invert_next = 0;
	char *spacer = "";	// space when needed to assemble arguments
	char *level1 = NULL;
	char *level2 = NULL;
	char *leveli1 = "        ";
	char *leveli2 = "          ";

#define CLOSE_LEVEL(LEVEL) \
	do { \
		if (level ## LEVEL) printf("</%s>\n", \
		(leveltag ## LEVEL)?(leveltag ## LEVEL):(level ## LEVEL)); \
		level ## LEVEL=NULL;\
	} while(0)

#define OPEN_LEVEL(LEVEL,TAG) \
	do {\
		level ## LEVEL=TAG;\
		if (leveltag ## LEVEL) {\
			printf("%s<%s ", (leveli ## LEVEL), \
				(leveltag ## LEVEL));\
			xmlAttrS("type", (TAG)); \
		} else printf("%s<%s ", (leveli ## LEVEL), (level ## LEVEL)); \
	} while(0)

	if (part == 1) {	/* skip */
		/* use argvattr to tell which arguments were quoted 
		   to avoid comparing quoted arguments, like comments, to -j, */
		while (arg < argc && (argvattr[arg] || !isTarget(argv[arg])))
			arg++;
	}

	/* Before we start, if the first arg is -[^-] and not -m or -j or -g
	 * then start a dummy <match> tag for old style built-in matches.
	 * We would do this in any case, but no need if it would be empty.
	 * In the case of negation, we need to look at arg+1
	 */
	if (arg < argc && strcmp(argv[arg], "!") == 0)
		i = arg + 1;
	else
		i = arg;
	if (i < argc && argv[i][0] == '-' && !isTarget(argv[i])
	    && strcmp(argv[i], "-m") != 0) {
		OPEN_LEVEL(1, "match");
		printf(">\n");
	}
	while (arg < argc) {
		// If ! is followed by -* then apply to that else output as data
		// Stop, if we need to
		if (part == -1 && !argvattr[arg] && (isTarget(argv[arg]))) {
			break;
		} else if (!argvattr[arg] && strcmp(argv[arg], "!") == 0) {
			if ((arg + 1) < argc && argv[arg + 1][0] == '-')
				invert_next = '!';
			else
				printf("%s%s", spacer, argv[arg]);
			spacer = " ";
346
347
348
		} else if (!argvattr[arg] && isTarget(argv[arg]) &&
			   (arg + 1 < argc) &&
			   existsChain(argv[arg + 1])) {
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
			CLOSE_LEVEL(2);
			if (level1)
				printf("%s", leveli1);
			CLOSE_LEVEL(1);
			spacer = "";
			invert_next = 0;
			if (strcmp(argv[arg], "-g") == 0
			    || strcmp(argv[arg], "--goto") == 0) {
				/* goto user chain */
				OPEN_LEVEL(1, "goto");
				printf(">\n");
				arg++;
				OPEN_LEVEL(2, argv[arg]);
				printf("/>\n");
				level2 = NULL;
			} else {
				/* call user chain */
				OPEN_LEVEL(1, "call");
				printf(">\n");
				arg++;
				OPEN_LEVEL(2, argv[arg]);
				printf("/>\n");
				level2 = NULL;
			}
		} else if (!argvattr[arg]
			   && (isTarget(argv[arg])
			       || strcmp(argv[arg], "-m") == 0
			       || strcmp(argv[arg], "--module") == 0)) {
			if (!((1 + arg) < argc))
				// no args to -j, -m or -g, ignore & finish loop
				break;
			CLOSE_LEVEL(2);
			if (level1)
				printf("%s", leveli1);
			CLOSE_LEVEL(1);
			spacer = "";
			invert_next = 0;
			arg++;
			OPEN_LEVEL(1, (argv[arg]));
			// Optimize case, can we close this tag already?
			if ((arg + 1) >= argc || (!argvattr[arg + 1]
						  && (isTarget(argv[arg + 1])
						      || strcmp(argv[arg + 1],
								"-m") == 0
						      || strcmp(argv[arg + 1],
								"--module") ==
						      0))) {
				printf(" />\n");
				level1 = NULL;
			} else {
				printf(">\n");
			}
		} else if (!argvattr[arg] && argv[arg][0] == '-') {
			char *tag;
			CLOSE_LEVEL(2);
			// Skip past any -
			tag = argv[arg];
			while (*tag == '-' && *tag)
				tag++;

			spacer = "";
			OPEN_LEVEL(2, tag);
			if (invert_next)
				printf(" invert=\"1\"");
			invert_next = 0;

			// Optimize case, can we close this tag already?
			if (!((arg + 1) < argc)
			    || (argv[arg + 1][0] == '-' /* NOT QUOTED */ )) {
				printf(" />\n");
				level2 = NULL;
			} else {
				printf(">");
			}
		} else {	// regular data
			char *spaces = strchr(argv[arg], ' ');
			printf("%s", spacer);
			if (spaces || argvattr[arg])
				printf("&quot;");
			// if argv[arg] contains a space, enclose in quotes
			xmlEncode(argv[arg]);
			if (spaces || argvattr[arg])
				printf("&quot;");
			spacer = " ";
		}
		arg++;
	}
	CLOSE_LEVEL(2);
	if (level1)
		printf("%s", leveli1);
	CLOSE_LEVEL(1);
}

static int
443
compareRules(int newargc, char *newargv[], int oldargc, char *oldargv[])
444
{
445
446
447
448
449
450
451
	/* Compare arguments up to -j or -g for match.
	 * NOTE: We don't want to combine actions if there were no criteria
	 * in each rule, or rules didn't have an action.
	 * NOTE: Depends on arguments being in some kind of "normal" order which
	 * is the case when processing the ACTUAL output of actual iptables-save
	 * rather than a file merely in a compatible format.
	 */
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491

	unsigned int old = 0;
	unsigned int new = 0;

	int compare = 0;

	while (new < newargc && old < oldargc) {
		if (isTarget(oldargv[old]) && isTarget(newargv[new])) {
			/* if oldarg was a terminating action then it makes no sense
			 * to combine further actions into the same xml */
			if (((strcmp((oldargv[old]), "-j") == 0 
					|| strcmp((oldargv[old]), "--jump") == 0) 
				&& old+1 < oldargc
				&& isTerminatingTarget(oldargv[old+1]) )
			    || strcmp((oldargv[old]), "-g") == 0 
			    || strcmp((oldargv[old]), "--goto") == 0 ) {
				/* Previous rule had terminating action */	
				compare = 0;
			} else {
				compare = 1;
			}
			break;
		}
		// break when old!=new
		if (strcmp(oldargv[old], newargv[new]) != 0) {
			compare = 0;
			break;
		}

		old++;
		new++;
	}
	// We won't match unless both rules had a target. 
	// This means we don't combine target-less rules, which is good

	return compare == 1;
}

/* has a nice parsed rule starting with -A */
static void
492
493
do_rule(char *pcnt, char *bcnt, int argc, char *argv[], int argvattr[],
	int oldargc, char *oldargv[])
494
495
496
{
	/* are these conditions the same as the previous rule?
	 * If so, skip arg straight to -j or -g */
497
498
	if (combine && argc > 2 && !isTarget(argv[2]) &&
	    compareRules(argc, argv, oldargc, oldargv)) {
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
		xmlComment("Combine action from next rule");
	} else {

		if (closeActionTag[0]) {
			printf("%s\n", closeActionTag);
			closeActionTag[0] = 0;
		}
		if (closeRuleTag[0]) {
			printf("%s\n", closeRuleTag);
			closeRuleTag[0] = 0;
		}

		printf("      <rule ");
		//xmlAttrS("table",curTable); // not needed in full mode 
		//xmlAttrS("chain",argv[1]); // not needed in full mode 
		if (pcnt)
			xmlAttrS("packet-count", pcnt);
		if (bcnt)
			xmlAttrS("byte-count", bcnt);
		printf(">\n");

		strncpy(closeRuleTag, "      </rule>\n", XT_TABLE_MAXNAMELEN);
		closeRuleTag[XT_TABLE_MAXNAMELEN] = '\0';

		/* no point in writing out condition if there isn't one */
		if (argc >= 3 && !isTarget(argv[2])) {
			printf("       <conditions>\n");
			do_rule_part(NULL, NULL, -1, argc, argv, argvattr);
			printf("       </conditions>\n");
		}
	}
	/* Write out the action */
	//do_rule_part("action","arg",1,argc,argv,argvattr);
	if (!closeActionTag[0]) {
		printf("       <actions>\n");
		strncpy(closeActionTag, "       </actions>\n",
			XT_TABLE_MAXNAMELEN);
		closeActionTag[XT_TABLE_MAXNAMELEN] = '\0';
	}
	do_rule_part(NULL, NULL, 1, argc, argv, argvattr);
}

int
iptables_xml_main(int argc, char *argv[])
{
544
	struct argv_store last_rule = {}, cur_rule = {};
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
	char buffer[10240];
	int c;
	FILE *in;

	line = 0;

	xtables_set_params(&iptables_xml_globals);
	while ((c = getopt_long(argc, argv, "cvh", options, NULL)) != -1) {
		switch (c) {
		case 'c':
			combine = 1;
			break;
		case 'v':
			printf("xptables-xml\n");
			verbose = 1;
			break;
		case 'h':
562
			print_usage("iptables-xml", PACKAGE_VERSION);
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
			break;
		}
	}

	if (optind == argc - 1) {
		in = fopen(argv[optind], "re");
		if (!in) {
			fprintf(stderr, "Can't open %s: %s", argv[optind],
				strerror(errno));
			exit(1);
		}
	} else if (optind < argc) {
		fprintf(stderr, "Unknown arguments found on commandline");
		exit(1);
	} else
		in = stdin;

	printf("<iptables-rules version=\"1.0\">\n");

	/* Grab standard input. */
	while (fgets(buffer, sizeof(buffer), in)) {
		int ret = 0;

		line++;

		if (buffer[0] == '\n')
			continue;
		else if (buffer[0] == '#') {
			xmlComment(buffer);
			continue;
		}

		if (verbose) {
			printf("<!-- line %d ", line);
			xmlCommentEscape(buffer);
			printf(" -->\n");
		}

		if ((strcmp(buffer, "COMMIT\n") == 0) && (curTable[0])) {
			DEBUGP("Calling commit\n");
			closeTable();
			ret = 1;
		} else if ((buffer[0] == '*')) {
			/* New table */
			char *table;

			table = strtok(buffer + 1, " \t\n");
			DEBUGP("line %u, table '%s'\n", line, table);
611
			if (!table)
612
613
614
				xtables_error(PARAMETER_PROBLEM,
					   "%s: line %u table name invalid\n",
					   prog_name, line);
615

616
617
618
619
620
621
622
623
624
625
626
			openTable(table);

			ret = 1;
		} else if ((buffer[0] == ':') && (curTable[0])) {
			/* New chain. */
			char *policy, *chain;
			struct xt_counters count;
			char *ctrs;

			chain = strtok(buffer + 1, " \t\n");
			DEBUGP("line %u, chain '%s'\n", line, chain);
627
			if (!chain)
628
629
630
631
632
633
634
635
				xtables_error(PARAMETER_PROBLEM,
					   "%s: line %u chain name invalid\n",
					   prog_name, line);

			DEBUGP("Creating new chain '%s'\n", chain);

			policy = strtok(NULL, " \t\n");
			DEBUGP("line %u, policy '%s'\n", line, policy);
636
			if (!policy)
637
638
639
640
641
642
643
644
645
646
647
648
649
				xtables_error(PARAMETER_PROBLEM,
					   "%s: line %u policy invalid\n",
					   prog_name, line);

			ctrs = strtok(NULL, " \t\n");
			parse_counters(ctrs, &count);
			saveChain(chain, policy, &count);

			ret = 1;
		} else if (curTable[0]) {
			unsigned int a;
			char *pcnt = NULL;
			char *bcnt = NULL;
650
			char *parsestart = buffer;
651
652
			char *chain = NULL;

653
654
			tokenize_rule_counters(&parsestart, &pcnt, &bcnt, line);
			add_param_to_argv(&cur_rule, parsestart, line);
655
656

			DEBUGP("calling do_command4(%u, argv, &%s, handle):\n",
657
658
			       cur_rule.argc, curTable);
			debug_print_argv(&cur_rule);
659

660
661
662
663
664
665
			for (a = 1; a < cur_rule.argc; a++) {
				if (strcmp(cur_rule.argv[a - 1], "-A"))
					continue;
				chain = cur_rule.argv[a];
				break;
			}
666
667
668
669
670
			if (!chain) {
				fprintf(stderr, "%s: line %u failed - no chain found\n",
					prog_name, line);
				exit(1);
			}
671
			needChain(chain);// Should we explicitly look for -A
672
673
			do_rule(pcnt, bcnt, cur_rule.argc, cur_rule.argv,
				cur_rule.argvattr, last_rule.argc, last_rule.argv);
674

675
			save_argv(&last_rule, &cur_rule);
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
			ret = 1;
		}
		if (!ret) {
			fprintf(stderr, "%s: line %u failed\n",
				prog_name, line);
			exit(1);
		}
	}
	if (curTable[0]) {
		fprintf(stderr, "%s: COMMIT expected at line %u\n",
			prog_name, line + 1);
		exit(1);
	}

	fclose(in);
	printf("</iptables-rules>\n");
692
	free_argv(&last_rule);
693
694
695

	return 0;
}