Verify confirmed hmac in web display, showing status as either 'confirmed'
[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     $data{$_} = CGI::escapeHTML($data{$_}) if defined $data{$_};
86   }
87
88   $data{gender} = 9 if not $data{gender};
89
90   # Now we have to fill in the rest that needs some processing...
91   $data{id} = $id;
92   $data{authtoken} = $authtoken;
93   $data{editdn} = $editdn;
94   $data{staddress} = $entry->{postaladdress}->[0];
95   $data{staddress} =~ s/\$/\n/;
96   $data{staddress} = CGI::escapeHTML($data{staddress});
97   $data{countryname} = &Util::LookupCountry($data{c});
98
99   if ($data{mailgreylisting} eq "TRUE") {
100     $data{mailgreylisting} = " checked";
101   } else {
102     $data{mailgreylisting} = "";
103   }
104
105   if ($data{mailcallout} eq "TRUE") {
106     $data{mailcallout} = " checked";
107   } else {
108     $data{mailcallout} = "";
109   }
110   
111   $data{email} = CGI::escapeHTML(join(", ", @{$entry->{emailforward}}));
112
113   my $genderselect = '<select name="gender">'
114                    . '<option value="9"'
115                    . ($data{gender} == 9 ? ' selected' : '')
116                    . '>unspecified'
117                    . '<option value="1"'
118                    . ($data{gender} == 1 ? ' selected' : '')
119                    . '>male<option value="2"'
120                    . ($data{gender} == 2 ? ' selected' : '')
121                    . '>female</select>';
122   my $confirmstring = '';
123   my $sudopassword = '';
124   for my $e(@{$entry->{'sudopassword'}}) {
125     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.,*]+) ([^ ]+)$/);
126     unless (defined $uuid) {
127       $sudopassword .= "<tr><td>Unparseable line!</td></tr>\n";
128       next;
129     }
130     if ($status =~ /^confirmed:/) {
131       my $data = join(':', 'password-is-confirmed', $uuid, $hosts, $crypted);
132       my $hmac = hmac_sha1_hex( $data, $hmac_key);
133       if ($status eq "confirmed:$hmac") {
134         $status = 'confirmed';
135       } else {
136         $status = 'INVALID';
137       }
138     }
139     my $e = "<tr><td>".CGI::escapeHTML($hosts)."</td>
140                  <td>".CGI::escapeHTML($status)."</td>
141                  <td><small>not shown</small></td>
142                  <!--<td><small><code>".CGI::escapeHTML($uuid)."</code></small></td>-->
143                  <td><input name=\"sudopassword-delete-".CGI::escapeHTML($uuid)."\" type=\"checkbox\" value=\"delete\"> (delete)</td></tr>\n";
144     $sudopassword .= $e;
145     if ($status eq 'unconfirmed') {
146       my $data = join(':', 'confirm-new-password', $uuid, $hosts, $crypted);
147       my $hmac = hmac_sha1_hex( $data, $hmac_key);
148       $confirmstring .= CGI::escapeHTML("confirm sudopassword $uuid $hosts $hmac\n");
149     }
150   };
151   if ($confirmstring ne '') {
152     $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>";
153   }
154
155   my $sudopasswordhosts = '<select name="newsudopass-host"> <option value="*">ALL';
156   for my $dn (sort {$host_entries->{$a}->{host}->[0] cmp $host_entries->{$b}->{host}->[0]} keys(%$host_entries)) {
157       my $data = $host_entries->{$dn};
158       my $host = $data->{'host'}->[0];
159       my $hostname = $data->{'hostname'}->[0];
160       $sudopasswordhosts .= "<option value=\"$hostname\">$host\n";
161   };
162   $sudopasswordhosts .= '</select>';
163
164   # finally we can send output...
165   my ($sub, $substr);
166   &Util::HTMLSendHeader;
167   open (F, "<$config{webupdatehtml}") || &Util::HTMLError($!);
168   while (<F>) {
169     s/~(.+?)~/$data{$1}/g;
170     s/<\?genderselect>/$genderselect/;
171     s/<\?sudopassword>/$sudopassword/;
172     s/<\?sudopasswordhosts>/$sudopasswordhosts/;
173     s/<\?confirmstring>/$confirmstring/;
174     print;
175   }
176   close F;
177 } else {
178   my @ldapinfo_for_pwcheck;
179   for my $a (qw{cn sn md gecos uid}) {
180     for my $e (@{$entry->{$a}}) {
181       push @ldapinfo_for_pwcheck, $e;
182     }
183   }
184
185
186   # Actually update stuff...
187   my ($newpassword, $newstaddress);
188   
189   # Good god, why would we want to do that here?  it breaks password setting
190   # etc, and it doesn't prevent people from setting eveil stuff in ldap
191   # directly.
192   # &Util::FixParams($query);
193
194   if (($query->param('labeleduri')) && 
195       ($query->param('labeleduri') !~ /^https?:\/\//i)) {
196     &Util::HTMLError("Your homepage URL is invalid");
197   }
198   
199   if ($query->param('newpass') && $query->param('newpassvrfy')) {
200     if ($query->param('newpass') ne $query->param('newpassvrfy')) {
201       # passwords don't match...
202       &Util::HTMLError("The passwords you specified do not match. Please go back and try again.");
203     }
204
205     my ($r, $msg) = &Util::checkPasswordQuality($query->param('newpass'), undef, [@ldapinfo_for_pwcheck]);
206     if ($r) {
207       &Util::HTMLError("Password check failed: $msg.  Please go back and try again.");
208     }
209
210     # create a md5 crypted password
211     $newpassword = '{crypt}'.crypt($query->param('newpass'), &Util::CreateCryptSalt(1));
212     
213     &Util::LDAPUpdate($ldap, $editdn, 'userPassword', $newpassword);
214     &Util::UpdateAuthToken($authtoken, $query->param('newpass'));
215   }  
216
217   $newstaddress = $query->param('staddress');
218   $newstaddress =~ s/\n/\$/m;
219
220   my $gender = $query->param('gender');
221   if ($gender != 1 && $gender != 2) {
222     $gender = 9; # unspecified
223   }
224   
225   my ($bd_ok, $bd_yr, $bd_mo, $bd_day);
226
227   if ($query->param('birthdate') =~ /^([1-9][0-9]{3})([01][0-9])([0-3][0-9])$/) {
228     $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
229     if ($bd_yr > 1850 and $bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
230       if ($bd_mo == 2) {
231          if ($bd_day == 29 and ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0))) {
232            $bd_ok = 1;
233          } elsif ($bd_day <= 28) {
234            $bd_ok = 1;
235          }
236       } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
237         if ($bd_day <= 30) {
238           $bd_ok = 1;
239         }
240       } else {
241         if ($bd_day <= 31) {
242           $bd_ok = 1;
243         }
244       }
245     }
246   } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
247     $bd_ok = 1;
248   }
249   my ($lat, $long);
250   ($lat, $long) = &Util::CheckLatLong($query->param('latitude'), 
251                                       $query->param('longitude'));
252   my ($greylisting, $callout);
253
254   $greylisting = $query->param('mailgreylisting');
255   if (!$greylisting or $greylisting ne "TRUE") {
256      $greylisting = "FALSE";
257   }
258
259   $callout = $query->param('mailcallout');
260   if (!$callout or $callout ne "TRUE") {
261      $callout = "FALSE";
262   }
263
264   my $newsudo;
265   my $newsudo_hosts;
266   if ($query->param('newsudopass') && $query->param('newsudopassvrfy')) {
267     my $host = $query->param('newsudopass-host');
268     if ($host =~ /[^a-z0-9.-]/ and $host ne '*') {
269       &Util::HTMLError("The sudo host has weird characters '$host'.");
270     }
271
272     if ($query->param('newsudopass') ne $query->param('newsudopassvrfy')) {
273       &Util::HTMLError("The sudo passwords you specified do not match. Please go back and try again.");
274     }
275
276     my $ldappass = $password;
277     $ldappass = $query->param('newpass') if $query->param('newpass');
278     push @ldapinfo_for_pwcheck, $host, split(/\./, $host);
279     my ($r, $msg) = &Util::checkPasswordQuality($query->param('newsudopass'), $ldappass, [@ldapinfo_for_pwcheck]);
280     if ($r) {
281       &Util::HTMLError("Password check failed for new sudo pass: $msg.  Please go back and try again.");
282     }
283
284     # create a md5 crypted password
285     my $newsudopassword = crypt($query->param('newsudopass'), &Util::CreateCryptSalt(1));
286     my $ug = new Data::UUID;
287     my $uuid = $ug->create_str();
288
289     $newsudo = "$uuid unconfirmed $host $newsudopassword";
290     $newsudo_hosts = $host;
291   }
292
293   my %delete_uuids = map { s/^sudopassword-delete-//; $_ => 1} grep { $query->param($_) eq 'delete' } grep { /^sudopassword-delete-/ } $query->param;
294   my @keepsudo;
295   for my $entry (@{$entry->{'sudopassword'}}) {
296     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.,*]+) ([^ ]+)$/);
297     next unless defined ($uuid);
298     next if (defined $delete_uuids{$uuid});
299     my %hosts = map { $_ => 1 } split(/,/, $hosts);
300     next if ($hosts{$newsudo_hosts});
301     push @keepsudo, $entry;
302   };
303   if ($newsudo ne '') {
304     push @keepsudo, $newsudo;
305   }
306
307   &Util::LDAPUpdate($ldap, $editdn, 'postalAddress', $newstaddress);
308   &Util::LDAPUpdate($ldap, $editdn, 'l', $query->param('l'));
309   &Util::LDAPUpdate($ldap, $editdn, 'latitude', $lat);
310   &Util::LDAPUpdate($ldap, $editdn, 'longitude', $long);
311   &Util::LDAPUpdate($ldap, $editdn, 'c', $query->param('country'));
312   &Util::LDAPUpdate($ldap, $editdn, 'postalCode', $query->param('postalcode'));
313   &Util::LDAPUpdate($ldap, $editdn, 'telephoneNumber', $query->param('telephonenumber'));
314   &Util::LDAPUpdate($ldap, $editdn, 'facsimileTelephoneNumber', $query->param('facsimiletelephonenumber'));
315   &Util::LDAPUpdate($ldap, $editdn, 'VoIP', $query->param('VoIP'));
316   &Util::LDAPUpdate($ldap, $editdn, 'loginShell', $query->param('loginshell'));
317   &Util::LDAPUpdate($ldap, $editdn, 'emailForward', $query->param('email'));
318   &Util::LDAPUpdate($ldap, $editdn, 'privateSub', $query->param('privatesub'));
319   &Util::LDAPUpdate($ldap, $editdn, 'ircNick', $query->param('ircnick'));
320   &Util::LDAPUpdate($ldap, $editdn, 'icqUin', $query->param('icquin'));
321   &Util::LDAPUpdate($ldap, $editdn, 'jabberJID', $query->param('jabberjid'));
322   &Util::LDAPUpdate($ldap, $editdn, 'labeledURI', $query->param('labeleduri'));
323   &Util::LDAPUpdate($ldap, $editdn, 'onVacation', $query->param('onvacation'));
324   &Util::LDAPUpdate($ldap, $editdn, 'gender', $gender);
325   &Util::LDAPUpdate($ldap, $editdn, 'birthDate', $query->param('birthdate')) if $bd_ok;
326   &Util::LDAPUpdate($ldap, $editdn, 'mailDisableMessage', $query->param('maildisablemessage'));
327   &Util::LDAPUpdate($ldap, $editdn, 'mailCallout', $callout);
328   &Util::LDAPUpdate($ldap, $editdn, 'mailGreylisting', $greylisting);
329   &Util::LDAPUpdate($ldap, $editdn, 'sudoPassword', \@keepsudo);
330
331   # when we are done, reload the page with the updated details.
332   my $url = "https://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id&authtoken=$authtoken&editdn=";
333   $url .= uri_escape($editdn, "\x00-\x40\x7f-\xff");
334   print "Location: $url\n\n";  
335 }
336
337 $ldap->unbind;