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