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