forked from jonjensen/endpoint-firewall-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firewall-whitelisting-remote-cgi
executable file
·512 lines (428 loc) · 14.8 KB
/
firewall-whitelisting-remote-cgi
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
#!/usr/bin/env perl -T
=for comment
firewall whitelisting CGI program
by Jon Jensen <[email protected]>
2005-03-04 - created
2005-12-09 - support multiple host iptables changes
2006-05-26 - support groups of users each with different server access
2006-07-06 - tolerate groups without URLs in HTML output
2006-09-20 - adapt for OpenBSD and pf tables on the local machine
2006-09-21 - daemonize and make listen on UNIX socket to avoid need for suidperl
2006-09-22 - re-unify and run under sudo
2007-03-16 - switch to CGI-based authentication instead of HTTP basic auth;
limit number of bad attempts per user; quell pfctl success message;
2007-06-29 - added support for remote pf firewall rule setting
2008-04-02 - adapted for End Point by Kiel Christofferson;
added support for multiple commands per iptables run
2011-02-16 - added pastebot access
2011-12-28 - added use of COMMENT module with a timestamp
2012-03-24 - remove trailing \n from syslog messages where it appears as \012
- start phasing out CGI module
- move to HTML5, don't cache, auto-select username field, turn off browser autocomplete
next - allow user to change password; allow admin to force user to change password
=cut
use strict;
use warnings;
no warnings 'qw';
use utf8;
use IO::Handle;
use Sys::Syslog qw(:DEFAULT setlogsock);
use CGI ();
use Apache::Htpasswd ();
use DB_File;
my $now_time = time();
# authentication settings
my $max_failed_attempts = 3;
my $access_path = '/home/firewall/access';
my $users_file = "$access_path/firewall.users";
my $groups_file = "$access_path/firewall.groups";
my $user_attempts_file = '/var/log/httpd/firewall.users.failed.attempts';
my $email = '[email protected]';
# firewall opening settings
my $command_timeout_seconds = 10;
my $iptables = '/usr/sbin/iptables'; # customizable per-host below in %host_rules
my $ip6tables = '/usr/sbin/ip6tables'; # customizable per-host below in %host_rules
my $pfctl = '/sbin/pfctl';
my $ssh = '/usr/bin/ssh';
my $ssh_key = '/root/.ssh/id_rsa.firewall-whitelist';
*STDOUT->autoflush(1);
*STDERR->autoflush(1);
die "This application may only be accessed via https.\n"
unless $ENV{HTTPS};
my $ip = $ENV{REMOTE_ADDR};
my $class = 4;
my $q = CGI->new;
my @params = $q->param;
my $action = $q->param('firewall_action');
my $user = $q->param('firewall_user');
my $pass = $q->param('firewall_pass');
# clear tainted environment
%ENV = ();
setlogsock 'unix';
openlog 'firewall CGI', 'pid nowait', 'LOG_AUTH';
# Validate source IP address
if (! $ip) {
perish("Connection is missing IP address");
}
elsif ($ip =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
@_ = split /\./, $1 || '';
my @ip;
for (@_) {
push @ip, $_ if $_ < 256;
}
perish("Invalid IP address")
unless @ip == 4;
$ip = join '.', @ip;
perish("Devious IP address: $ip")
if $ip eq '0.0.0.0' or $ip eq '255.255.255.255';
announce("Connection reported from $ip");
}
elsif ($ip =~ /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/) {
$class = 6;
announce("Connection reported from $ip");
}
else {
perish("Connection from invalid IP address '$ip'");
}
# Deal with dual page personality:
# ask for user info vs. process and open firewalls
my $onload = '';
my @msg;
my $problems = ' if you run into any problems';
my $pwfile = new Apache::Htpasswd({passwdFile => $users_file, ReadOnly => 1 })
or perish("Error connecting to password file $users_file");
tie my %user_attempts, 'DB_File', $user_attempts_file
or perish("Error tie-ing $user_attempts_file");
if (! $action) {
announce("Initial connection made (no action specified)");
ask_for_id();
}
elsif ($action eq 'Log in') {
authenticate() and open_firewalls();
}
elsif ($action eq 'change_password') {
authenticate() and change_password();
}
else {
perish("Invalid form action attempted: $action");
}
# Return HTML page
my $page_title = 'End Point Firewall';
my $msg = join '', @msg;
print "Content-Type: text/html; charset=UTF-8\r\n";
print "Cache-Control: private, no-store, no-cache\r\n";
print "X-UA-Compatible: IE=edge,chrome=1\r\n";
print "\r\n";
print <<END;
<!doctype html>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<title>$page_title</title>
<style type="text/css">
html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
html, button, input, select, textarea { font-family: sans-serif; color: #222; }
body { margin: 1em; font-size: 1em; line-height: 1.4; }
::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; }
::selection { background: #fe57a1; color: #fff; text-shadow: none; }
a { color: #00e; }
a:visited { color: #551a8b; }
a:hover { color: #06e; }
a:focus { outline: thin dotted; }
a:hover, a:active { outline: 0; }
abbr[title] { border-bottom: 1px dotted; }
b, strong { font-weight: bold; }
blockquote { margin: 1em 40px; }
dfn { font-style: italic; }
hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }
ins { background: #ff9; color: #000; text-decoration: none; }
mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; }
pre, code, kbd, samp { font-family: monospace, serif; _font-family: 'courier new', monospace; font-size: 1em; }
pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; }
q { quotes: none; }
q:before, q:after { content: ""; content: none; }
small { font-size: 85%; }
sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }
ul, ol { margin: 1em 0; padding: 0 0 0 40px; }
dd { margin: 0 0 0 40px; }
nav ul, nav ol { list-style: none; list-style-image: none; margin: 0; padding: 0; }
img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; }
svg:not(:root) { overflow: hidden; }
figure { margin: 0; }
form { margin: 0; }
fieldset { border: 0; margin: 0; padding: 0; }
label { cursor: pointer; }
legend { border: 0; *margin-left: -7px; padding: 0; white-space: normal; }
button, input, select, textarea { font-size: 100%; margin: 0; vertical-align: baseline; *vertical-align: middle; }
button, input { line-height: normal; }
button, input[type="button"], input[type="reset"], input[type="submit"] { cursor: pointer; -webkit-appearance: button; *overflow: visible; }
button[disabled], input[disabled] { cursor: default; }
input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; *width: 13px; *height: 13px; }
input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; }
input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; }
button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; }
textarea { overflow: auto; vertical-align: top; resize: vertical; }
input:valid, textarea:valid { }
input:invalid, textarea:invalid { background-color: #f0dddd; }
table { border-collapse: collapse; border-spacing: 0; }
td { vertical-align: top; }
</style>
</head>
<body$onload>
<h1>$page_title</h1>
$msg
</body>
</html>
END
# Done!
untie %user_attempts
or perish("Error untie-ing file $user_attempts_file!");
announce("HTML response sent and all done");
closelog;
exit;
# Utility routines
sub announce {
syslog 'LOG_NOTICE', '%s', $_[0];
return;
}
sub error {
syslog 'LOG_ERR', '%s', $_[0];
return;
}
sub perish {
syslog 'LOG_ERR', '%s', $_[0];
closelog;
die @_;
}
# Authenticate the user
sub authenticate {
# make sure user's not failed too many times
my $attempts = ++$user_attempts{$user};
if ($attempts > $max_failed_attempts) {
push @msg, qq{<p>Your account is locked due to too many failed login attempts. <b>It will be automatically unlocked within 30 minutes. Please wait and try again.</b> If you are still unable to log in, contact your manager.</p>};
announce("Refused user '$user' because $attempts attempts have been made (limit of $max_failed_attempts allowed).");
$problems = ' to have your account unlocked';
return;
}
# check user + password
my $valid;
eval {
$valid = $pwfile->htCheckPassword($user, $pass);
};
undef $valid if $@;
unless ($valid) {
my $lockout = ($attempts >= $max_failed_attempts);
my $m = 'The username and password you provided are incorrect.';
$m .= ' Your account has now been locked due to too many failed login attempts. <b>Your account will be automatically unlocked after 30 minutes. Please wait 30 minutes and try again.</b> If you are still unable to log in, '
if $lockout;
push @msg, qq{<p>$m</p>};
ask_for_id() unless $lockout;
$problems = ' to have your account unlocked';
announce(
"Authentication for user '$user' failed"
. ($lockout
? " and account is now locked because the limit of"
. " $max_failed_attempts failed attempts has been reached"
: '')
. '.'
);
return;
}
announce("User '$user' authenticated.");
# reset failed attempt counter
$user_attempts{$user} = 0;
return 1;
}
# Open the firewall(s)
sub open_firewalls {
perish("open_firewalls called with no user specified!")
unless $user;
# Find out which groups the user is in
my %in_group;
{
local @ARGV = $groups_file;
while (<>) {
next if /^\s*$/ or /^\s*#/;
my ($group, $users) = /^\s*(\w+)\s*:\s*(.*)/
or perish("Invalid groups file");
$in_group{$group} = 1 if $users =~ /\b$user\b/;
}
}
# Define the various hosts and firewall rules
my @iptables_base = ($iptables, '-A', 'dynamic_ip', '-s', $ip);
my $iptables_bin = 'iptables';
if ($class == 6)
{
$iptables_bin = 'ip6tables';
@iptables_base = ($ip6tables, '-A', 'dynamic_ip', '-s', $ip);
}
my $user = $1 if $user =~ /^(\w+)$/; # untaint
my $iptables_comment = '-m comment --comment "whitelist-' . $user . '-' . $now_time . '"';
my %host_rules = (
bastion => [
[
$iptables_bin, 'localhost',
"-p tcp --dport 22 $iptables_comment -j ACCEPT",
],
],
intranet => [
[
$iptables_bin, 'intranet.yourdomain.tld',
"-p tcp -m multiport --dports 22,80,443 $iptables_comment -j ACCEPT",
],
],
);
# Open the appropriate firewall(s) for this user
my (%success, %errors);
for my $group (keys %in_group) {
my $argset = $host_rules{$group} or die "Missing rules for host $group?\n";
for my $args (@$argset) {
my $fw = shift @$args;
my $host = shift @$args;
my (@cmd, $ret, $errmsg);
if ($fw eq 'pf') {
@cmd = ($pfctl, '-q', '-t', $group, '-T', 'add', $ip);
}
elsif ($fw =~ /\bip6?tables\b/) {
@cmd = join('; ', map { join ' ', @iptables_base, $_ } @$args);
}
else {
die "Unknown firewall type in host_rules: $fw\n";
}
undef $ret;
undef $errmsg;
local $?;
if ($host eq 'localhost') {
$ret = system(@cmd);
}
else {
my $pid = fork;
if (! defined $pid) {
die "Couldn't fork: $!\n";
}
elsif (! $pid) {
# child
my @ssh_cmd = (
$ssh,
'-axqT',
'-o', 'BatchMode=yes',
'-i', $ssh_key,
'-l', 'root',
$host,
join(' ', @cmd),
);
print STDERR "Executing: @ssh_cmd\n";
exec(@ssh_cmd);
}
# parent
eval {
local $SIG{ALRM} = sub { kill 15, $pid; die "timeout\n" };
alarm $command_timeout_seconds;
waitpid $pid, 0;
$ret = $?;
alarm 0;
};
alarm 0;
$errmsg = $@ if $@;
}
if ($ret) {
my $errstr;
if ($ret == -1) {
$errstr = "failed to execute: $!";
}
elsif ($ret & 127) {
$errstr = sprintf "child died with signal %d, %s coredump",
($ret & 127), ($ret & 128) ? 'with' : 'without';
}
else {
my $real = $ret >> 8;
if ($real != 0) {
$errstr = sprintf "child exited with value %d", $real;
}
}
if ($errstr) {
error("Error with $host: $errstr");
++$errors{$group};
}
}
elsif ($errmsg) {
error("Error with $host: $errmsg");
++$errors{$group};
}
else {
++$success{$group};
my $logmsg = "IP has been added to $host";
$logmsg .= '/' . $group if $host eq 'localhost';
$logmsg .= ' whitelist';
announce($logmsg);
}
}
}
if (%success) {
push @msg, "<p>Your IP address, $ip, has been added to the firewall whitelist of servers in these groups:</p>\n";
push @msg, "<ul>\n";
my %sites = (
intranet => {
Wiki => 'https://wiki.yourdomain.tld/',
},
);
for my $group (sort keys %success) {
push @msg, "<li>$group: ";
my $set = $sites{$group};
my @items;
for my $item (sort keys %$set) {
$item = qq{<a href="$set->{$item}">$item</a>} if $set->{$item};
push @items, $item;
}
push @msg, join(', ', @items);
push @msg, "</li>\n";
}
push @msg, "</ul>\n";
if (%errors) {
push @msg, "<p>But there were errors for these: " . join(', ', sort keys %errors) . ".</p>";
$problems = ' about this problem';
}
}
else {
if (%errors) {
push @msg, "<p>There was a problem adding your IP address, $ip, to the firewall whitelist.</p>";
}
push @msg, "<p>You are not part of any access groups. Please contact your manager so you can be added as appropriate.</p>";
}
return;
}
sub ask_for_id {
push @msg, qq{<form name="auth" method="post" action="" enctype="multipart/form-data">\n};
push @msg, qq{<table>\n};
push @msg, qq{<tr>\n};
push @msg, qq{<td>Username:</td>\n};
push @msg, qq{<td><input type="text" name="firewall_user" autocomplete="off" size="20"></td>\n};
push @msg, qq{</tr>\n};
push @msg, qq{<tr>\n};
push @msg, qq{<td>Password:</td>\n};
push @msg, qq{<td><input type="password" name="firewall_pass" autocomplete="off" size="20"></td>\n};
push @msg, qq{</tr>\n};
push @msg, qq{<tr colspan="2">\n};
push @msg, qq{<td><input type="submit" name="firewall_action" value="Log in"></td>\n};
push @msg, qq{</tr>\n};
push @msg, qq{</table>\n};
push @msg, qq{</form>\n};
$onload = qq{ onLoad="document.auth.firewall_user.focus()"};
return;
}
=for skip
sub update_password {
my $ok;
eval {
$pwfile->update_user($user, $new_pass, 'changed=' . time());
};
undef $ok if $@;
perish("Error changing password for user '$user'") unless $ok;
return;
}
=cut