-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.c
531 lines (452 loc) · 14.9 KB
/
main.c
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
/*
This file is part of Linux Application Firewall (LAF).
Linux Application Firewall (LAF) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
Linux Application Firewall (LAF) is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Linux Application Firewall (LAF). If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <linux/types.h>
#include <linux/netfilter.h> /* for NF_ACCEPT */
#include <arpa/inet.h> /* for inet_ntop(), inet_pton() */
#include <string.h> /* for memcpy(), strcmp() etc. */
#include <signal.h>
#include <assert.h>
#include <ctype.h>
#include <libnetfilter_queue/libnetfilter_queue.h>
#include "main.h"
#include "config.h"
struct laf_entry allowed[MAX_ALLOWED_WHIETLIST];
int total_entries, stats_pkt_count, stats_pkt_ip, stats_pkt_tcp, stats_pkt_udp, stats_pkt_icmp, stats_pkt_unknown, stats_pkt_blocked, stats_pkt_allowed = 0;
int reload_config = 0;
/* Print all whitelisted entries */
int print_allowed()
{
int i;
for(i = 0; i < total_entries; i++)
{
printf("[>] Allowing traffic to %s from %s", allowed[i].ip_dst, allowed[i].binary_name);
if(allowed[i].port != 0)
{
printf(" on port %d", allowed[i].port);
}
printf("\n");
}
return 0;
}
/* Print a single entry */
int print_entry(struct laf_entry *entry)
{
printf("'%s'\t", entry->binary_name);
printf("'%s'\t", entry->ip_src);
printf("'%s'\t", entry->ip_dst);
printf("'%d'\n", entry->port);
return 0;
}
/* Load the whitelist into memory */
int read_whitelist()
{
FILE *fp;
char buff[LINE_BUFFER_SIZE];
/* TODO Check file exists */
fp = fopen(WHITELIST, "r");
if( fp == NULL ){
fprintf(stderr, "[!!] Error opening the white list file (%s).\n", WHITELIST);
return 1;
}
/* Make sure the allowed list is zerored */
/*memset(allowed, 0, MAX_ALLOWED_WHIETLIST);*/
while (fgets(buff, LINE_BUFFER_SIZE, fp) != NULL)
{
int c = 0;
char *split_entry;
struct laf_entry entry;
split_entry = strtok(buff, " ");
while(split_entry != NULL)
{
switch(c)
{
case 0:
entry.binary_name = strdup(split_entry);
break;
case 1:
entry.ip_dst = strdup(split_entry);
break;
case 2:
entry.port = atoi(split_entry);
break;
default:
fprintf(stderr, "[!!] Error reading config, too many tokens!");
return 2;
}
c++;
split_entry = strtok(NULL, " ");
}
allowed[total_entries] = entry;
total_entries++;
}
fclose(fp);
/* TODO: Should read_whitlist exit the application if it fails to read ? */
return 0;
}
/* load the config */
int load_config()
{
int rtn = 1;
rtn = read_whitelist();
print_allowed();
return rtn;
}
/* Process packet form the queue */
static u_int32_t process_pkt (struct nfq_data *tb, struct laf_entry *curr_entry)
{
int id = 0;
struct nfqnl_msg_packet_hdr *ph;
int ret;
unsigned char *data;
ph = nfq_get_msg_packet_hdr(tb);
if (ph) {
id = ntohl(ph->packet_id);
if(VERBOSE_LEVEL > 0)
{
printf("[#] hw_protocol=0x%04x hook=%u id=%u \n",
ntohs(ph->hw_protocol), ph->hook, id);
}
}
ret = nfq_get_payload(tb, &data);
if (ret >= 0)
{
const struct sniff_ip *ip; /* The IP header */
const struct sniff_tcp *tcp; /* The TCP header */
const char *binary_name = NULL;
const char *new_binary_name;
int size_ip;
int size_tcp;
int size_payload;
ip = (struct sniff_ip*)(data);
size_ip = IP_HL(ip)*4;
if (size_ip < 20) {
printf("[!!] Invalid IP header length: %u bytes\n", size_ip);
return id;
}
/* TODO Find a cleaner way to get the hostname of the IP address. */
/*
struct sockaddr_in sa;
char host[NI_MAXHOST], service[NI_MAXSERV];
sa.sin_family = AF_INET;
sa.sin_port = 80;
sa.sin_addr = ip->ip_dst;
getnameinfo(&sa, sizeof sa, host, sizeof host, service, sizeof service, 0);
printf("[>] To: %s (%s)\n", host, inet_ntoa(ip->ip_dst)); TODO Handle return value.
*/
/* print source and destination IP addresses */
if(VERBOSE_LEVEL > 0)
{
printf("[>] From: %s\n", inet_ntoa(ip->ip_src));
printf("[>] To: %s\n", inet_ntoa(ip->ip_dst));
}
/* determine protocol */
switch(ip->ip_p) {
case IPPROTO_TCP:
if(VERBOSE_LEVEL > 0)
{
printf("[>] Protocol: TCP\n");
}
stats_pkt_tcp++;
break;
case IPPROTO_UDP:
if(VERBOSE_LEVEL > 0)
{
printf("[>] Protocol: UDP\n");
}
stats_pkt_udp++;
/* TODO: handle this better */
curr_entry->ip_src = strdup(inet_ntoa(ip->ip_src));
curr_entry->ip_dst = strdup(inet_ntoa(ip->ip_dst));
break;
case IPPROTO_ICMP:
if(VERBOSE_LEVEL > 0)
{
printf("[>] Protocol: ICMP\n");
}
stats_pkt_icmp++;
break;
case IPPROTO_IP:
if(VERBOSE_LEVEL > 0)
{
printf("[>] Protocol: IP\n");
}
stats_pkt_ip++;
break;
default:
printf("[!!] Protocol: unknown\n");
stats_pkt_unknown++;
break;
}
/* Do nothing else if it's not TCP. */
if(ip->ip_p != IPPROTO_TCP){
stats_pkt_blocked++;
return id;
}
/* define/compute tcp header offset */
tcp = (struct sniff_tcp*)(data + size_ip);
size_tcp = TH_OFF(tcp)*4;
if (size_tcp < 20) {
printf("[!!] Invalid TCP header length: %u bytes\n", size_tcp);
return id;
}
if(VERBOSE_LEVEL > 0)
{
printf("[>] Src port: %d\n", ntohs(tcp->th_sport));
printf("[>] Dst port: %d\n", ntohs(tcp->th_dport));
}
binary_name = net_to_pid_name(
strdup(inet_ntoa(ip->ip_src)),
ntohs(tcp->th_sport),
strdup(inet_ntoa(ip->ip_dst)),
ntohs(tcp->th_dport)
);
if(binary_name != NULL){
new_binary_name = get_actual_binary_name(binary_name);
if (new_binary_name == NULL)
{
new_binary_name = binary_name;
}
if(VERBOSE_LEVEL > 0)
{
printf("[>] Binary: %s\n", new_binary_name);
}
} else {
new_binary_name = malloc(0);
}
curr_entry->binary_name = new_binary_name;
curr_entry->ip_src = strdup(inet_ntoa(ip->ip_src));
curr_entry->ip_dst = strdup(inet_ntoa(ip->ip_dst));
curr_entry->port = ntohs(tcp->th_dport);
binary_name = NULL;
/* compute tcp payload (segment) size */
size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp);
if (size_payload > 0)
if(VERBOSE_LEVEL > 0)
{
printf("[#] Payload %d bytes.\n", size_payload);
}
}
return id;
}
/* Check if the whitelist contains this entry */
int check_whitelist(struct laf_entry *entry)
{
int i = 0, response = 0;
// TODO: Proper check of entry.
if (entry->ip_src == NULL || entry->ip_dst == NULL || entry->binary_name == NULL)
{
if(VERBOSE_LEVEL > 0)
{
printf("[>] Dropping\n\n");
}
return NF_DROP;
}
for(i = 0; i < total_entries; i++)
{
if(((strcmp(entry->binary_name, allowed[i].binary_name) == 0) || (strcmp(allowed[i].binary_name, "*") == 0))
&& ((strcmp(entry->ip_dst, allowed[i].ip_dst) == 0) || (strcmp(allowed[i].ip_dst, "*")==0))
&& (entry->port == allowed[i].port
|| allowed[i].port == atoi("*")))
{
if(VERBOSE_LEVEL > 0)
{
printf("[>] Whitelist - Accepting\n\n");
}
stats_pkt_allowed++;
return NF_ACCEPT;
}
}
/* Handle crazy input.*/
printf("\n\n[?] %s wants to connect to %s on port %d\n", entry->binary_name, entry->ip_dst, entry->port);
printf("[?] Allow [y/N] ");
if (scanf("%d", &response) < 0){
printf("[!!] Bad input (check_whitelist)\n");
}
/* TODO Check user input!! */
switch (response) {
case 'y':
case 'Y':
case 1:
add_entry(entry);
load_config();
return NF_REPEAT;
break;
case 'n':
case 'N':
default:
if(VERBOSE_LEVEL > 0)
{
printf("[>] Dropping\n\n");
}
stats_pkt_blocked++;
return NF_DROP;
break;
}
}
/* Adds an entry to the whitlist */
int add_entry(struct laf_entry *entry) {
int rtn = -1;
FILE* fp;
fp = fopen (WHITELIST,"a+");
if(fp == NULL)
{
fprintf(stderr, "[!!] Couldn't open file path [%s]. (add_entry)\n", WHITELIST);
return -1;
}
rtn = fprintf(fp, "%s %s %d\n", entry->binary_name, entry->ip_dst, entry->port);
if(rtn > 0) {
printf("[>] Written %s %s %d to %s.\n", entry->binary_name, entry->ip_dst, entry->port, WHITELIST);
}
fclose(fp);
return rtn;
}
/* Callback for the packet */
static int cb(struct nfq_q_handle *qh, __attribute__ ((unused)) struct nfgenmsg *nfmsg,
struct nfq_data *nfa, __attribute__ ((unused)) void *data)
{
struct laf_entry entry;
entry.ip_src = NULL;
entry.ip_dst = NULL;
entry.binary_name = NULL;
u_int32_t id = process_pkt(nfa, &entry);
int verdict = check_whitelist(&entry);
free((char *) entry.binary_name);
free(entry.ip_src);
free(entry.ip_dst);
stats_pkt_count++;
return nfq_set_verdict(qh, id, verdict, 0, NULL);
}
/* TODO: Remove printf/puts from signal handler. */
static void termination_handler(int signo) {
switch (signo)
{
case SIGHUP:
puts("Reloading whitelist.\n");
reload_config = 1;
break;
case SIGINT:
case SIGTERM:
default:
printf("\nPackets total: %d\n", stats_pkt_count);
printf("Packets allowed: %d\n", stats_pkt_allowed);
printf("Packets blocked: %d\n", stats_pkt_blocked);
printf("IP: %d, TCP: %d, UDP: %d, ICMP: %d, Unknown: %d\n\n",
stats_pkt_ip, stats_pkt_tcp, stats_pkt_udp, stats_pkt_icmp,
stats_pkt_unknown);
exit(EXIT_SUCCESS);
break;
}
}
/* Main entry point to the application */
int main(__attribute__ ((unused)) int argc, __attribute__ ((unused)) char **argv)
{
int fd, rv;
struct sigaction new_action, old_action;
struct nfq_handle *h;
struct nfq_q_handle *qh;
char buf[MAX_PKT_BUFFER] __attribute__ ((aligned));
/* Set up the structure to specify the new action. */
new_action.sa_handler = termination_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGINT, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction (SIGINT, &new_action, NULL);
sigaction (SIGHUP, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction (SIGHUP, &new_action, NULL);
sigaction (SIGTERM, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction (SIGTERM, &new_action, NULL);
if (getuid() > 0)
{
fprintf(stderr, "[!!] This is a simple test to check if you are root, there is a better way to do this but for now this will do.\nBye.\n");
exit(EXIT_FAILURE);
}
if (load_config() > 0)
{
fprintf(stderr, "[!!] Exiting - Unable to load config file.\n");
exit(EXIT_FAILURE);
}
printf("[#] Opening library handle.\n");
h = nfq_open();
if (!h) {
fprintf(stderr, "[!!] Error during nfq_open().\n");
exit(1);
}
printf("[#] Unbinding existing nf_queue handler for AF_INET (if any).\n");
if (nfq_unbind_pf(h, AF_INET) < 0) {
fprintf(stderr, "[!!] Error during nfq_unbind_pf().\n");
exit(1);
}
printf("[#] Binding nfnetlink_queue as nf_queue handler for AF_INET.\n");
if (nfq_bind_pf(h, AF_INET) < 0) {
fprintf(stderr, "[!!] Error during nfq_bind_pf().\n");
exit(1);
}
printf("[#] Binding this socket to queue '0'.\n");
qh = nfq_create_queue(h, 0, &cb, NULL);
if (!qh) {
fprintf(stderr, "[!!] Error during nfq_create_queue().\n");
exit(1);
}
printf("[#] Setting copy_packet mode.\n");
if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) {
fprintf(stderr, "[!!] Can't set packet_copy mode.\n");
exit(1);
}
fd = nfq_fd(h);
while ((rv = recv(fd, buf, sizeof(buf), 0)) && rv >= 0) {
nfq_handle_packet(h, buf, rv);
if(reload_config == 1)
{
printf("Reload-Config!\n");
if (load_config() > 0)
{
fprintf(stderr, "[!!] Exiting - Unable to load config file.\n");
exit(EXIT_FAILURE);
}
reload_config = 0;
}
}
printf("[#] Unbinding from queue '0'.\n");
nfq_destroy_queue(qh);
printf("[#] Closing library handle.\n");
nfq_close(h);
/* TODO Display help options program arguments */
exit(0);
}
const char* get_actual_binary_name(const char* path)
{
char *last_split;
char *split_path = strdup(path);
char *non_const_path = strdup(path);
last_split = strtok(non_const_path, "/");
while(last_split != NULL)
{
last_split = strtok(NULL, "/");
if(last_split != NULL)
{
split_path = strdup(last_split);
}
}
free(non_const_path);
return (const char *) split_path;
}