-
Notifications
You must be signed in to change notification settings - Fork 6
/
geod.c
354 lines (297 loc) · 10.2 KB
/
geod.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
// geod.c
// geod
//
// Created by Dr. Rolf Jansen on 2016-07-14.
// Copyright © 2016-2018 Dr. Rolf Jansen. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <math.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include "utils.h"
#include "uint128t.h"
#include "store.h"
#define DAEMON_NAME "geod"
const char *pidfname = "/var/run/"DAEMON_NAME".pid";
void usage(const char *executable)
{
const char *r = executable + strvlen(executable);
while (--r >= executable && *r != '/'); r++;
printf("%s v1.0 (" SCMREV "), Copyright © 2016-2018 Dr. Rolf Jansen\n", r);
printf("Usage: %s [-a AA:BB:..] [-d DD:EE:..] [-r bstfile] [-p pidfile] [-f] [-n] [-h]\n", r);
printf(" -a AA:BB:.. allow IPv4 source addresses from the listed countries,\n");
printf(" i.e, 2 letter capital country codes, separated by colon.\n");
printf(" -d DD:EE:.. deny IPv4 source addresses from the listed countries.\n");
printf(" NOTE: the -a and the -d option are mutually exclusive.\n");
printf(" -r bstfile the path to the binary file with the consolidated IP ranges that has been.\n");
printf(" generated by the 'ipdb' tool [default: /usr/local/etc/ipdb/IPRanges/ipcc.bst].\n");
printf(" -p pidfile the path to the pid file [default: /var/run/"DAEMON_NAME".pid].\n");
printf(" -f foreground mode, don't fork off as a daemon.\n");
printf(" -n no console, don't fork off as a daemon - started/managed by initd, launchd, etc.\n");
printf(" -h show these usage instructions.\n\n");
}
static void signals(int sig)
{
switch (sig)
{
case SIGHUP:
syslog(LOG_ERR, "Received SIGHUP signal.");
kill(0, SIGHUP);
unlink(pidfname);
exit(0);
break;
case SIGINT:
syslog(LOG_ERR, "Received SIGINT signal.");
kill(0, SIGINT);
unlink(pidfname);
exit(0);
break;
case SIGQUIT:
syslog(LOG_ERR, "Received SIGQUIT signal.");
kill(0, SIGQUIT);
unlink(pidfname);
exit(0);
break;
case SIGTERM:
syslog(LOG_ERR, "Received SIGTERM signal.");
kill(0, SIGTERM);
unlink(pidfname);
exit(0);
break;
default:
syslog(LOG_ERR, "Unhandled signal (%d) %s", sig, strsignal(sig));
break;
}
}
typedef enum
{
noDaemon,
launchdDaemon,
discreteDaemon
} DaemonKind;
void daemonize(DaemonKind kind)
{
switch (kind)
{
case noDaemon:
openlog(DAEMON_NAME, LOG_NDELAY | LOG_PID | LOG_CONS, LOG_USER);
break;
case launchdDaemon:
signal(SIGTERM, signals);
openlog(DAEMON_NAME, LOG_NDELAY | LOG_PID, LOG_USER);
break;
case discreteDaemon:
{
// fork off the parent process
pid_t pid = fork();
if (pid < 0)
exit(EXIT_FAILURE);
// if we got a good PID, then we can exit the parent process.
if (pid > 0)
exit(EXIT_SUCCESS);
// The child process continues here.
// first close all open descriptors
for (int i = getdtablesize(); i >= 0; --i)
close(i);
// re-open stdin, stdout, stderr connected to /dev/null
int inouterr = open("/dev/null", O_RDWR); // stdin
dup(inouterr); // stdout
dup(inouterr); // stderr
// Change the file mode mask, 027 = complement of 750
umask(027);
pid_t sid = setsid();
if (sid < 0)
exit(EXIT_FAILURE); // should log the failure before exiting?
// Check and write our pid lock file
// and mutually exclude other instances from running
int pidfile = open(pidfname, O_RDWR|O_CREAT, 0640);
if (pidfile < 0)
exit(1); // can not open our pid file
if (lockf(pidfile, F_TLOCK, 0) < 0)
exit(0); // can not lock our pid file -- was locked already
// only first instance continues beyound this
char s[256];
int l = snprintf(s, 256, "%d\n", getpid());
write(pidfile, s, l); // record pid to our pid file
signal(SIGHUP, signals);
signal(SIGINT, signals);
signal(SIGQUIT, signals);
signal(SIGTERM, signals);
signal(SIGCHLD, SIG_IGN); // ignore child
signal(SIGTSTP, SIG_IGN); // ignore tty signals
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
openlog(DAEMON_NAME, LOG_NDELAY | LOG_PID, LOG_USER);
break;
}
}
}
bool allowMatch = true;
CCNode **CCTable = NULL;
IP4Set *sortedIP4Sets = NULL;
void releaseStores(void)
{
deallocate(VPR(sortedIP4Sets), false);
releaseCCTable(CCTable);
}
int main(int argc, char *argv[])
{
int ch, rc = 0;
char *cmd = argv[0];
char *allowList = NULL,
*denyList = NULL,
*bstfname = "/usr/local/etc/ipdb/IPRanges/ipcc.bst";
DaemonKind dKind = discreteDaemon;
while ((ch = getopt(argc, argv, "a:d:r:p:fnh")) != -1)
{
switch (ch)
{
case 'a':
if (!denyList)
allowList = optarg;
else
goto arg_err;
break;
case 'd':
if (!allowList)
{
denyList = optarg;
allowMatch = false;
}
else
goto arg_err;
break;
case 'r':
bstfname = optarg;
break;
case 'p':
pidfname = optarg;
break;
case 'f':
dKind = noDaemon;
break;
case 'n':
dKind = launchdDaemon;
break;
arg_err:
printf("Incorrect argument:\n -%c %s, ...\n\n", ch, optarg);
default:
rc = 1;
case 'h':
usage(cmd);
return rc;
}
}
argc -= optind;
argv += optind;
if (argc != 0)
{
printf("Wrong number of arguments:\n %s, ...\n\n", argv[0]);
usage(cmd);
return 1;
}
daemonize(dKind);
char *cc = (allowList) ?: denyList;
if (cc)
{
CCTable = createCCTable();
while (*cc)
{
int tl = collen(cc);
if (cc[tl] == ':')
cc[tl++] = '\0';
storeCC(CCTable, *(uint16_t *)cc, 0);
cc += tl;
}
}
struct stat st;
FILE *in;
if (stat(bstfname, &st) == no_error && st.st_size && (in = fopen(bstfname, "r")))
{
sortedIP4Sets = allocate((ssize_t)st.st_size, false, default_align);
atexit(releaseStores);
rc = (int)fread(sortedIP4Sets, (ssize_t)st.st_size, 1, in);
fclose(in);
if (!rc)
{
syslog(LOG_ERR, "IPv4 database file could not be loaded.");
exit(EXIT_FAILURE);
}
int divertSock;
if ((divertSock = socket(PF_INET, SOCK_RAW, IPPROTO_DIVERT)) < 0)
{
syslog(LOG_ERR, "Error creating the divert socket: %d", errno);
exit(EXIT_FAILURE);
}
struct sockaddr_in divertAddress = {};
divertAddress.sin_family = AF_INET;
divertAddress.sin_port = htons(8669);
if (bind(divertSock, (struct sockaddr *)&divertAddress, sizeof(divertAddress)) < 0)
{
syslog(LOG_ERR, "Error calling bind() on the divert socket: %d", errno);
exit(EXIT_FAILURE);
}
uint8_t buffer[IP_MAXPACKET];
struct ip *ip = (struct ip*)buffer;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
ssize_t recvlen, sendlen;
int o, n = (int)(st.st_size/sizeof(IP4Set));
for (;;)
{
if ((recvlen = recvfrom(divertSock, buffer, IP_MAXPACKET, 0, (struct sockaddr *)&addr, &addrlen)) < 0)
{
syslog(LOG_ERR, "Error receiving raw data from the divert socket: %d", errno);
exit(EXIT_FAILURE);
}
// don't filter if no CC list was given or if the source IP cannot be found in the IP ranges sets
if (CCTable && (o = bisectionIP4Search(htonl(ip->ip_src.s_addr), sortedIP4Sets, n)) >= 0)
{
bool doesMatch = findCC(CCTable, sortedIP4Sets[o].cc) != NULL;
if (allowMatch && !doesMatch || !allowMatch && doesMatch)
continue;
}
if ((sendlen = sendto(divertSock, buffer, recvlen, 0, (struct sockaddr *)&addr, sizeof(addr))) < 0)
{
syslog(LOG_ERR, "Error sending raw data to the divert socket: %d", errno);
exit(EXIT_FAILURE);
}
}
return 0;
}
return 1;
}