Implement password quality checking in update
[mirror/userdir-ldap-cgi.git] / update.cgi
1 #!/usr/bin/perl
2
3 # $Id: update.cgi,v 1.13 2006/12/28 02:44:02 rmurray Exp $
4 # (c) 1999 Randolph Chung. Licensed under the GPL. <tausq@debian.org>
5 # (c) 2006 Ryan Murray. Licensed under the GPL. <rmurray@debian.org>
6
7 use lib '.';
8 use strict vars;
9 #use Apache::Registry;
10 use CGI;
11 use Data::UUID;
12 use Digest::HMAC_SHA1 qw(hmac_sha1_hex);
13 use Util;
14 use English;
15 use URI::Escape;
16 use Net::LDAP qw(:all);
17
18 my %config = &Util::ReadConfigFile;
19
20 my $query = new CGI;
21 my $proto = ($ENV{HTTPS} ? "https" : "http");
22
23 my $id = $query->param('id');
24 my $authtoken = $query->param('authtoken');
25 my $password = &Util::CheckAuthToken($authtoken);
26 my $editdn = $query->param('editdn');
27
28 if ($proto eq "http" || !($id && $password)) {
29   print "Location: https://$ENV{SERVER_NAME}/$config{webloginhtml}\n\n";
30   exit;
31
32
33 my $ldap;
34
35 open (F, "<$config{passdir}/key-hmac-$UID") || &Util::HTMLError($!);
36 my $hmac_key = <F>;
37 close(F);
38 chomp($hmac_key);
39
40 sub DieHandler {
41   $ldap->unbind if (defined($ldap));
42 }
43
44 $SIG{__DIE__} = \&DieHandler;
45
46 $ldap = Net::LDAP->new($config{ldaphost});
47 &Util::UpgradeConnection($ldap) unless $config{usessl} eq 'False';
48 my $auth = 0;
49 my $mesg;
50 $mesg = $ldap->bind($editdn, password => $password);
51 $mesg->sync;
52 $auth = ($mesg->code == LDAP_SUCCESS);
53
54 if (!$auth) {
55   $ldap->unbind;
56   &Util::HTMLError("You have not been authenticated. Please <a href=\"https://$ENV{SERVER_NAME}/$config{webloginhtml}\">Login</a>");
57 }
58
59 # Authenticated....
60 # Get our entry...
61 $mesg = $ldap->search(base   => $editdn,
62                       filter => "uid=*");
63 $mesg->code && &Util::HTMLError($mesg->error);
64   
65 my $entries = $mesg->as_struct;
66 if ($mesg->count != 1) {
67   # complain and quit
68 }
69
70 $mesg = $ldap->search(base  => $config{hostbasedn}, filter => 'host=*');
71 $mesg->code && &Util::HTMLError($mesg->error);
72 my $host_entries = $mesg->as_struct;
73
74 my @dns = keys(%$entries);
75 my $entry = $entries->{$dns[0]};
76
77 if (!($query->param('doupdate'))) {
78   # Not yet update, just fill in the form with the current values
79   my %data;
80   
81   # Fill in %data
82   # First do the easy stuff - this catches most of the cases
83   foreach (keys(%$entry)) {
84     $data{$_} = $entry->{$_}->[0];
85   }
86   
87   $data{gender} = 9 if not $data{gender};
88
89   # Now we have to fill in the rest that needs some processing...
90   $data{id} = $id;
91   $data{authtoken} = $authtoken;
92   $data{editdn} = $editdn;
93   $data{staddress} = $entry->{postaladdress}->[0];
94   $data{staddress} =~ s/\$/\n/;
95   $data{countryname} = &Util::LookupCountry($data{c});
96
97   if ($data{mailgreylisting} eq "TRUE") {
98     $data{mailgreylisting} = " checked";
99   } else {
100     $data{mailgreylisting} = "";
101   }
102
103   if ($data{mailcallout} eq "TRUE") {
104     $data{mailcallout} = " checked";
105   } else {
106     $data{mailcallout} = "";
107   }
108   
109   $data{email} = join(", ", @{$entry->{emailforward}});  
110
111   my $genderselect = '<select name="gender">'
112                    . '<option value="9"'
113                    . ($data{gender} == 9 ? ' selected' : '')
114                    . '>unspecified'
115                    . '<option value="1"'
116                    . ($data{gender} == 1 ? ' selected' : '')
117                    . '>male<option value="2"'
118                    . ($data{gender} == 2 ? ' selected' : '')
119                    . '>female</select>';
120   my $confirmstring = '';
121   my $sudopassword = '';
122   for my $e(@{$entry->{'sudopassword'}}) {
123     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.,*]+) ([^ ]+)$/);
124     unless (defined $uuid) {
125       $sudopassword .= "<tr><td>Unparseable line!</td></tr>\n";
126       next;
127     }
128     $status =~ s/:.*//; # remove verification hmac, it's just noise here.
129     my $e = "<tr><td>$hosts</td>
130                  <td>$status</td>
131                  <td><small>not shown</small></td>
132                  <!--<td><small><code>$uuid</code></small></td>-->
133                  <td><input name=\"sudopassword-delete-$uuid\" type=\"checkbox\" value=\"delete\"> (delete)</td></tr>\n";
134     $sudopassword .= $e;
135     if ($status eq 'unconfirmed') {
136       my $data = join(':', 'confirm-new-password', $uuid, $hosts, $crypted);
137       my $hmac = hmac_sha1_hex( $data, $hmac_key);
138       $confirmstring .= "confirm sudopassword $uuid $hosts $hmac\n";
139     }
140   };
141   if ($confirmstring ne '') {
142     $confirmstring = "<br>To confirm your new sudo passwords send signed mail to changes\@db.debian.org with a signed body containing these lines:<br><pre>$confirmstring</pre>";
143   }
144
145   my $sudopasswordhosts = '<select name="newsudopass-host"> <option value="*">ALL';
146   for my $dn (sort {$host_entries->{$a}->{host}->[0] cmp $host_entries->{$b}->{host}->[0]} keys(%$host_entries)) {
147       my $data = $host_entries->{$dn};
148       my $host = $data->{'host'}->[0];
149       my $hostname = $data->{'hostname'}->[0];
150       $sudopasswordhosts .= "<option value=\"$hostname\">$host\n";
151   };
152   $sudopasswordhosts .= '</select>';
153
154   # finally we can send output...
155   my ($sub, $substr);
156   &Util::HTMLSendHeader;
157   open (F, "<$config{webupdatehtml}") || &Util::HTMLError($!);
158   while (<F>) {
159     s/~(.+?)~/$data{$1}/g;
160     s/<\?genderselect>/$genderselect/;
161     s/<\?sudopassword>/$sudopassword/;
162     s/<\?sudopasswordhosts>/$sudopasswordhosts/;
163     s/<\?confirmstring>/$confirmstring/;
164     print;
165   }
166   close F;
167 } else {
168   my @ldapinfo_for_pwcheck;
169   for my $a (qw{cn sn md gecos uid}) {
170     for my $e (@{$entry->{$a}}) {
171       push @ldapinfo_for_pwcheck, $e;
172     }
173   }
174
175
176   # Actually update stuff...
177   my ($newpassword, $newstaddress);
178   
179   &Util::FixParams($query);
180
181   if (($query->param('labeleduri')) && 
182       ($query->param('labeleduri') !~ /^https?:\/\//i)) {
183     &Util::HTMLError("Your homepage URL is invalid");
184   }
185   
186   if ($query->param('newpass') && $query->param('newpassvrfy')) {
187     if ($query->param('newpass') ne $query->param('newpassvrfy')) {
188       # passwords don't match...
189       &Util::HTMLError("The passwords you specified do not match. Please go back and try again.");
190     }
191
192     my ($r, $msg) = &Util::checkPasswordQuality($query->param('newpass'), undef, [@ldapinfo_for_pwcheck]);
193     if ($r) {
194       &Util::HTMLError("Password check failed: $msg.  Please go back and try again.");
195     }
196
197     # create a md5 crypted password
198     $newpassword = '{crypt}'.crypt($query->param('newpass'), &Util::CreateCryptSalt(1));
199     
200     &Util::LDAPUpdate($ldap, $editdn, 'userPassword', $newpassword);
201     &Util::UpdateAuthToken($authtoken, $query->param('newpass'));
202   }  
203
204   $newstaddress = $query->param('staddress');
205   $newstaddress =~ s/\n/\$/m;
206
207   my $gender = $query->param('gender');
208   if ($gender != 1 && $gender != 2) {
209     $gender = 9; # unspecified
210   }
211   
212   my ($bd_ok, $bd_yr, $bd_mo, $bd_day);
213
214   if ($query->param('birthdate') =~ /^([1-9][0-9]{3})([01][0-9])([0-3][0-9])$/) {
215     $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
216     if ($bd_yr > 1850 and $bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
217       if ($bd_mo == 2) {
218          if ($bd_day == 29 and ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0))) {
219            $bd_ok = 1;
220          } elsif ($bd_day <= 28) {
221            $bd_ok = 1;
222          }
223       } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
224         if ($bd_day <= 30) {
225           $bd_ok = 1;
226         }
227       } else {
228         if ($bd_day <= 31) {
229           $bd_ok = 1;
230         }
231       }
232     }
233   } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
234     $bd_ok = 1;
235   }
236   my ($lat, $long);
237   ($lat, $long) = &Util::CheckLatLong($query->param('latitude'), 
238                                       $query->param('longitude'));
239   my ($greylisting, $callout);
240
241   $greylisting = $query->param('mailgreylisting');
242   if (!$greylisting or $greylisting ne "TRUE") {
243      $greylisting = "FALSE";
244   }
245
246   $callout = $query->param('mailcallout');
247   if (!$callout or $callout ne "TRUE") {
248      $callout = "FALSE";
249   }
250
251   my $newsudo;
252   my $newsudo_hosts;
253   if ($query->param('newsudopass') && $query->param('newsudopassvrfy')) {
254     my $host = $query->param('newsudopass-host');
255     if ($host =~ /[^a-z0-9.-]/ and $host ne '*') {
256       &Util::HTMLError("The sudo host has weird characters '$host'.");
257     }
258
259     if ($query->param('newsudopass') ne $query->param('newsudopassvrfy')) {
260       &Util::HTMLError("The sudo passwords you specified do not match. Please go back and try again.");
261     }
262
263     my $ldappass = $password;
264     $ldappass = $query->param('newpass') if $query->param('newpass');
265     push @ldapinfo_for_pwcheck, $host, split(/\./, $host);
266     my ($r, $msg) = &Util::checkPasswordQuality($query->param('newsudopass'), $ldappass, [@ldapinfo_for_pwcheck]);
267     if ($r) {
268       &Util::HTMLError("Password check failed for new sudo pass: $msg.  Please go back and try again.");
269     }
270
271     # create a md5 crypted password
272     my $newsudopassword = crypt($query->param('newsudopass'), &Util::CreateCryptSalt(1));
273     my $ug = new Data::UUID;
274     my $uuid = $ug->create_str();
275
276     $newsudo = "$uuid unconfirmed $host $newsudopassword";
277     $newsudo_hosts = $host;
278   }
279
280   my %delete_uuids = map { s/^sudopassword-delete-//; $_ => 1} grep { $query->param($_) eq 'delete' } grep { /^sudopassword-delete-/ } $query->param;
281   my @keepsudo;
282   for my $entry (@{$entry->{'sudopassword'}}) {
283     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.,*]+) ([^ ]+)$/);
284     next unless defined ($uuid);
285     next if (defined $delete_uuids{$uuid});
286     my %hosts = map { $_ => 1 } split(/,/, $hosts);
287     next if ($hosts{$newsudo_hosts});
288     push @keepsudo, $entry;
289   };
290   if ($newsudo ne '') {
291     push @keepsudo, $newsudo;
292   }
293
294   &Util::LDAPUpdate($ldap, $editdn, 'postalAddress', $newstaddress);
295   &Util::LDAPUpdate($ldap, $editdn, 'l', $query->param('l'));
296   &Util::LDAPUpdate($ldap, $editdn, 'latitude', $lat);
297   &Util::LDAPUpdate($ldap, $editdn, 'longitude', $long);
298   &Util::LDAPUpdate($ldap, $editdn, 'c', $query->param('country'));
299   &Util::LDAPUpdate($ldap, $editdn, 'postalCode', $query->param('postalcode'));
300   &Util::LDAPUpdate($ldap, $editdn, 'telephoneNumber', $query->param('telephonenumber'));
301   &Util::LDAPUpdate($ldap, $editdn, 'facsimileTelephoneNumber', $query->param('facsimiletelephonenumber'));
302   &Util::LDAPUpdate($ldap, $editdn, 'VoIP', $query->param('VoIP'));
303   &Util::LDAPUpdate($ldap, $editdn, 'loginShell', $query->param('loginshell'));
304   &Util::LDAPUpdate($ldap, $editdn, 'emailForward', $query->param('email'));
305   &Util::LDAPUpdate($ldap, $editdn, 'privateSub', $query->param('privatesub'));
306   &Util::LDAPUpdate($ldap, $editdn, 'ircNick', $query->param('ircnick'));
307   &Util::LDAPUpdate($ldap, $editdn, 'icqUin', $query->param('icquin'));
308   &Util::LDAPUpdate($ldap, $editdn, 'jabberJID', $query->param('jabberjid'));
309   &Util::LDAPUpdate($ldap, $editdn, 'labeledURI', $query->param('labeleduri'));
310   &Util::LDAPUpdate($ldap, $editdn, 'onVacation', $query->param('onvacation'));
311   &Util::LDAPUpdate($ldap, $editdn, 'gender', $gender);
312   &Util::LDAPUpdate($ldap, $editdn, 'birthDate', $query->param('birthdate')) if $bd_ok;
313   &Util::LDAPUpdate($ldap, $editdn, 'mailDisableMessage', $query->param('maildisablemessage'));
314   &Util::LDAPUpdate($ldap, $editdn, 'mailCallout', $callout);
315   &Util::LDAPUpdate($ldap, $editdn, 'mailGreylisting', $greylisting);
316   &Util::LDAPUpdate($ldap, $editdn, 'sudoPassword', \@keepsudo);
317
318   # when we are done, reload the page with the updated details.
319   my $url = "https://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id&authtoken=$authtoken&editdn=";
320   $url .= uri_escape($editdn, "\x00-\x40\x7f-\xff");
321   print "Location: $url\n\n";  
322 }
323
324 $ldap->unbind;