Repository navigation
Expand file tree
/
Copy pathAutoBlock.c
More file actions
410 lines (316 loc) · 11.5 KB
/
Copy pathAutoBlock.c
File metadata and controls
410 lines (316 loc) · 11.5 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
/*
This source file is part of the AutoBlock project.
Copyright (C) 2026 Dennis Hawkins
This program 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 2 of the License, or
(at your option) any later version.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you use this code in any way, I would love to hear from you. My email
address is: dennis@galliform.com
*/
// This is the main source file for the program.
#include "AutoBlock.h"
#include <stdarg.h>
#include <time.h>
// To compile with gcc, use the following:
// gcc -o AutoBlock AutoBlock.c Hash-ip.c ReadIpList.c ReadMsgs.c tries.c whois.c config.c import.c parameters.c
// To view hacker counts in openwrt:
// nft list ruleset | grep -A 1 -i "block-attacker"
// To view remotely:
// ssh -o BatchMode=yes root@192.168.1.1 ' nft list ruleset | grep -A 1 -i "block-attacker" '
// For duplicate sets in openwrt use the following:
// nft delete set inet fw4 IncludedIpSet
void Send2Router(void)
{
int status;
FILE *pfp;
char buffer[256];
// sprintf(buffer, "rsync -c %s %s:%s", SRCPATH, DSTSERV, G_FirewallBlockListPath);
PrintErr(STATUS, "%s\n", G_TransferCmd);
if (G_DryRun) return; // don't actually send anything to the router
pfp = popen(G_TransferCmd, "r");
buffer[0] = 0;
// Read the output if you want to log the progress
while (fgets(buffer, sizeof(buffer), pfp) != NULL)
{
PrintErr(STATUS, "rsync: %s\n", buffer);
}
status = pclose(pfp); // close and wait for finish
if (WEXITSTATUS(status) != 0)
{
// Log the error: Transfer failed or firewall reload failed
PrintErr(FATAL, "Error with File Transfer.\n");
}
// sprintf(buffer, "ssh %s '%s'", DSTSERV, DSTLOAD);
PrintErr(STATUS, "%s\n", G_ReloadCmd);
status = pclose(popen(G_ReloadCmd, "r"));
if (WEXITSTATUS(status) != 0)
{
// Log the error: Transfer failed or firewall reload failed
PrintErr(FATAL, "Error restarting firewall.\n");
}
}
bool ConfigChanged(void)
{
struct stat config_stat;
struct stat output_stat;
int config_rc = stat(CONFIGPATH, &config_stat);
int output_rc = stat(SRCPATH, &output_stat);
// If the configuration file itself is missing,
// we cannot execute or copy anything anyway.
if (config_rc != 0) return false;
// FIRST RUN: If the config exists but the history file is missing,
// this is a brand new installation—force an initial upload.
if (output_rc != 0) return true;
// Both files exist cleanly. Check if config is newer.
if (config_stat.st_mtime > output_stat.st_mtime)
return true;
return false;
}
bool is_root(void)
{
#if defined(__BORLANDC__)
return(true); // not supported by borland
#else
return geteuid() == 0;
#endif
}
// Checks if a file is insecure (not owned by root or writeable by others).
bool NotRootOwned(char *path)
{
if (!path) return(true);
#if defined(__BORLANDC__)
strlen(path); // remove compiler warning
return(false);
#else
struct stat fileStat;
// Execute system call to read file metadata
if (stat(path, &fileStat) < 0)
{
// Fail-safe: If the file is missing or unreadable, treat it as
// insecure
PrintErr(FATAL, "Error reading %s file status.\n", path);
return true;
}
// 1. Check Ownership: Root User ID (UID) is always 0
if (fileStat.st_uid != 0)
{
PrintErr(FATAL, "%s is not owned by root.\n", path);
return true; // Not owned by root
}
// 2. Check Permissions: Ensure nobody else has write permissions
// S_IWGRP check = Group Write permission bit
// S_IWOTH check = Others Write permission bit
if ((fileStat.st_mode & S_IWGRP) || (fileStat.st_mode & S_IWOTH))
{
PrintErr(FATAL, "Modifying %s by non-root users must not be allowed.\n", path);
return true; // Allows modification by group or others
}
// The file is fully secure (Owned by Root, Write-restricted)
return false;
#endif
}
// Return number of days since January 1, 2020 @ 00:00:00
WORD GetDateStamp(void)
{
// Hardcoded UTC seconds for Jan 1, 2020 00:00:00 UTC
const time_t base_time_utc = 1577836800;
// Get current calendar time in UTC seconds from Epoch
time_t current_time = time(NULL);
if (current_time == (time_t)(-1))
{
return 0;
}
// Return delta in seconds
return ((WORD) ((current_time - base_time_utc) / 86400));
}
int main(int argc, char *argv[])
{
int countHash, countImport, countUnique, countWhois;
int bits, oldbits, i, rt, TotalNewAdds;
DWORD ip;
WORD DateStamp;
IPTYPE ipBlk;
TrieNode *TriRoot;
char *IpStr;
bool changed=false;
#if defined(__BORLANDC__)
WSADATA wsaData;
#endif
if (argc > 1)
{
rt = ProcessCmdLine(argc, argv);
if (rt != 0) return(0);
}
#if defined(__BORLANDC__)
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
{
PrintErr(FATAL, "Winsock initialization failed.\n");
return -1;
}
#endif
DateStamp = GetDateStamp();
if (!is_root())
{
PrintErr(FATAL, "This program must be run as root.\n");
CLOSE_NETWORK();
return(-3);
}
if (NotRootOwned(CONFIGPATH))
{
PrintErr(FATAL, "The config file must only be modifiable by root.\n");
CLOSE_NETWORK();
return(-4);
}
PrintErr(STATUS, "%s is Running.\n", VERSION);
if (ParseConfig(CONFIGPATH))
{
PrintErr(FATAL, "Could not parse \"%s\" config file.\n", CONFIGPATH);
CLOSE_NETWORK();
return(-2);
}
TriRoot = create_node(); // Create Trie
// Read existing bad IPs from WhoiIs file into Trie here
// Function handles file i/o errors
PrintErr(STATUS, "Reading existing banned IP blocks.\n");
process_ip_file(MAINPATH, TriRoot);
// Add imported IPs directly to the Trie
PrintErr(STATUS, "Reading %u imported IP blocks.\n", G_NumImports);
countImport = ImportIPs(TriRoot, DateStamp);
if (countImport >= 0)
{
PrintErr(STATUS, "There were %u unique bad IP's imported.\n",
countImport);
changed = true;
}
// Read message log
// These go into the hash table first to prevent duplicates
PrintErr(STATUS, "Reading New IP's from: %s\n", G_AsteriskNoticeFile);
countHash = HashMessages();
if (countHash >= 0)
PrintErr(STATUS, "There were %d bad IP's added to the hash table.\n",
countHash);
// Convert to flat linked list
countUnique = HashFlat();
PrintErr(STATUS, "There were %d unique bad IP's in the hash table.\n", countUnique);
// Read hash table and add to Trie
countWhois = 0;
GetNextHash(true); // initialize the walker
while ((ip = GetNextHash(false)) != 0)
{
if (is_ip_covered(TriRoot, ip, DateStamp)) continue; // already there
// We check the whitelist twice. Here we check it before it gets
// added to the blacklist trie. Later we check the trie again to
// make sure it didn't slip in as part of a larger block.
if (is_ip_whitelisted(ip)) continue; // don't add friends
if (G_UseWhois)
{
// Use whois to find netblock
countWhois++;
ipBlk.IP = ip;
ipBlk.bits = 0;
IpStr = IP2Str(ipBlk);
PrintErr(STATUS, "%d: Whois: %s -> ", countWhois, IpStr);
bits = query_radb_netblock(IpStr, &ipBlk);
if (bits)
{
PrintErr(STATUS, "%s ", IP2Str(ipBlk));
changed = true;
}
else
{
PrintErr(WARN, "Failed.\n");
continue; // whois failed for some reason
}
}
// Add directly into Trie
oldbits = bits;
if (bits == 0 || bits > G_MaxCidr) bits = G_MaxCidr;
if (bits < G_MinCidr) bits = G_MinCidr;
if (oldbits != bits) PrintErr(STATUS, "Cidr Mofified ->(%d)", bits);
insert_netblock(TriRoot, ipBlk, DateStamp);
PrintErr(STATUS, "\n");
}
PrintErr(STATUS, "There were %d new netbocks added to the blacklist.\n", countWhois);
destroy_hash_table(); // free hash table
// Save unmangled netblocks to the whois history file.
if (changed)
{
PrintErr(STATUS, "Updating main whois file.\n");
export_netblocks_to_file(TriRoot, MAINPATH, false);
}
// Compress the trie
CompressTrie(TriRoot);
TotalNewAdds = countImport + countWhois;
PrintErr(STATUS, "Removing whitelist blocks.\n");
if (G_IgnoreBlocks && G_NumIgnoreBlocks)
{
for (i = 0; i < G_NumIgnoreBlocks; i++)
{
ipBlk = G_IgnoreBlocks[i];
rt = whitelist_netblock(TriRoot, ipBlk);
PrintErr(STATUS, "%s was ", IP2Str(ipBlk));
PrintErr(STATUS, "%s the blacklist.\n", rt ?
"Removed from" : "Not found in");
}
}
CLOSE_NETWORK();
if (changed || ConfigChanged())
{
// Save whitelist mangled trie
PrintErr(STATUS, "Sending to Router.\n");
export_netblocks_to_file(TriRoot, SRCPATH, true);
Send2Router();
}
free_subtree(TriRoot); // destroy trie
FreeConfig(); // free the heap
PrintErr(WARN, "AutoBlock Run, %d unique IPs found in logs, "
"%d unique imported IPs, %d newly blocked.\n",
countUnique, countImport, TotalNewAdds);
return(0);
}
//enum {QUIET, FATAL, WARN, STATUS };
void PrintErr(DWORD level, const char *fmt, ...)
{
va_list args;
// Print to console if verbose mode is enabled
if (G_Verbosity >= level)
{
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
fflush(stdout); // Ensure immediate console output
}
// Log to file if the path string is not empty
if (level < STATUS && G_LogFilePath[0] != '\0')
{
FILE *fp = fopen(G_LogFilePath, "at");
if (fp != NULL)
{
time_t rawtime;
struct tm *timeinfo;
// Get current system time
time(&rawtime);
timeinfo = localtime(&rawtime);
// Write timestamp prefix: YYYY-MM-DD HH:MM>
fprintf(fp, "%04d-%02d-%02d %02d:%02d> ",
timeinfo->tm_year + 1900,
timeinfo->tm_mon + 1,
timeinfo->tm_mday,
timeinfo->tm_hour,
timeinfo->tm_min);
// Write the formatted error message components
va_start(args, fmt);
vfprintf(fp, fmt, args);
va_end(args);
fclose(fp);
}
}
}