Include accountname in totp url
[mirror/userdir-ldap-cgi.git] / update.cgi
index c0d722b..3cf1900 100755 (executable)
@@ -1,15 +1,23 @@
 #!/usr/bin/perl
 
-# $Id: update.cgi,v 1.2 1999/09/26 01:20:39 tausq Exp $
+# $Id: update.cgi,v 1.13 2006/12/28 02:44:02 rmurray Exp $
 # (c) 1999 Randolph Chung. Licensed under the GPL. <tausq@debian.org>
+# (c) 2006 Ryan Murray. Licensed under the GPL. <rmurray@debian.org>
+# Copyright (c) 2008, 2011, 2012, 2014, 2015 Peter Palfrader
 
 use lib '.';
 use strict vars;
 #use Apache::Registry;
 use CGI;
+use Data::UUID;
+use Digest::HMAC_SHA1 qw(hmac_sha1_hex);
+use Digest::MD5 qw(md5_hex);
 use Util;
+use English;
 use URI::Escape;
-use Net::LDAP qw(:all);
+use Crypt::PasswdMD5;
+use Net::LDAP qw(LDAP_SUCCESS LDAP_PROTOCOL_ERROR);
+use Net::LDAP::Util qw(ldap_explode_dn);
 
 my %config = &Util::ReadConfigFile;
 
@@ -18,23 +26,38 @@ my $proto = ($ENV{HTTPS} ? "https" : "http");
 
 my $id = $query->param('id');
 my $authtoken = $query->param('authtoken');
-my $password = &Util::CheckAuthToken($authtoken);
-my $editdn = $query->param('editdn');
 
-if (!($id && $password)) {
-  print "Location: $proto://$ENV{SERVER_NAME}/$config{webloginurl}\n\n";
+my $password = undef;
+
+if ($authtoken || $id) {
+  $password = Util::TouchAuthToken($authtoken, $id);
+} else {
+  $password = '';
+  $id = '';
+  $authtoken = '';
+}
+
+if ($proto eq "http" || !($id && $password)) {
+  print "Location: https://$ENV{SERVER_NAME}/$config{webloginhtml}\n\n";
   exit;
-} 
+}
 
 my $ldap;
 
+open (F, "<$config{passdir}/key-hmac-$UID") || &Util::HTMLError($!);
+my $hmac_key = <F>;
+close(F);
+chomp($hmac_key);
+
 sub DieHandler {
   $ldap->unbind if (defined($ldap));
 }
 
-$SIG{__DIE__} = \&DieHandler;
+#$SIG{__DIE__} = \&DieHandler;
+my $editdn = "uid=$id,$config{basedn}";
 
 $ldap = Net::LDAP->new($config{ldaphost});
+&Util::UpgradeConnection($ldap) unless $config{usessl} eq 'False';
 my $auth = 0;
 my $mesg;
 $mesg = $ldap->bind($editdn, password => $password);
@@ -43,7 +66,7 @@ $auth = ($mesg->code == LDAP_SUCCESS);
 
 if (!$auth) {
   $ldap->unbind;
-  &Util::HTMLError("You have not been authenticated. Please <a href=\"$proto://$ENV{SERVER_NAME}/$config{webloginurl}\">Login</a>");
+  &Util::HTMLError("You have not been authenticated. Please <a href=\"https://$ENV{SERVER_NAME}/$config{webloginhtml}\">Login</a>");
 }
 
 # Authenticated....
@@ -51,34 +74,115 @@ if (!$auth) {
 $mesg = $ldap->search(base   => $editdn,
                       filter => "uid=*");
 $mesg->code && &Util::HTMLError($mesg->error);
-  
+
 my $entries = $mesg->as_struct;
 if ($mesg->count != 1) {
   # complain and quit
 }
-  
+
+$mesg = $ldap->search(base  => $config{hostbasedn}, filter => 'host=*');
+$mesg->code && &Util::HTMLError($mesg->error);
+my $host_entries = $mesg->as_struct;
+
 my @dns = keys(%$entries);
 my $entry = $entries->{$dns[0]};
 
 if (!($query->param('doupdate'))) {
   # Not yet update, just fill in the form with the current values
   my %data;
-  
+
   # Fill in %data
   # First do the easy stuff - this catches most of the cases
   foreach (keys(%$entry)) {
     $data{$_} = $entry->{$_}->[0];
+    $data{$_} = CGI::escapeHTML($data{$_}) if defined $data{$_};
   }
-  
+
   # Now we have to fill in the rest that needs some processing...
   $data{id} = $id;
   $data{authtoken} = $authtoken;
   $data{editdn} = $editdn;
   $data{staddress} = $entry->{postaladdress}->[0];
   $data{staddress} =~ s/\$/\n/;
+  $data{staddress} = CGI::escapeHTML($data{staddress});
   $data{countryname} = &Util::LookupCountry($data{c});
-  
-  $data{email} = join(", ", @{$entry->{emailforward}});  
+
+  if ($data{mailgreylisting} eq "TRUE") {
+    $data{mailgreylisting} = " checked";
+  } else {
+    $data{mailgreylisting} = "";
+  }
+
+  if ($data{mailcallout} eq "TRUE") {
+    $data{mailcallout} = " checked";
+  } else {
+    $data{mailcallout} = "";
+  }
+
+  $data{maildefaultoptions} ||= 'TRUE';
+
+  if ($data{maildefaultoptions} eq "TRUE") {
+    $data{maildefaultoptions} = " checked";
+  } else {
+    $data{maildefaultoptions} = "";
+  }
+
+  $data{mailcontentinspectionaction} ||= 'reject';
+
+  $data{email} = CGI::escapeHTML(join(", ", @{$entry->{emailforward}}));
+
+  my $mailcontentselect = '<select name="mailcontentinspection">'
+                        . '<option value="blackhole"'
+                        . ($data{mailcontentinspectionaction} eq 'blackhole' ? ' selected' : '')
+                        . '>blackhole'
+                        . '<option value="markup"'
+                        . ($data{mailcontentinspectionaction} eq 'markup' ? ' selected' : '')
+                        . '>markup'
+                        . '<option value="reject"'
+                        . ($data{mailcontentinspectionaction} eq 'reject' ? ' selected' : '')
+                        . '>reject';
+
+  my $confirmstring = '';
+  my $sudopassword = '';
+  for my $e(@{$entry->{'sudopassword'}}) {
+    my ($uuid, $status, $hosts, $crypted) = ($e =~ /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*-]+) ([^ ]+)$/);
+    unless (defined $uuid) {
+      $sudopassword .= "<tr><td>Unparseable line!</td></tr>\n";
+      next;
+    }
+    if ($status =~ /^confirmed:/) {
+      my $data = join(':', 'password-is-confirmed', 'sudo', $data{'uid'}, $uuid, $hosts, $crypted);
+      my $hmac = hmac_sha1_hex( $data, $hmac_key);
+      if ($status eq "confirmed:$hmac") {
+        $status = 'confirmed';
+      } else {
+        $status = 'INVALID';
+      }
+    }
+    my $e = "<tr><td>".CGI::escapeHTML($hosts)."</td>
+                 <td>".CGI::escapeHTML($status)."</td>
+                 <td><small>not shown</small></td>
+                 <!--<td><small><code>".CGI::escapeHTML($uuid)."</code></small></td>-->
+                 <td><input name=\"sudopassword-delete-".CGI::escapeHTML($uuid)."\" type=\"checkbox\" value=\"delete\"> (delete)</td></tr>\n";
+    $sudopassword .= $e;
+    if ($status eq 'unconfirmed') {
+      my $data = join(':', 'confirm-new-password', 'sudo', $data{'uid'}, $uuid, $hosts, $crypted);
+      my $hmac = hmac_sha1_hex( $data, $hmac_key);
+      $confirmstring .= CGI::escapeHTML("confirm sudopassword $uuid $hosts $hmac\n");
+    }
+  };
+  if ($confirmstring ne '') {
+    $confirmstring = "<br>To confirm your new sudo passwords send signed mail to changes\@$config{maildomain} with a signed body containing these lines:<br><pre>$confirmstring</pre>";
+  }
+
+  my $sudopasswordhosts = '<select name="newsudopass-host"> <option value="*">ALL';
+  for my $dn (sort {$host_entries->{$a}->{host}->[0] cmp $host_entries->{$b}->{host}->[0]} keys(%$host_entries)) {
+      my $data = $host_entries->{$dn};
+      my $host = $data->{'host'}->[0];
+      my $hostname = $data->{'hostname'}->[0];
+      $sudopasswordhosts .= "<option value=\"$hostname\">$host\n";
+  };
+  $sudopasswordhosts .= '</select>';
 
   # finally we can send output...
   my ($sub, $substr);
@@ -86,68 +190,209 @@ if (!($query->param('doupdate'))) {
   open (F, "<$config{webupdatehtml}") || &Util::HTMLError($!);
   while (<F>) {
     s/~(.+?)~/$data{$1}/g;
+    s/<\?mailcontentselect>/$mailcontentselect/;
+    s/<\?sudopassword>/$sudopassword/;
+    s/<\?sudopasswordhosts>/$sudopasswordhosts/;
+    s/<\?confirmstring>/$confirmstring/;
     print;
   }
   close F;
-  
 } else {
+  my @ldapinfo_for_pwcheck;
+  for my $a (qw{cn sn md gecos uid}) {
+    for my $e (@{$entry->{$a}}) {
+      push @ldapinfo_for_pwcheck, $e;
+    }
+  }
+
+
   # Actually update stuff...
-  my ($newpassword, $newstaddress);
-  
+  my ($newpassword, $newstaddress, $newwebpassword, $newrtcpassword);
+
+  # Good god, why would we want to do that here?  it breaks password setting
+  # etc, and it doesn't prevent people from setting eveil stuff in ldap
+  # directly.
+  # &Util::FixParams($query);
+
+  if (($query->param('labeleduri')) &&
+      ($query->param('labeleduri') !~ /^https?:\/\//i)) {
+    &Util::HTMLError("Your homepage URL is invalid");
+  }
+
   if ($query->param('newpass') && $query->param('newpassvrfy')) {
     if ($query->param('newpass') ne $query->param('newpassvrfy')) {
       # passwords don't match...
       &Util::HTMLError("The passwords you specified do not match. Please go back and try again.");
-    }    
+    }
+
+    my ($r, $msg) = &Util::checkPasswordQuality($query->param('newpass'), undef, [@ldapinfo_for_pwcheck]);
+    if ($r) {
+      &Util::HTMLError("Password check failed: $msg.  Please go back and try again.");
+    }
+
     # create a md5 crypted password
     $newpassword = '{crypt}'.crypt($query->param('newpass'), &Util::CreateCryptSalt(1));
-    
-    LDAPUpdate($ldap, $editdn, 'userPassword', $newpassword);
+
+    &Util::LDAPUpdate($ldap, $editdn, 'userPassword', $newpassword);
     &Util::UpdateAuthToken($authtoken, $query->param('newpass'));
-  }  
+  }
+
+  if ($query->param('newwebpass') && $query->param('newwebpassvrfy')) {
+    if ($query->param('newwebpass') ne $query->param('newwebpassvrfy')) {
+      # passwords don't match...
+      &Util::HTMLError("The web-passwords you specified do not match. Please go back and try again.");
+    }
+
+    my ($r, $msg) = &Util::checkPasswordQuality($query->param('newwebpass'), undef, [@ldapinfo_for_pwcheck]);
+    if ($r) {
+      &Util::HTMLError("Password check failed for web-password: $msg.  Please go back and try again.");
+    }
+
+    # create a md5 crypted password
+    $newwebpassword = apache_md5_crypt($query->param('newwebpass'), &Util::CreateCryptSalt(1, 1));
+
+    &Util::LDAPUpdate($ldap, $editdn, 'webPassword', $newwebpassword);
+  }
+  if ($query->param('newrtcpass') && $query->param('newrtcpassvrfy')) {
+    if ($query->param('newrtcpass') ne $query->param('newrtcpassvrfy')) {
+      # passwords don't match...
+      &Util::HTMLError("The rtc-passwords you specified do not match. Please go back and try again.");
+    }
+
+    my ($r, $msg) = &Util::checkPasswordQuality($query->param('newrtcpass'), undef, [@ldapinfo_for_pwcheck]);
+    if ($r) {
+      &Util::HTMLError("Password check failed for rtc-password: $msg.  Please go back and try again.");
+    }
+    # create a md5 crypted password
+    $newrtcpassword = &md5_hex( ldap_explode_dn($editdn)->[0]{UID} . '@debian.org:rtc.debian.org:' . $query->param('newrtcpass') );
+
+    &Util::LDAPUpdate($ldap, $editdn, 'rtcPassword', $newrtcpassword);
+  }
 
   $newstaddress = $query->param('staddress');
   $newstaddress =~ s/\n/\$/m;
-  
+
+  my ($bd_ok, $bd_yr, $bd_mo, $bd_day);
+
+  if ($query->param('birthdate') =~ /^([1-9][0-9]{3})([01][0-9])([0-3][0-9])$/) {
+    $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
+    if ($bd_yr > 1850 and $bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
+      if ($bd_mo == 2) {
+        if ($bd_day == 29 and ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0))) {
+          $bd_ok = 1;
+        } elsif ($bd_day <= 28) {
+          $bd_ok = 1;
+        }
+      } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
+       if ($bd_day <= 30) {
+         $bd_ok = 1;
+       }
+      } else {
+       if ($bd_day <= 31) {
+         $bd_ok = 1;
+       }
+      }
+    }
+  } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
+    $bd_ok = 1;
+  }
   my ($lat, $long);
-  ($lat, $long) = &Util::CheckLatLong($query->param('latitude'), 
+  ($lat, $long) = &Util::CheckLatLong($query->param('latitude'),
                                       $query->param('longitude'));
-  
-  LDAPUpdate($ldap, $editdn, 'postalAddress', $newstaddress);
-  LDAPUpdate($ldap, $editdn, 'l', $query->param('l'));
-  LDAPUpdate($ldap, $editdn, 'latitude', $lat);
-  LDAPUpdate($ldap, $editdn, 'longitude', $long);
-  LDAPUpdate($ldap, $editdn, 'c', $query->param('country'));
-  LDAPUpdate($ldap, $editdn, 'postalcode', $query->param('postalcode'));
-  LDAPUpdate($ldap, $editdn, 'telephoneNumber', $query->param('telephonenumber'));
-  LDAPUpdate($ldap, $editdn, 'facsimileTelephoneNumber', $query->param('facsimiletelephonenumber'));
-  LDAPUpdate($ldap, $editdn, 'loginShell', $query->param('loginshell'));
-  LDAPUpdate($ldap, $editdn, 'emailForward', $query->param('email'));
-  LDAPUpdate($ldap, $editdn, 'privatesub', $query->param('privatesub'));
-  LDAPUpdate($ldap, $editdn, 'ircNick', $query->param('ircnick'));
-  LDAPUpdate($ldap, $editdn, 'labeledUrl', $query->param('labeledurl'));
-  LDAPUpdate($ldap, $editdn, 'onvacation', $query->param('onvacation'));
+  my ($greylisting, $callout, $mailcontentinspection, $defaultoptions);
 
-  # when we are done, reload the page with the updated details.
-  my $url = "$proto://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id&authtoken=$authtoken&editdn=";
-  $url .= uri_escape($editdn, "\x00-\x40\x7f-\xff");
-  print "Location: $url\n\n";  
-}
+  $greylisting = $query->param('mailgreylisting');
+  if (!$greylisting or $greylisting ne "TRUE") {
+     $greylisting = "FALSE";
+  }
 
-$ldap->unbind;
+  $callout = $query->param('mailcallout');
+  if (!$callout or $callout ne "TRUE") {
+     $callout = "FALSE";
+  }
 
-sub LDAPUpdate {
-  my $ldap = shift;
-  my $dn = shift;
-  my $attr = shift;
-  my $val = shift;
-  my $mesg;
-  
-  if (!$val) {
-    $mesg = $ldap->modify($dn, delete => { $attr => [] });
-  } else {
-    $val = [ $val ] if (!ref($val));
-    $mesg = $ldap->modify($dn, replace => { $attr => $val });
-    $mesg->code && &Util::HTMLError("error updating $attr: ".$mesg->error);
+  $mailcontentinspection = $query->param('mailcontentinspection');
+  if (!$mailcontentinspection or ($mailcontentinspection ne "blackhole" and $mailcontentinspection ne "markup")) {
+     $mailcontentinspection = "reject";
+  }
+
+  $defaultoptions = $query->param('maildefaultoptions');
+  if (!$defaultoptions or $defaultoptions ne "TRUE") {
+     $defaultoptions = "FALSE";
   }
+
+  my $newsudo;
+  my $newsudo_hosts;
+  if ($query->param('newsudopass') && $query->param('newsudopassvrfy')) {
+    my $host = $query->param('newsudopass-host');
+    if ($host =~ /[^a-z0-9.-]/ and $host ne '*') {
+      &Util::HTMLError("The sudo host has weird characters '$host'.");
+    }
+
+    if ($query->param('newsudopass') ne $query->param('newsudopassvrfy')) {
+      &Util::HTMLError("The sudo passwords you specified do not match. Please go back and try again.");
+    }
+
+    my $ldappass = $password;
+    $ldappass = $query->param('newpass') if $query->param('newpass');
+    push @ldapinfo_for_pwcheck, $host, split(/\./, $host);
+    my ($r, $msg) = &Util::checkPasswordQuality($query->param('newsudopass'), $ldappass, [@ldapinfo_for_pwcheck]);
+    if ($r) {
+      &Util::HTMLError("Password check failed for new sudo pass: $msg.  Please go back and try again.");
+    }
+
+    # create a md5 crypted password
+    my $newsudopassword = crypt($query->param('newsudopass'), &Util::CreateCryptSalt(1));
+    my $ug = new Data::UUID;
+    my $uuid = $ug->create_str();
+
+    $newsudo = "$uuid unconfirmed $host $newsudopassword";
+    $newsudo_hosts = $host;
+  }
+
+  my %delete_uuids = map { s/^sudopassword-delete-//; $_ => 1} grep { $query->param($_) eq 'delete' } grep { /^sudopassword-delete-/ } $query->param;
+  my @keepsudo;
+  for my $entry (@{$entry->{'sudopassword'}}) {
+    my ($uuid, $status, $hosts, $crypted) = ($entry =~ /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*-]+) ([^ ]+)$/);
+    next unless defined ($uuid);
+    next if (defined $delete_uuids{$uuid});
+    my %hosts = map { $_ => 1 } split(/,/, $hosts);
+    next if ($hosts{$newsudo_hosts});
+    push @keepsudo, $entry;
+  };
+  if ($newsudo ne '') {
+    push @keepsudo, $newsudo;
+  }
+
+  &Util::LDAPUpdate($ldap, $editdn, 'postalAddress', $newstaddress);
+  &Util::LDAPUpdate($ldap, $editdn, 'l', $query->param('l'));
+  &Util::LDAPUpdate($ldap, $editdn, 'latitude', $lat);
+  &Util::LDAPUpdate($ldap, $editdn, 'longitude', $long);
+  &Util::LDAPUpdate($ldap, $editdn, 'c', $query->param('country'));
+  &Util::LDAPUpdate($ldap, $editdn, 'postalCode', $query->param('postalcode'));
+  &Util::LDAPUpdate($ldap, $editdn, 'telephoneNumber', $query->param('telephonenumber'));
+  &Util::LDAPUpdate($ldap, $editdn, 'facsimileTelephoneNumber', $query->param('facsimiletelephonenumber'));
+  &Util::LDAPUpdate($ldap, $editdn, 'bATVToken', $query->param('bATVToken'));
+  &Util::LDAPUpdate($ldap, $editdn, 'VoIP', $query->param('VoIP'));
+  &Util::LDAPUpdate($ldap, $editdn, 'loginShell', $query->param('loginshell'));
+  &Util::LDAPUpdate($ldap, $editdn, 'emailForward', $query->param('email'));
+  &Util::LDAPUpdate($ldap, $editdn, 'privateSub', $query->param('privatesub'));
+  &Util::LDAPUpdate($ldap, $editdn, 'ircNick', $query->param('ircnick'));
+  &Util::LDAPUpdate($ldap, $editdn, 'icqUin', $query->param('icquin'));
+  &Util::LDAPUpdate($ldap, $editdn, 'jabberJID', $query->param('jabberjid'));
+  &Util::LDAPUpdate($ldap, $editdn, 'labeledURI', $query->param('labeleduri'));
+  &Util::LDAPUpdate($ldap, $editdn, 'onVacation', $query->param('onvacation'));
+  &Util::LDAPUpdate($ldap, $editdn, 'birthDate', $query->param('birthdate')) if $bd_ok;
+  &Util::LDAPUpdate($ldap, $editdn, 'mailDisableMessage', $query->param('maildisablemessage'));
+  &Util::LDAPUpdate($ldap, $editdn, 'mailCallout', $callout);
+  &Util::LDAPUpdate($ldap, $editdn, 'mailContentInspectionAction', $mailcontentinspection);
+  &Util::LDAPUpdate($ldap, $editdn, 'mailGreylisting', $greylisting);
+  &Util::LDAPUpdate($ldap, $editdn, 'mailDefaultOptions', $defaultoptions);
+  &Util::LDAPUpdate($ldap, $editdn, 'sudoPassword', \@keepsudo);
+
+  # when we are done, reload the page with the updated details.
+  my $url = "https://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id;authtoken=$authtoken";
+  print "Location: $url\n\n";
 }
+
+$ldap->unbind;