3 # Copyright (c) 1999-2006 Debian Admin Team Members and Developers (taken from debian/copyright in 2008 by weasel)
4 # Copyright (c) 2002, 2003, 2004, 2008 Peter Palfrader
9 use Date::Manip qw(ParseDate);
10 use Net::LDAP qw(LDAP_SUCCESS LDAP_PROTOCOL_ERROR);
13 my $blocksize = 8; # A blowfish block is 8 bytes
14 my $configfile = "/etc/userdir-ldap/userdir-ldap.conf";
15 #my $configfile = "/home/randolph/html/debian/perl/userdir-ldap.conf";
17 my %config = &ReadConfigFile;
20 eval 'use Crypt::Blowfish';
28 open (F, "</dev/urandom") || die &HTMLError("No /dev/urandom found!");
29 read(F, $input, $keysize); # key length is 8 bytes
36 # CreateCryptSalt(type = 0, skip_header = 0)
37 # this can create either a DES type salt or a MD5 salt
38 # 0 for DES, 1 for MD5 salt
39 # if skip_header is 0, does not add $1$ for md5 salts.
40 my $md5 = shift; # do we want a MD5 salt?
41 my $no_crypttype_header = shift;
42 my $validstr = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
43 my @valid = split(//,$validstr);
46 my $cryptsaltlen = ($md5 ? 8 : 2);
48 open (F, "</dev/urandom") || die &HTMLError("No /dev/urandom found!");
49 foreach (1..$cryptsaltlen) {
51 $out .= $valid[ord($in) % ($#valid + 1)];
54 if ($md5 == 1 && !$no_crypttype_header) { $out = "\$1\$$out\$"; }
59 # blowfish only encrypts things in blocks of 8 bytes, so we
60 # need a custom routine that handles longer strings....
65 # prepend a length byte */
66 $input = chr(length($input)).$input;
67 $input .= "\001" x ($blocksize - (length($input) % $blocksize)) if (length($input % $blocksize));
69 for ($pos = 0; $pos < length($input); $pos += $blocksize) {
70 $output .= unpack("H16", $cipher->encrypt(substr($input, $pos, $blocksize))) if ($hascryptix);
76 # like encrypt, needs to deal with big blocks. Note that we assume
77 # trailing spaces are unimportant.
80 my ($pos, $portion, $output, $len);
82 ((length($input) % $blocksize) == 0) || &HTMLError("Password corrupted"); # should always be true...
84 for ($pos = 0; $pos < length($input); $pos += $blocksize*2) {
85 $portion = pack("H16", substr($input, $pos, $blocksize*2));
86 $output .= $cipher->decrypt($portion) if ($hascryptix);
89 # check length byte, discard junk
90 $len = substr($output, 0, 1);
91 $output = substr($output, 1, ord($len));
95 sub SavePasswordToFile {
100 my $cryptuser = crypt($userid, &CreateCryptSalt);
101 my $secret = Encrypt($cipher, $password);
102 $cryptuser =~ y/\//_/; # translate slashes to underscores...
104 my $fn = "$config{authtokenpath}/$cryptuser";
105 open (F, ">$fn") || &HTMLError("$fn: $!");
113 sub ReadPasswordFromFile {
119 $userid =~ y/\//_/; # translate slashes to underscores...
121 # if we couldn't read the password file, assume user is unauthenticated. is this ok?
122 open (F, "<$config{authtokenpath}/$userid") || return undef;
123 chomp($passwd = <F>);
127 # check to make sure we read something
128 return undef if (!$passwd || !$time);
130 # check to make sure the time is positive, and that the auth token
132 my $tdiff = (time - $time);
133 &HTMLError("Your authentication token has expired. Please <a href=\"https://$ENV{SERVER_NAME}/$config{webloginhtml}\">relogin</a>") if (($tdiff < 0) || ($tdiff > $config{authexpires}));
135 return Decrypt($cipher, $passwd);
139 my ($id, $hrkey) = split(/,/, shift, 2);
140 return undef if (!$id || !$hrkey);
141 my $key = pack("H".(length($hrkey)), $hrkey);
142 my $cipher = new Crypt::Blowfish $key;
143 my $r = ReadPasswordFromFile($id, $cipher);
145 UpdateAuthToken("$id,$hrkey", $r);
147 ClearAuthToken("$id,$hrkey")
153 my ($id, $hrkey) = split(/,/, shift, 2);
154 $id =~ y/\//_/; # switch / to _
155 unlink "$config{authtokenpath}/$id" || &HTMLError("Error removing authtoken: $!");
158 sub UpdateAuthToken {
159 my ($id, $hrkey) = split(/,/, shift, 2);
160 my $password = shift;
161 my $key = pack("H".(length($hrkey)), $hrkey);
162 $id =~ y/\//_/; # switch / to _
163 my $cipher = new Crypt::Blowfish $key;
164 my $secret = Encrypt($cipher, $password);
166 my $fn = "$config{authtokenpath}/$id";
167 open (F, ">$fn") || &HTMLError("$fn: $!");
171 chmod 0600, "$fn" || &HTMLError("$fn: $!");
175 sub FormatFingerPrint {
179 if (length($in) == 32) {
181 $out .= substr($in, $_*2, 2)." ";
182 $out .= " " if ($_ == 7);
185 foreach (0..int(length($in)/4)) {
186 $out .= substr($in, $_*4, 4)." ";
194 my $fingerprint = shift;
195 my $signatures = shift;
196 my ($out, $keyringparam) = undef;
198 foreach (split(/:/, $config{keyrings})) {
199 $keyringparam .= "--keyring $_ ";
202 $fingerprint =~ s/\s//g;
203 $fingerprint = "0x".$fingerprint;
205 local $ENV{PATH} = '';
206 $/ = undef; # just suck it up ....
208 open(FP, "$config{gpg} --no-options --no-default-keyring $keyringparam --list-sigs --fingerprint $fingerprint|");
212 open(FP, "$config{gpg} --no-options --no-default-keyring $keyringparam --export -a $fingerprint|");
220 sub FormatTimestamp {
222 $in =~ /^(....)(..)(..)(..)(..)(..)/;
224 return sprintf("%04d/%02d/%02d %02d:%02d:%02d UTC", $1,$2,$3,$4,$5,$6);
229 # [Tue, 11 Jan 2000 02:37:18] "Joey Hess <joeyh@debian.org>" "<debian-boot@lists.debian.org> archive/latest/7130" "<20000110181924.H19910@kitenet.net>"
230 # [Mon, 10 Jan 2000 21:48:19] "9E1E 1052 F8BB A351 0606 5527 50BB 2974 2D59 A7D2" "<debian-devel-changes@lists.debian.org> archive/latest/58632" "<20000110200506.13257.qmail@master.debian.org>"
231 my $lastseenpgp = shift;
232 my $lastseenfrom = shift;
233 my ($d1, $d2, $lastseen);
235 return "<b>No activity detected</b>" if (!$lastseenpgp && !$lastseenfrom);
236 $lastseen = $lastseenpgp;
237 $lastseen = $lastseenfrom if (!$lastseenpgp);
239 if ($lastseenfrom && $lastseenpgp) {
240 ($d1) = ($lastseenpgp =~ /^\[(.+?)\]/); $d1 = ParseDate($d1);
241 ($d2) = ($lastseenfrom =~ /^\[(.+?)\]/); $d2 = ParseDate($d2);
242 $lastseen = (($d1 gt $d2) ? $lastseenpgp : $lastseenfrom);
245 my ($date,$user,$list,$msgid) = ($lastseen =~ /^\[(.+?)\]\s+"(.+?)"\s+"(?:<(.+?)>.*?|\-)"\s+"(<.+?>)"/);
246 $list = "on $list" if ($list);
247 $date = CGI::escapeHTML($date);
248 $user = CGI::escapeHTML($user);
249 $list = CGI::escapeHTML($list);
250 $msgid = CGI::escapeHTML($msgid);
251 return "$date $list<br> Message ID: $msgid";
256 my ($abbrev, $country);
257 open (F, $config{countrylist}) || return uc($in);
260 ($abbrev, $country) = split(/\s+/, $_, 2);
261 if ($abbrev eq $in) {
276 print "Content-type: text/html; charset=utf-8\n\n" if (!$htmlhdrsent);
281 &HTMLSendHeader if (!$htmlhdrsent);
291 my ($lat, $long) = @_;
293 $lat =~ s/[^-+\.\d]//g; $long =~ s/[^-+\.\d]//g;
295 if (($lat =~ /^(\-|\+?)\d+(\.\d+)?/) && ($long =~ /^(\-|\+?)\d+(\.\d+)?/)) {
296 return ($lat, $long);
305 my @names = $query->param;
307 foreach $key (@names) { # web security is a joke ... <sigh>
308 $_ = $query->param($key);
313 $query->param($key, $_);
326 $mesg = $ldap->modify($dn, delete => { $attr => [] });
328 $val = [ $val ] if (!ref($val));
329 $mesg = $ldap->modify($dn, replace => { $attr => $val });
330 $mesg->code && &Util::HTMLError("error updating $attr: ".$mesg->error);
337 # reads a config file and results a hashref with the results
338 my (%config, $attr, $setting);
339 open (F, "<$configfile") || &HTMLError("Cannot open $configfile: $!");
342 if ((!/^\s*#/) && ($_ ne "")) {
343 # Chop off any trailing comments
346 ($attr, $setting) = ($1, $2);
347 $setting =~ s/"//g; #"
349 $attr =~ s/^\s+//; $attr =~ s/\s+$//;
350 $setting =~ s/^\s+//; $setting =~ s/\s+$//;
351 $config{$attr} = $setting;
358 sub UpgradeConnection($) {
360 my $mesg = $ldap->start_tls(
362 cafile => '/etc/ssl/certs/spi-cacert-2008.pem'
365 if ($mesg->code != LDAP_SUCCESS) {
366 print "Content-type: text/html; charset=utf-8\n\n";
367 print "<html><body><h1>STARTTLS failed: ".$mesg->error."</h1></body></html>\n";
372 sub readwrite3($$$$) {
373 my ($in, $inputfd, $stdoutfd, $stderrfd) = @_;
375 #Echolot::Log::trace("Entering readwrite_gpg.");
377 local $INPUT_RECORD_SEPARATOR = undef;
378 my $sout = IO::Select->new();
379 my $sin = IO::Select->new();
382 #Echolot::Log::trace("input is $inputfd; output is $stdoutfd; err is $stderrfd; status is ".(defined $statusfd ? $statusfd : 'undef').".");
384 $inputfd->blocking(0);
385 $stdoutfd->blocking(0);
386 $stderrfd->blocking(0);
387 $sout->add($stdoutfd);
388 $sout->add($stderrfd);
391 my ($stdout, $stderr) = ("", "", "");
393 my ($readyr, $readyw);
394 while ($sout->count() > 0 || (defined($sin) && ($sin->count() > 0))) {
395 #Echolot::Log::trace("select waiting for ".($sout->count())." fds.");
396 ($readyr, $readyw, undef) = IO::Select::select($sout, $sin, undef, 42);
397 #Echolot::Log::trace("ready: write: ".(defined $readyw ? scalar @$readyw : 'none')."; read: ".(defined $readyr ? scalar @$readyr : 'none'));
398 for my $wfd (@$readyw) {
399 #Echolot::Log::trace("writing to $wfd.");
401 if ($offset != length($in)) {
402 $written = $wfd->syswrite($in, length($in) - $offset, $offset);
404 unless (defined ($written)) {
405 #Echolot::Log::warn("Error while writing to GnuPG: $!");
411 if ($offset == length($in)) {
412 #Echolot::Log::trace("writing to $wfd done.");
420 next unless (defined(@$readyr)); # Wait some more.
422 for my $rfd (@$readyr) {
424 #Echolot::Log::trace("reading from $rfd done.");
429 #Echolot::Log::trace("reading from $rfd.");
430 if ($rfd == $stdoutfd) {
434 if ($rfd == $stderrfd) {
440 #Echolot::Log::trace("readwrite_gpg done.");
441 return ($stdout, $stderr);
444 sub checkPasswordQuality($$$) {
445 my ($pw, $oldpw, $ldapelements) = @_;
446 my ($stdinR, $stdinW) = (IO::Handle->new(), IO::Handle->new());
447 my ($stdoutR, $stdoutW) = (IO::Handle->new(), IO::Handle->new());
448 my ($stderrR, $stderrW) = (IO::Handle->new(), IO::Handle->new());
449 pipe $stdinR, $stdinW;
450 pipe $stdoutR, $stdoutW;
451 pipe $stderrR, $stderrW;
454 unless (defined $pid) {
455 return (2, "Could not fork: $!");
457 unless ($pid) { # child
464 open (STDIN, "<&".$stdinR->fileno) or warn ("Cannot dup stdinR (fd ".$stdinR->fileno.") as STDIN: $!");
465 open (STDOUT, ">&".$stdoutW->fileno) or warn ("Cannot dup stdoutW (fd ".$stdoutW->fileno.") as STDOUT: $!");
466 open (STDERR, ">&".$stderrW->fileno) or warn ("Cannot dup stderrW (fd ".$stderrW->fileno.") as STDERR: $!");
467 { exec('/usr/lib/userdir-ldap-cgi/password-qualify-check'); }
468 $stderrW->print("Could not exec password-qualify-check: $!\n");
475 $oldpw = '' unless defined $oldpw;
476 my $out = join("\n", $pw, $oldpw, @$ldapelements)."\n";
477 my ($stdout, $stderr) = readwrite3($out, $stdinW, $stdoutR, $stderrR);
480 my $exitcode = $? >> 8;
481 if ($exitcode == 0 && $stdout eq '' && $stderr eq '') {
483 } elsif ($exitcode == 1 && $stderr eq '') {
486 return (2, "check exited with exit code $exitcode, said '$stdout' on stdout, and '$stderr' on stderr.");