-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminiserv.pl
More file actions
executable file
·2627 lines (2476 loc) · 67.7 KB
/
miniserv.pl
File metadata and controls
executable file
·2627 lines (2476 loc) · 67.7 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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# A very simple perl web server used by Webmin
# Require basic libraries
package miniserv;
use Socket;
use POSIX;
# Find and read config file
if (@ARGV != 1) {
die "Usage: miniserv.pl <config file>";
}
if ($ARGV[0] =~ /^\//) {
$conf = $ARGV[0];
}
else {
chop($pwd = `pwd`);
$conf = "$pwd/$ARGV[0]";
}
open(CONF, $conf) || die "Failed to open config file $conf : $!";
while(<CONF>) {
s/\r|\n//g;
if (/^#/ || !/\S/) { next; }
/^([^=]+)=(.*)$/;
$name = $1; $val = $2;
$name =~ s/^\s+//g; $name =~ s/\s+$//g;
$val =~ s/^\s+//g; $val =~ s/\s+$//g;
$config{$name} = $val;
}
close(CONF);
# Check is SSL is enabled and available
if ($config{'ssl'}) {
eval "use Net::SSLeay";
if (!$@) {
$use_ssl = 1;
# These functions only exist for SSLeay 1.0
eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
eval "Net::SSLeay::load_error_strings()";
if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
defined(&Net::SSLeay::CTX_load_verify_locations) &&
defined(&Net::SSLeay::CTX_set_verify)) {
$client_certs = 1;
}
}
}
# Check if the syslog module is available to log hacking attempts
if ($config{'syslog'} && !$config{'inetd'}) {
eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
if (!$@) {
$use_syslog = 1;
}
}
# check if the TCP-wrappers module is available
if ($config{'libwrap'}) {
eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
if (!$@) {
$use_libwrap = 1;
}
}
# Get miniserv's perl path and location
$miniserv_path = $0;
open(SOURCE, $miniserv_path);
<SOURCE> =~ /^#!(\S+)/; $perl_path = $1;
close(SOURCE);
@miniserv_argv = @ARGV;
# Check vital config options
%vital = ("port", 80,
"root", "./",
"server", "MiniServ/0.01",
"index_docs", "index.html index.htm index.cgi index.pl index.php",
"addtype_html", "text/html",
"addtype_txt", "text/plain",
"addtype_gif", "image/gif",
"addtype_jpg", "image/jpeg",
"addtype_jpeg", "image/jpeg",
"realm", "MiniServ",
"session_login", "/session_login.cgi",
"password_form", "/password_form.cgi",
"password_change", "/password_change.cgi",
"maxconns", 50,
"pam", "webmin",
"sidname", "sid",
"unauth", "^/unauthenticated/ ^[A-Za-z0-9\\-/]+\\.jar\$ ^[A-Za-z0-9\\-/]+\\.class\$ ^[A-Za-z0-9\\-/]+\\.gif\$ ^[A-Za-z0-9\\-/]+\\.conf\$",
"max_post", 10000
);
foreach $v (keys %vital) {
if (!$config{$v}) {
if ($vital{$v} eq "") {
die "Missing config option $v";
}
$config{$v} = $vital{$v};
}
}
if (!$config{'sessiondb'}) {
$config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
$config{'sessiondb'} = "$1/sessiondb";
}
if (!$config{'errorlog'}) {
$config{'logfile'} =~ /^(.*)\/[^\/]+$/;
$config{'errorlog'} = "$1/miniserv.error";
}
$sidname = $config{'sidname'};
die "Session authentication cannot be used in inetd mode"
if ($config{'inetd'} && $config{'session'});
# check if the PAM module is available to authenticate
if (!$config{'no_pam'}) {
eval "use Authen::PAM";
if (!$@) {
# check if the PAM authentication can be used by opening a
# PAM handle
local $pamh;
if (ref($pamh = new Authen::PAM($config{'pam'}, "root",
\&pam_conv_func))) {
# Now test a login to see if /etc/pam.d/XXX is set
# up properly.
$pam_conv_func_called = 0;
$pam_username = "test";
$pam_password = "test";
$pamh->pam_authenticate();
if ($pam_conv_func_called) {
$pam_msg = "PAM authentication enabled";
$use_pam = 1;
}
else {
$pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
}
}
else {
$pam_msg = "PAM initialization of Authen::PAM failed";
}
}
}
# init days and months for http_date
@weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
@month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
# Change dir to the server root
chdir($config{'root'});
$user_homedir = (getpwuid($<))[7];
# Read users file
if ($config{'userfile'}) {
open(USERS, $config{'userfile'});
while(<USERS>) {
s/\r|\n//g;
local @user = split(/:/, $_);
$users{$user[0]} = $user[1];
$certs{$user[0]} = $user[3] if ($user[3]);
if ($user[4] =~ /^allow\s+(.*)/) {
$allow{$user[0]} = $config{'alwaysresolve'} ?
[ split(/\s+/, $1) ] :
[ &to_ipaddress(split(/\s+/, $1)) ];
}
elsif ($user[4] =~ /^deny\s+(.*)/) {
$deny{$user[0]} = $config{'alwaysresolve'} ?
[ split(/\s+/, $1) ] :
[ &to_ipaddress(split(/\s+/, $1)) ];
}
}
close(USERS);
}
# Setup SSL if possible and if requested
if (!-r $config{'keyfile'} ||
$config{'certfile'} && !-r $config{'certfile'}) {
# Key file doesn't exist!
$use_ssl = 0;
}
if ($use_ssl) {
$ssl_ctx = Net::SSLeay::CTX_new() ||
die "Failed to create SSL context : $!";
$client_certs = 0 if (!-r $config{'ca'} || !%certs);
if ($client_certs) {
Net::SSLeay::CTX_load_verify_locations(
$ssl_ctx, $config{'ca'}, "");
Net::SSLeay::CTX_set_verify(
$ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
}
if ($config{'extracas'}) {
foreach $p (split(/\s+/, $config{'extracas'})) {
Net::SSLeay::CTX_load_verify_locations(
$ssl_ctx, $p, "");
}
}
Net::SSLeay::CTX_use_RSAPrivateKey_file(
$ssl_ctx, $config{'keyfile'},
&Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key";
Net::SSLeay::CTX_use_certificate_file(
$ssl_ctx, $config{'certfile'} || $config{'keyfile'},
&Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert";
}
# Setup syslog support if possible and if requested
if ($use_syslog) {
eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock("unix")';
if ($@) {
$use_syslog = 0;
}
else {
local $msg = ucfirst($config{'pam'})." starting";
eval { syslog("info", $msg); };
if ($@) {
eval {
setlogsock("inet");
syslog("info", $msg);
};
if ($@) {
# All attempts to use syslog have failed..
$use_syslog = 0;
}
}
}
}
# Read MIME types file and add extra types
if ($config{"mimetypes"} ne "") {
open(MIME, $config{"mimetypes"});
while(<MIME>) {
chop; s/#.*$//;
if (/^(\S+)\s+(.*)$/) {
$type = $1; @exts = split(/\s+/, $2);
foreach $ext (@exts) {
$mime{$ext} = $type;
}
}
}
close(MIME);
}
foreach $k (keys %config) {
if ($k !~ /^addtype_(.*)$/) { next; }
$mime{$1} = $config{$k};
}
# get the time zone
if ($config{'log'}) {
local(@gmt, @lct, $days, $hours, $mins);
@make_date_marr = ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
@gmt = gmtime(time());
@lct = localtime(time());
$days = $lct[3] - $gmt[3];
$hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
$lct[2] - $gmt[2];
$mins = $hours * 60 + $lct[1] - $gmt[1];
$timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
$timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
}
# build anonymous access list
foreach $a (split(/\s+/, $config{'anonymous'})) {
if ($a =~ /^([^=]+)=(\S+)$/) {
$anonymous{$1} = $2;
}
}
# build unauthenticated URLs list
@unauth = split(/\s+/, $config{'unauth'});
# build redirect mapping
foreach $r (split(/\s+/, $config{'redirect'})) {
if ($r =~ /^([^=]+)=(\S+)$/) {
$redirect{$1} = $2;
}
}
# start up external authentication program, if needed
if ($config{'extauth'}) {
socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
if (!($extauth = fork())) {
close(EXTAUTH);
close(STDIN);
close(STDOUT);
open(STDIN, "<&EXTAUTH2");
open(STDOUT, ">&EXTAUTH2");
exec($config{'extauth'});
print STDERR "exec failed : $!\n";
exit 1;
}
close(EXTAUTH2);
local $os = select(EXTAUTH);
$| = 1; select($os);
}
# Re-direct STDERR to a log file
if ($config{'errorlog'} ne '-') {
open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
}
# Init allow and deny lists
@deny = split(/\s+/, $config{"deny"});
@deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
@allow = split(/\s+/, $config{"allow"});
@allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
if ($config{'allowusers'}) {
@allowusers = split(/\s+/, $config{'allowusers'});
}
elsif ($config{'denyusers'}) {
@denyusers = split(/\s+/, $config{'denyusers'});
}
if ($config{'inetd'}) {
# We are being run from inetd - go direct to handling the request
$SIG{'HUP'} = 'IGNORE';
$SIG{'TERM'} = 'DEFAULT';
$SIG{'PIPE'} = 'DEFAULT';
open(SOCK, "+>&STDIN");
# Check if it is time for the logfile to be cleared
if ($config{'logclear'}) {
local $write_logtime = 0;
local @st = stat("$config{'logfile'}.time");
if (@st) {
if ($st[9]+$config{'logtime'}*60*60 < time()){
# need to clear log
$write_logtime = 1;
unlink($config{'logfile'});
}
}
else { $write_logtime = 1; }
if ($write_logtime) {
open(LOGTIME, ">$config{'logfile'}.time");
print LOGTIME time(),"\n";
close(LOGTIME);
}
}
# Initialize SSL for this connection
if ($use_ssl) {
$ssl_con = Net::SSLeay::new($ssl_ctx);
Net::SSLeay::set_fd($ssl_con, fileno(SOCK));
Net::SSLeay::accept($ssl_con) || exit;
}
# Work out the hostname for this web server
$host = &get_socket_name(SOCK);
$host || exit;
$port = $config{'port'};
$acptaddr = getpeername(SOCK);
$acptaddr || exit;
while(&handle_request($acptaddr, getsockname(SOCK))) { }
close(SOCK);
exit;
}
# Build list of sockets to listen on
if ($config{"bind"} && $config{"bind"} ne "*") {
push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
}
else {
push(@sockets, [ INADDR_ANY, $config{'port'} ]);
}
foreach $s (split(/\s+/, $config{'sockets'})) {
if ($s =~ /^(\d+)$/) {
# Just listen on another port on the main IP
push(@sockets, [ $sockets[0]->[0], $s ]);
}
elsif ($s =~ /^(\S+):(\d+)$/) {
# Listen on a specific port and IP
push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
}
elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
# Listen on the main port on another IP
push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
}
}
# Open all the sockets
$proto = getprotobyname('tcp');
for($i=0; $i<@sockets; $i++) {
$fh = "MAIN$i";
socket($fh, PF_INET, SOCK_STREAM, $proto) ||
die "Failed to open socket : $!";
setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
for($j=0; $j<5; $j++) {
last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
$sockets[$i]->[0])));
sleep(1);
}
die "Failed to bind to $sockets[$i]->[1] : $!" if ($j == 5);
listen($fh, SOMAXCONN);
push(@socketfhs, $fh);
}
if ($config{'listen'}) {
# Open the socket that allows other webmin servers to find this one
$proto = getprotobyname('udp');
if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
listen(LISTEN, SOMAXCONN);
}
else {
$config{'listen'} = 0;
}
}
# Split from the controlling terminal
if (fork()) { exit; }
setsid();
# Close standard file handles
open(STDIN, "</dev/null");
open(STDOUT, ">/dev/null");
&log_error("miniserv.pl started");
&log_error($pam_msg) if ($pam_msg);
# write out the PID file
open(PIDFILE, "> $config{'pidfile'}");
printf PIDFILE "%d\n", getpid();
close(PIDFILE);
# Start the log-clearing process, if needed. This checks every minute
# to see if the log has passed its reset time, and if so clears it
if ($config{'logclear'}) {
if (!($logclearer = fork())) {
&close_all_sockets();
close(LISTEN);
while(1) {
local $write_logtime = 0;
local @st = stat("$config{'logfile'}.time");
if (@st) {
if ($st[9]+$config{'logtime'}*60*60 < time()){
# need to clear log
$write_logtime = 1;
unlink($config{'logfile'});
}
}
else { $write_logtime = 1; }
if ($write_logtime) {
open(LOGTIME, ">$config{'logfile'}.time");
print LOGTIME time(),"\n";
close(LOGTIME);
}
sleep(5*60);
}
exit;
}
push(@childpids, $logclearer);
}
# Setup the logout time dbm if needed
if ($config{'session'}) {
eval "use SDBM_File";
dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
eval "\$sessiondb{'1111111111'} = 'foo bar';";
if ($@) {
dbmclose(%sessiondb);
eval "use NDBM_File";
dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
}
else {
delete($sessiondb{'1111111111'});
}
}
# Run the main loop
$SIG{'HUP'} = 'miniserv::trigger_restart';
$SIG{'TERM'} = 'miniserv::term_handler';
$SIG{'PIPE'} = 'IGNORE';
while(1) {
# wait for a new connection, or a message from a child process
local ($i, $rmask);
if (@childpids <= $config{'maxconns'}) {
# Only accept new main socket connects when ready
local $s;
foreach $s (@socketfhs) {
vec($rmask, fileno($s), 1) = 1;
}
}
else {
printf STDERR "too many children (%d > %d)\n",
scalar(@childpids), $config{'maxconns'};
}
if ($config{'passdelay'} || $config{'session'}) {
for($i=0; $i<@passin; $i++) {
vec($rmask, fileno($passin[$i]), 1) = 1;
}
}
vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
local $sel = select($rmask, undef, undef, 10);
if ($need_restart) { &restart_miniserv(); }
local $time_now = time();
# Clean up finished processes
local $pid;
do { $pid = waitpid(-1, WNOHANG);
@childpids = grep { $_ != $pid } @childpids;
} while($pid > 0);
# run the unblocking procedure to check if enough time has passed to
# unblock hosts that heve been blocked because of password failures
if ($config{'blockhost_failures'}) {
$i = 0;
while ($i <= $#deny) {
if ($blockhosttime{$deny[$i]} && $config{'blockhost_time'} != 0 &&
($time_now - $blockhosttime{$deny[$i]}) >= $config{'blockhost_time'}) {
# the host can be unblocked now
$hostfail{$deny[$i]} = 0;
splice(@deny, $i, 1);
}
$i++;
}
}
if ($config{'session'} && (++$remove_session_count%50) == 0) {
# Remove sessions with more than 7 days of inactivity,
local $s;
foreach $s (keys %sessiondb) {
local ($user, $ltime) = split(/\s+/, $sessiondb{$s});
if ($time_now - $ltime > 7*24*60*60) {
local @sdb = split(/\s+/, $sessiondb{$s});
&run_logout_script($s, $sdb[0]);
delete($sessiondb{$s});
if ($use_syslog) {
syslog("info", "Timeout of $sdb[0]");
}
}
}
}
next if ($sel <= 0);
# Check if any of the main sockets have received a new connection
local $sn = 0;
foreach $s (@socketfhs) {
if (vec($rmask, fileno($s), 1)) {
# got new connection
$acptaddr = accept(SOCK, $s);
if (!$acptaddr) { next; }
binmode(SOCK); # turn off any Perl IO stuff
# create pipes
local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
if ($config{'passdelay'} || $config{'session'}) {
local $p;
local %taken = map { $_, 1 } @passin;
for($p=0; $taken{"PASSINr$p"}; $p++) { }
$PASSINr = "PASSINr$p";
$PASSINw = "PASSINw$p";
$PASSOUTr = "PASSOUTr$p";
$PASSOUTw = "PASSOUTw$p";
pipe($PASSINr, $PASSINw);
pipe($PASSOUTr, $PASSOUTw);
select($PASSINw); $| = 1;
select($PASSINr); $| = 1;
select($PASSOUTw); $| = 1;
select($PASSOUTw); $| = 1;
}
select(STDOUT);
# Check username of connecting user
local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
$localauth_user = undef;
if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
if (open(TCP, "/proc/net/tcp")) {
# Get the info direct from the kernel
while(<TCP>) {
s/^\s+//;
local @t = split(/[\s:]+/, $_);
if ($t[1] eq '0100007F' &&
$t[2] eq sprintf("%4.4X", $peerp)) {
$localauth_user = getpwuid($t[11]);
last;
}
}
close(TCP);
}
else {
# Call lsof for the info
local $lsofpid = open(LSOF,
"$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
while(<LSOF>) {
if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
$2 != $$ && $2 != $lsofpid) {
$localauth_user = $3;
}
}
close(LSOF);
}
}
# Work out the hostname for this web server
$host = &get_socket_name(SOCK);
if (!$host) {
print STDERR "Failed to get local socket name : $!\n";
close(SOCK);
next;
}
$port = $sockets[$sn]->[1];
# fork the subprocess
local $handpid;
if (!($handpid = fork())) {
# setup signal handlers
$SIG{'TERM'} = 'DEFAULT';
$SIG{'PIPE'} = 'DEFAULT';
#$SIG{'CHLD'} = 'IGNORE';
$SIG{'HUP'} = 'IGNORE';
# Initialize SSL for this connection
if ($use_ssl) {
$ssl_con = Net::SSLeay::new($ssl_ctx);
Net::SSLeay::set_fd($ssl_con, fileno(SOCK));
Net::SSLeay::accept($ssl_con) || exit;
}
# close useless pipes
if ($config{'passdelay'} || $config{'session'}) {
local $p;
foreach $p (@passin) { close($p); }
foreach $p (@passout) { close($p); }
close($PASSINr); close($PASSOUTw);
}
&close_all_sockets();
close(LISTEN);
while(&handle_request($acptaddr, getsockname(SOCK))) { }
shutdown(SOCK, 1);
close(SOCK);
close($PASSINw); close($PASSOUTw);
exit;
}
push(@childpids, $handpid);
if ($config{'passdelay'} || $config{'session'}) {
close($PASSINw); close($PASSOUTr);
push(@passin, $PASSINr); push(@passout, $PASSOUTw);
}
close(SOCK);
}
$sn++;
}
if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
# Got UDP packet from another webmin server
local $rcvbuf;
local $from = recv(LISTEN, $rcvbuf, 1024, 0);
next if (!$from);
local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
local $toip = inet_ntoa((unpack_sockaddr_in(
getsockname(LISTEN)))[1]);
if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
(!@allow || &ip_match($fromip, $toip, @allow))) {
local $listenhost = &get_socket_name(LISTEN);
send(LISTEN, "$listenhost:$config{'port'}:".
($use_ssl || $config{'inetd_ssl'} ? 1 : 0),
0, $from)
if ($listenhost);
}
}
# check for password-timeout messages from subprocesses
for($i=0; $i<@passin; $i++) {
if (vec($rmask, fileno($passin[$i]), 1)) {
# this sub-process is asking about a password
local $infd = $passin[$i];
local $outfd = $passout[$i];
local $inline = <$infd>;
if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
# Got a delay request from a subprocess.. for
# valid logins, there is no delay (to prevent
# denial of service attacks), but for invalid
# logins the delay increases with each failed
# attempt.
if ($3) {
# login OK.. no delay
print $outfd "0 0\n";
$hostfail{$2} = 0;
}
else {
# login failed..
$hostfail{$2}++;
# add the host to the block list if necessary
if ($config{'blockhost_failures'} &&
$hostfail{$2} >= $config{'blockhost_failures'}) {
push(@deny, $2);
$blockhosttime{$2} = $time_now;
$blocked = 1;
if ($use_syslog) {
local $logtext = "Security alert: Host $2 ".
"blocked after $config{'blockhost_failures'} ".
"failed logins for user $1";
syslog("crit", $logtext);
}
}
else {
$blocked = 0;
}
$dl = $userdlay{$1} -
int(($time_now - $userlast{$1})/50);
$dl = $dl < 0 ? 0 : $dl+1;
print $outfd "$dl $blocked\n";
$userdlay{$1} = $dl;
}
$userlast{$1} = $time_now;
}
elsif ($inline =~ /^verify\s+(\S+)/) {
# Verifying a session ID
local $session_id = $1;
if (!defined($sessiondb{$session_id})) {
# Session doesn't exist
print $outfd "0 0\n";
}
else {
local ($user, $ltime) = split(/\s+/, $sessiondb{$session_id});
if ($config{'logouttime'} &&
$time_now - $ltime > $config{'logouttime'}*60) {
# Session has timed out
print $outfd "1 ",$time_now - $ltime,"\n";
#delete($sessiondb{$session_id});
}
else {
# Session is OK
print $outfd "2 $user\n";
if ($config{'logouttime'} &&
$time_now - $ltime > ($config{'logouttime'}*60)/2) {
$sessiondb{$session_id} = "$user $time_now";
}
}
}
}
elsif ($inline =~ /^new\s+(\S+)\s+(\S+)/) {
# Creating a new session
$sessiondb{$1} = "$2 $time_now";
}
elsif ($inline =~ /^delete\s+(\S+)/) {
# Logging out a session
local $sid = $1;
local @sdb = split(/\s+/, $sessiondb{$sid});
print $outfd $sdb[0],"\n";
delete($sessiondb{$sid});
}
else {
# close pipe
close($infd); close($outfd);
$passin[$i] = $passout[$i] = undef;
}
}
}
@passin = grep { defined($_) } @passin;
@passout = grep { defined($_) } @passout;
}
# handle_request(remoteaddress, localaddress)
# Where the real work is done
sub handle_request
{
$acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
$localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
if ($config{'loghost'}) {
$acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
$acpthost = $acptip if (!$acpthost);
}
else {
$acpthost = $acptip;
}
$datestr = &http_date(time());
$ok_code = 200;
$ok_message = "Document follows";
$logged_code = undef;
$reqline = $request_uri = $page = undef;
# Wait at most 60 secs for start of headers for initial requests, or
# 10 minutes for kept-alive connections
local $rmask;
vec($rmask, fileno(SOCK), 1) = 1;
local $sel = select($rmask, undef, undef, $checked_timeout ? 10*60 : 60);
if (!$sel) {
if ($checked_timeout) { exit; }
else { &http_error(400, "Timeout"); }
}
$checked_timeout++;
# Read the HTTP request and headers
local $origreqline = &read_line();
($reqline = $origreqline) =~ s/\r|\n//g;
$method = $page = $request_uri = undef;
if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
# An empty request .. just close the connection
return 0;
}
elsif ($reqline !~ /^(GET|POST|HEAD)\s+(.*)\s+HTTP\/1\..$/) {
if ($use_ssl) {
# This could be an http request when it should be https
$use_ssl = 0;
local $url = "https://$host:$port/";
if ($config{'ssl_redirect'}) {
# Just re-direct to the correct URL
&write_data("HTTP/1.0 302 Moved Temporarily\r\n");
&write_data("Date: $datestr\r\n");
&write_data("Server: $config{'server'}\r\n");
&write_data("Location: $url\r\n");
&write_keep_alive(0);
&write_data("\r\n");
return 0;
}
else {
# Tell user the correct URL
&http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
}
}
elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
# This could be an https request when it should be http ..
# need to fake a HTTP response
eval <<'EOF';
use Net::SSLeay;
eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
eval "Net::SSLeay::load_error_strings()";
$ssl_ctx = Net::SSLeay::CTX_new();
Net::SSLeay::CTX_use_RSAPrivateKey_file(
$ssl_ctx, $config{'keyfile'},
&Net::SSLeay::FILETYPE_PEM);
Net::SSLeay::CTX_use_certificate_file(
$ssl_ctx,
$config{'certfile'} || $config{'keyfile'},
&Net::SSLeay::FILETYPE_PEM);
$ssl_con = Net::SSLeay::new($ssl_ctx);
pipe(SSLr, SSLw);
if (!fork()) {
close(SSLr);
select(SSLw); $| = 1; select(STDOUT);
print SSLw $origreqline;
local $buf;
while(sysread(SOCK, $buf, 1) > 0) {
print SSLw $buf;
}
close(SOCK);
exit;
}
close(SSLw);
Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
Net::SSLeay::accept($ssl_con) || die "accept() failed";
$use_ssl = 1;
local $url = "http://$host:$port/";
if ($config{'ssl_redirect'}) {
# Just re-direct to the correct URL
&write_data("HTTP/1.0 302 Moved Temporarily\r\n");
&write_data("Date: $datestr\r\n");
&write_data("Server: $config{'server'}\r\n");
&write_data("Location: $url\r\n");
&write_keep_alive(0);
&write_data("\r\n");
return 0;
}
else {
# Tell user the correct URL
&http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
}
EOF
if ($@) {
&http_error(400, "Bad Request");
}
}
else {
&http_error(400, "Bad Request");
}
}
$method = $1;
$request_uri = $page = $2;
%header = ();
local $lastheader;
while(1) {
($headline = &read_line()) =~ s/\r|\n//g;
last if ($headline eq "");
if ($headline =~ /^(\S+):\s*(.*)$/) {
$header{$lastheader = lc($1)} = $2;
}
elsif ($headline =~ /^\s+(.*)$/) {
$header{$lastheader} .= $headline;
}
else {
&http_error(400, "Bad Header $headline");
}
}
if (defined($header{'host'})) {
if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) { $host = $1; $port = $2; }
else { $host = $header{'host'}; }
if ($config{'musthost'} && $host ne $config{'musthost'}) {
# Disallowed hostname used
&http_error(400, "Invalid HTTP hostname");
}
}
undef(%in);
if ($page =~ /^([^\?]+)\?(.*)$/) {
# There is some query string information
$page = $1;
$querystring = $2;
if ($querystring !~ /=/) {
$queryargs = $querystring;
$queryargs =~ s/\+/ /g;
$queryargs =~ s/%(..)/pack("c",hex($1))/ge;
$querystring = "";
}
else {
# Parse query-string parameters
local @in = split(/\&/, $querystring);
foreach $i (@in) {
local ($k, $v) = split(/=/, $i, 2);
$k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
$v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
$in{$k} = $v;
}
}
}
$posted_data = undef;
if ($method eq 'POST' &&
$header{'content-type'} eq 'application/x-www-form-urlencoded') {
# Read in posted query string information, up the configured maximum
# post request length
$clen = $header{"content-length"};
$clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
while(length($posted_data) < $clen_read) {
$buf = &read_data($clen_read - length($posted_data));
if (!length($buf)) {
&http_error(500, "Failed to read POST request");
}
chomp($posted_data);
$posted_data =~ s/\015$//mg;
$posted_data .= $buf;
}
if ($clen_read != $clen) {
# If the client sent more data than we asked for, chop the
# rest off
$posted_data = substr($posted_data, 0, $clen)
if (length($posted_data) > $clen);
}
#$posted_data =~ s/\r|\n//g; # some browsers include an extra newline
# # in the data!
local @in = split(/\&/, $posted_data);
foreach $i (@in) {
local ($k, $v) = split(/=/, $i, 2);
$k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
$v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
$in{$k} = $v;
}
}
# replace %XX sequences in page
$page =~ s/%(..)/pack("c",hex($1))/ge;
# check address against access list
if (@deny && &ip_match($acptip, $localip, @deny) ||
@allow && !&ip_match($acptip, $localip, @allow)) {
&http_error(403, "Access denied for $acptip");
return 0;
}
if ($use_libwrap) {
# Check address with TCP-wrappers
if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN, $acptip, STRING_UNKNOWN)) {
&http_error(403, "Access denied for $acptip");
return 0;
}
}
# check for the logout flag file, and if existant deny authentication
if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
$deny_authentication++;
open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
chop($count = <LOGOUT>);
close(LOGOUT);
$count--;
if ($count > 0) {
open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
print LOGOUT "$count\n";
close(LOGOUT);
}
else {
unlink($config{'logout'}.$in{'miniserv_logout_id'});
}
}
# check for any redirect for the requested URL
$simple = &simplify_path($page, $bogus);
$rpath = $simple;
$rpath .= "&".$querystring if (defined($querystring));
$redir = $redirect{$rpath};
if (defined($redir)) {
&write_data("HTTP/1.0 302 Moved Temporarily\r\n");
&write_data("Date: $datestr\r\n");
&write_data("Server: $config{'server'}\r\n");
local $ssl = $use_ssl || $config{'inetd_ssl'};
$portstr = $port == 80 && !$ssl ? "" :
$port == 443 && $ssl ? "" : ":$port";
$prot = $ssl ? "https" : "http";
&write_data("Location: $prot://$host$portstr$redir\r\n");
&write_keep_alive(0);
&write_data("\r\n");
return 0;
}