-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtraffico.c
More file actions
585 lines (531 loc) · 17.9 KB
/
Copy pathtraffico.c
File metadata and controls
585 lines (531 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
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
492
493
494
495
496
497
498
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
#define _GNU_SOURCE
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <net/if.h>
#include <assert.h>
#include <argp.h>
#include <unistd.h>
#include <bpf/libbpf.h>
#include "api.h"
#include "api/dag.h"
#include "api/enforcement.h"
#include "api/input_parse.h"
#include "api/intent_bpf.h"
#include "chain.h"
#include "intent_bpf_loader.h"
const char *argp_program_version = TOOL_NAME " 0.6.0";
const char *argp_program_bug_address = "https://github.com/leodido/traffico/issues";
// Visibility attribute needed to override glibc's weak symbol
// when built with -fvisibility=hidden.
__attribute__((visibility("default")))
error_t argp_err_exit_status = 1;
const char argp_program_doc[] =
"\n"
"Isolate your host the eBPF way.\n"
"\v"
" INTENT MODE\n"
" - Intent permits: arp | dns/IP | tcp/IP[:PORT] | udp/IP[:PORT]\n"
" - Intent forbids: arp | dns/IP | tcp/IP:PORT | udp/IP:PORT\n"
" - Intent backend: Linux TC BPF egress only; try --dry-run --explain first\n"
"\n"
" PROGRAMS\n" PROGRAMS_DESCRIPTION;
const char OPT_VERBOSE_LONG[] = "verbose";
#define OPT_VERBOSE_KEY 'v'
const char OPT_IFNAME_LONG[] = "ifname";
#define OPT_IFNAME_KEY 'i'
const char OPT_IFNAME_ARG[] = "IFNAME";
const char OPT_ATTACH_LONG[] = "at";
#define OPT_ATTACH_KEY 0x80
const char OPT_ATTACH_ARG[] = "INGRESS|EGRESS";
#define OPT_NO_CLEANUP_KEY 0x81
const char OPT_NO_CLEANUP_LONG[] = "no-cleanup";
#define OPT_CHAIN_KEY 0x82
const char OPT_CHAIN_LONG[] = "chain";
const char OPT_CHAIN_ARG[] = "PROG:INPUT,...";
#define OPT_ALLOW_KEY 0x83
const char OPT_ALLOW_LONG[] = "allow";
const char OPT_ALLOW_ARG[] = "PERMIT";
#define OPT_PERMIT_KEY 0x84
const char OPT_PERMIT_LONG[] = "permit";
const char OPT_PERMIT_ARG[] = "PERMIT";
#define OPT_FORBID_KEY 0x85
const char OPT_FORBID_LONG[] = "forbid";
const char OPT_FORBID_ARG[] = "FORBID";
#define OPT_BLOCK_KEY 0x86
const char OPT_BLOCK_LONG[] = "block";
const char OPT_BLOCK_ARG[] = "FORBID";
#define OPT_DRY_RUN_KEY 0x87
const char OPT_DRY_RUN_LONG[] = "dry-run";
#define OPT_EXPLAIN_KEY 0x88
const char OPT_EXPLAIN_LONG[] = "explain";
const char OPT_EXPLAIN_ARG[] = "intent";
#define OPT_VERSION_KEY 0x89
const char OPT_VERSION_LONG[] = "version";
const struct argp_option argp_opts[] = {
{"OPTIONS", 0, 0, OPTION_DOC, 0, 0},
{OPT_VERBOSE_LONG, OPT_VERBOSE_KEY, NULL, 0, "Verbose debug output", -1},
{OPT_IFNAME_LONG, OPT_IFNAME_KEY, OPT_IFNAME_ARG, 0, "Interface to which to attach the filter\n(defaults to the default gateway interface)", 1},
{OPT_ATTACH_LONG, OPT_ATTACH_KEY, OPT_ATTACH_ARG, 0, "Where to attach the filter (defaults to egress)", 1},
{OPT_NO_CLEANUP_LONG, OPT_NO_CLEANUP_KEY, NULL, 0, "Do not detach the TC hook and filter at the exit", 1},
{OPT_CHAIN_LONG, OPT_CHAIN_KEY, OPT_CHAIN_ARG, 0, "Attach a chain of programs (e.g., allow_ipv4:10.0.0.1,allow_port:8080)", 1},
{OPT_ALLOW_LONG, OPT_ALLOW_KEY, OPT_ALLOW_ARG, 0, "Add an Intent permit", 1},
{OPT_PERMIT_LONG, OPT_PERMIT_KEY, OPT_PERMIT_ARG, 0, "Alias for --allow", 1},
{OPT_FORBID_LONG, OPT_FORBID_KEY, OPT_FORBID_ARG, 0, "Add an Intent forbid", 1},
{OPT_BLOCK_LONG, OPT_BLOCK_KEY, OPT_BLOCK_ARG, 0, "Alias for --forbid", 1},
{OPT_DRY_RUN_LONG, OPT_DRY_RUN_KEY, NULL, 0, "Validate Intent without attaching", 1},
{OPT_EXPLAIN_LONG, OPT_EXPLAIN_KEY, OPT_EXPLAIN_ARG, OPTION_ARG_OPTIONAL, "Print normalized Intent", 1},
{OPT_VERSION_LONG, OPT_VERSION_KEY, NULL, 0, "Print version and exit", 1},
{"", 0, 0, OPTION_DOC, 0, 0},
{0} // .
};
static struct config g_config;
static struct chain_entry g_chain[MAX_CHAIN_LEN];
static int g_chain_len = 0;
static char *g_chain_arg = NULL;
static struct intent g_intent;
static bool g_intent_mode = false;
static bool g_intent_dry_run = false;
static bool g_intent_explain = false;
#define log_erro(fmt, ...) \
log_err(&g_config, fmt, ##__VA_ARGS__);
#define log_info(fmt, ...) \
log_out(&g_config, fmt, ##__VA_ARGS__);
int get_gateway_iface(char *interface)
{
long dest, gateway;
char iface[IF_NAMESIZE];
char buf[4096];
FILE *file;
memset(iface, 0, sizeof(iface));
memset(buf, 0, sizeof(buf));
file = fopen("/proc/net/route", "r");
if (!file)
{
return -1;
}
while (fgets(buf, sizeof(buf), file))
{
if (sscanf(buf, "%15s %lx %lx", iface, &dest, &gateway) == 3)
{
// default route
if (dest == 0)
{
// note > gateway variable contains the address of the gateway
snprintf(interface, IF_NAMESIZE, "%s", iface);
fclose(file);
return 0;
}
}
}
// default route not found
if (file)
{
fclose(file);
}
return -1;
}
static error_t parse_cli(int key, char *arg, struct argp_state *state)
{
int ifindex;
int p;
const char *err_msg = NULL;
switch (key)
{
// Initializations
case ARGP_KEY_INIT:
g_config.attach_point = BPF_TC_EGRESS;
g_config.ifindex = 0;
g_config.ifname[0] = '\0';
g_config.cleanup_on_exit = true;
g_config.verbose = false;
g_config.err_stream = state->err_stream = stderr;
g_config.out_stream = state->out_stream = stdout;
intent_init(&g_intent, INTENT_DIRECTION_EGRESS);
g_intent_mode = false;
g_intent_dry_run = false;
g_intent_explain = false;
break;
// Options
case OPT_VERBOSE_KEY:
g_config.verbose = true;
break;
case OPT_IFNAME_KEY:
ifindex = if_nametoindex(arg);
if (ifindex == 0)
{
argp_error(state, "option '--%s' requires an existing interface: got '%s'\n", OPT_IFNAME_LONG, arg);
}
g_config.ifindex = ifindex;
snprintf(g_config.ifname, IF_NAMESIZE, "%s", arg);
break;
case OPT_ATTACH_KEY:
/**/ if (strncasecmp(arg, "egress", 6) == 0)
{
g_config.attach_point = BPF_TC_EGRESS;
}
else if (strncasecmp(arg, "ingress", 7) == 0)
{
g_config.attach_point = BPF_TC_INGRESS;
}
else
{
argp_error(state, "option '--%s' requires one of the following values: %s", OPT_ATTACH_LONG, OPT_ATTACH_ARG);
}
break;
case OPT_NO_CLEANUP_KEY:
g_config.cleanup_on_exit = false;
break;
case OPT_CHAIN_KEY:
g_chain_arg = arg;
break;
case OPT_ALLOW_KEY:
case OPT_PERMIT_KEY:
g_intent_mode = true;
if (intent_add_permit(&g_intent, arg, &err_msg) != 0)
{
argp_error(state, "%s: '%s'", err_msg, arg);
}
break;
case OPT_FORBID_KEY:
case OPT_BLOCK_KEY:
g_intent_mode = true;
if (intent_add_forbid(&g_intent, arg, &err_msg) != 0)
{
argp_error(state, "%s: '%s'", err_msg, arg);
}
break;
case OPT_DRY_RUN_KEY:
g_intent_dry_run = true;
break;
case OPT_EXPLAIN_KEY:
g_intent_explain = true;
if (arg && strcmp(arg, "intent") != 0)
{
argp_error(state, "unsupported --explain mode: '%s'", arg);
}
break;
case OPT_VERSION_KEY:
printf("%s\n", argp_program_version);
exit(0);
// Arguments
case ARGP_KEY_ARG:
assert(arg);
if (state->arg_num == 0)
{
// First positional arg: program name
g_config.program_arg = arg;
for (p = 0; p < NUM_PROGRAMS; p++)
{
if (strcasecmp(arg, g_programs_name[p]) == 0)
{
g_config.program = (program_t)p;
break;
}
}
}
else if (state->arg_num == 1)
{
// Second positional arg: input value (parsed in ARGP_KEY_FINI)
g_config.input_arg = arg;
}
else
{
argp_error(state, "too many arguments");
}
break;
case ARGP_KEY_END:
if (g_intent_mode && g_chain_arg)
{
argp_error(state, "--allow/--permit/--forbid/--block and --chain are mutually exclusive");
}
if (g_intent_mode && state->arg_num > 0)
{
argp_error(state, "--allow/--permit/--forbid/--block and positional PROGRAM arguments are mutually exclusive");
}
if (g_intent_dry_run && !g_intent_mode)
{
argp_error(state, "--dry-run currently requires --allow, --permit, --forbid, or --block");
}
if (g_intent_explain && !g_intent_mode)
{
argp_error(state, "--explain currently requires --allow, --permit, --forbid, or --block");
}
if (g_intent_mode && g_intent.permit_count == 0 && g_intent.forbid_count > 0)
{
argp_error(state, "--forbid/--block requires at least one --allow/--permit");
}
if (g_intent_mode)
{
/* Normalize here so dry-run, explain, and attach share one order. */
if (g_config.attach_point == BPF_TC_INGRESS)
g_intent.direction = INTENT_DIRECTION_INGRESS;
else
g_intent.direction = INTENT_DIRECTION_EGRESS;
intent_normalize(&g_intent);
}
// In chain or Intent mode, positional args are not required
if (!g_chain_arg && !g_intent_mode)
{
if (state->arg_num == 0)
{
argp_error(state, "program name is mandatory");
}
if (g_config.program == program_0)
{
argp_error(state, "argument '%s' is not a " TOOL_NAME " program", g_config.program_arg);
}
}
else if (state->arg_num > 0)
{
argp_error(state, "--chain and positional PROGRAM arguments are mutually exclusive");
}
break;
// Final settings, validations
case ARGP_KEY_FINI:
/*
* Dry-run compiles Intent only.
* Live attach and legacy modes still need a concrete interface.
*/
if (g_config.ifindex == 0 && !(g_intent_mode && g_intent_dry_run))
{
if (get_gateway_iface(g_config.ifname))
{
argp_error(state, "could not get the default gateway interface\n");
}
g_config.ifindex = if_nametoindex(g_config.ifname);
assert(g_config.ifindex != 0);
}
if (g_chain_arg)
{
// Parse chain: comma-separated "name:input" or "name" entries.
// Walk g_chain_arg directly so empty entries are not skipped.
if (g_chain_arg[0] == '\0')
{
argp_error(state, "--chain requires at least one program");
}
char *cursor = g_chain_arg;
while (cursor)
{
char *token = cursor;
char *comma = strchr(token, ',');
if (comma)
{
*comma = '\0';
cursor = comma + 1;
}
else
{
cursor = NULL;
}
if (token[0] == '\0')
{
argp_error(state, "empty chain entry");
}
if (g_chain_len >= MAX_CHAIN_LEN)
{
argp_error(state, "chain exceeds maximum of %d programs", MAX_CHAIN_LEN);
}
char *colon = strchr(token, ':');
char *prog_name = token;
char *input_str = NULL;
if (colon)
{
*colon = '\0';
input_str = colon + 1;
}
// Look up program name
int found = 0;
for (int pi = 1; pi < NUM_PROGRAMS; pi++)
{
if (strcasecmp(prog_name, g_programs_name[pi]) == 0)
{
g_chain[g_chain_len].program = (program_t)pi;
found = 1;
break;
}
}
if (!found)
{
argp_error(state, "unknown program in chain: '%s'", prog_name);
}
// Parse input for this program
if (input_str)
{
struct config tmp = {0};
tmp.program = g_chain[g_chain_len].program;
const char *err_msg = NULL;
if (parse_input(&tmp, input_str, &err_msg) != 0)
{
argp_error(state, "%s: '%s'", err_msg, input_str);
}
g_chain[g_chain_len].has_input = tmp.has_input;
memcpy(&g_chain[g_chain_len].input, &tmp.input, sizeof(tmp.input));
}
else if (program_requires_input(g_chain[g_chain_len].program))
{
argp_error(state, "program '%s' in chain requires an input value (use name:value)", prog_name);
}
g_chain_len++;
}
if (g_chain_len == 0)
{
argp_error(state, "--chain requires at least one program");
}
const char *validation_err = NULL;
program_t validation_program = (program_t)NUM_PROGRAMS;
if (validate_chain_entries(g_chain, g_chain_len, &validation_err, &validation_program) != 0)
{
if (validation_program != (program_t)NUM_PROGRAMS)
argp_error(state, "program '%s' does not support chaining", g_programs_name[validation_program]);
else
argp_error(state, "%s", validation_err);
}
}
else if (!g_intent_mode)
{
// Single program mode: parse input value
if (g_config.input_arg)
{
const char *err_msg = NULL;
if (parse_input(&g_config, g_config.input_arg, &err_msg) != 0)
{
argp_error(state, "%s: '%s'", err_msg, g_config.input_arg);
}
}
else if (program_requires_input(g_config.program))
{
argp_error(state, "program '%s' requires an input argument", g_programs_name[g_config.program]);
}
}
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static const struct argp argp = {
.options = argp_opts,
.parser = parse_cli,
.args_doc = "[PROGRAM [INPUT]]",
.doc = argp_program_doc,
};
static volatile sig_atomic_t g_stop;
void sig_handler(int signo)
{
g_stop = 1;
}
static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
{
#ifdef NDEBUG
// In release builds, only suppress debug-level verbosity
if (level == LIBBPF_DEBUG)
return 0;
#endif
return print_log(g_config.err_stream, level == LIBBPF_DEBUG && g_config.verbose, false, format, args);
}
int await(struct bpf_tc_hook hook, struct bpf_tc_opts opts)
{
// Block until user signal
while (!g_stop)
{
fprintf(stdout, ".");
fflush(stdout);
sleep(1);
}
fprintf(stdout, "\n");
return 0;
}
static int intent_compile_for_bpf(const char *context,
struct intent_enforcement_plan *plan,
struct intent_bpf_plan *bpf_plan)
{
struct decision_dag dag = {0};
const char *err_msg = NULL;
/*
* Dry-run and attach compile through the same backend path.
* This keeps dry-run aligned with BPF admission checks.
*/
if (intent_build_dag(&g_intent, &dag, &err_msg) != 0 ||
intent_enforcement_plan_from_dag(&dag, plan, &err_msg) != 0 ||
intent_bpf_plan_from_enforcement(plan, bpf_plan, &err_msg) != 0)
{
fprintf(g_config.err_stream, TOOL_NAME ": %s: %s\n", context, err_msg);
return 1;
}
return 0;
}
static void intent_explain(FILE *out)
{
const char *ifname = g_config.ifname[0] ? g_config.ifname : "not attached";
if (g_intent_explain)
{
intent_print_explain(out, ifname, &g_intent);
fflush(out);
}
}
static int intent_dry_run(void)
{
struct intent_enforcement_plan plan = {0};
struct intent_bpf_plan bpf_plan = {0};
intent_explain(g_config.out_stream);
if (intent_compile_for_bpf("intent dry-run", &plan, &bpf_plan) != 0)
{
return 1;
}
fprintf(g_config.out_stream, "intent dry-run: compiler ok\n");
fprintf(g_config.out_stream, "intent backend: bpf admissible\n");
return 0;
}
static int intent_attach(void)
{
struct intent_enforcement_plan plan = {0};
struct intent_bpf_plan bpf_plan = {0};
intent_explain(g_config.out_stream);
if (intent_compile_for_bpf("intent attach", &plan, &bpf_plan) != 0)
{
return 1;
}
return attach_intent_bpf(&g_config, &bpf_plan, &await);
}
int main(int argc, char **argv)
{
int err;
char buf[100];
buf[sizeof(buf) - 1] = '\0';
argp_err_exit_status = 1;
err = argp_parse(&argp, argc, argv, ARGP_IN_ORDER, NULL, NULL);
if (err)
{
return 1;
}
if (g_intent_mode && g_intent_dry_run)
{
return intent_dry_run();
}
// Setup signal handling
if (signal(SIGINT, sig_handler) == SIG_ERR || signal(SIGTERM, sig_handler) == SIG_ERR)
{
log_erro("can't handle signal: %s\n", strerror(errno));
return 1;
}
// Setup libbpf
libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
libbpf_set_print(libbpf_print_fn);
if (g_intent_mode)
{
return intent_attach();
}
// Execute
if (g_chain_len > 0)
{
log_info("chain: %d programs\n", g_chain_len);
return attach_chain(&g_config, g_chain, g_chain_len, &await);
}
log_info("prog: %s\n", g_programs_name[g_config.program]);
return attach(&g_config, &await);
}