Change import of Net::LDAP to work on squeeze
[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);
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   $newstaddress = $query->param('staddress');
240   $newstaddress =~ s/\n/\$/m;
241
242   my $gender = $query->param('gender');
243   if ($gender != 1 && $gender != 2) {
244     $gender = 9; # unspecified
245   }
246   
247   my ($bd_ok, $bd_yr, $bd_mo, $bd_day);
248
249   if ($query->param('birthdate') =~ /^([1-9][0-9]{3})([01][0-9])([0-3][0-9])$/) {
250     $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
251     if ($bd_yr > 1850 and $bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
252       if ($bd_mo == 2) {
253          if ($bd_day == 29 and ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0))) {
254            $bd_ok = 1;
255          } elsif ($bd_day <= 28) {
256            $bd_ok = 1;
257          }
258       } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
259         if ($bd_day <= 30) {
260           $bd_ok = 1;
261         }
262       } else {
263         if ($bd_day <= 31) {
264           $bd_ok = 1;
265         }
266       }
267     }
268   } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
269     $bd_ok = 1;
270   }
271   my ($lat, $long);
272   ($lat, $long) = &Util::CheckLatLong($query->param('latitude'), 
273                                       $query->param('longitude'));
274   my ($greylisting, $callout, $mailcontentinspection, $defaultoptions);
275
276   $greylisting = $query->param('mailgreylisting');
277   if (!$greylisting or $greylisting ne "TRUE") {
278      $greylisting = "FALSE";
279   }
280
281   $callout = $query->param('mailcallout');
282   if (!$callout or $callout ne "TRUE") {
283      $callout = "FALSE";
284   }
285
286   $mailcontentinspection = $query->param('mailcontentinspection');
287   if (!$mailcontentinspection or ($mailcontentinspection ne "blackhole" and $mailcontentinspection ne "markup")) {
288      $mailcontentinspection = "reject";
289   }
290
291   $defaultoptions = $query->param('maildefaultoptions');
292   if (!$defaultoptions or $defaultoptions ne "TRUE") {
293      $defaultoptions = "FALSE";
294   }
295
296   my $newsudo;
297   my $newsudo_hosts;
298   if ($query->param('newsudopass') && $query->param('newsudopassvrfy')) {
299     my $host = $query->param('newsudopass-host');
300     if ($host =~ /[^a-z0-9.-]/ and $host ne '*') {
301       &Util::HTMLError("The sudo host has weird characters '$host'.");
302     }
303
304     if ($query->param('newsudopass') ne $query->param('newsudopassvrfy')) {
305       &Util::HTMLError("The sudo passwords you specified do not match. Please go back and try again.");
306     }
307
308     my $ldappass = $password;
309     $ldappass = $query->param('newpass') if $query->param('newpass');
310     push @ldapinfo_for_pwcheck, $host, split(/\./, $host);
311     my ($r, $msg) = &Util::checkPasswordQuality($query->param('newsudopass'), $ldappass, [@ldapinfo_for_pwcheck]);
312     if ($r) {
313       &Util::HTMLError("Password check failed for new sudo pass: $msg.  Please go back and try again.");
314     }
315
316     # create a md5 crypted password
317     my $newsudopassword = crypt($query->param('newsudopass'), &Util::CreateCryptSalt(1));
318     my $ug = new Data::UUID;
319     my $uuid = $ug->create_str();
320
321     $newsudo = "$uuid unconfirmed $host $newsudopassword";
322     $newsudo_hosts = $host;
323   }
324
325   my %delete_uuids = map { s/^sudopassword-delete-//; $_ => 1} grep { $query->param($_) eq 'delete' } grep { /^sudopassword-delete-/ } $query->param;
326   my @keepsudo;
327   for my $entry (@{$entry->{'sudopassword'}}) {
328     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.,*]+) ([^ ]+)$/);
329     next unless defined ($uuid);
330     next if (defined $delete_uuids{$uuid});
331     my %hosts = map { $_ => 1 } split(/,/, $hosts);
332     next if ($hosts{$newsudo_hosts});
333     push @keepsudo, $entry;
334   };
335   if ($newsudo ne '') {
336     push @keepsudo, $newsudo;
337   }
338
339   &Util::LDAPUpdate($ldap, $editdn, 'postalAddress', $newstaddress);
340   &Util::LDAPUpdate($ldap, $editdn, 'l', $query->param('l'));
341   &Util::LDAPUpdate($ldap, $editdn, 'latitude', $lat);
342   &Util::LDAPUpdate($ldap, $editdn, 'longitude', $long);
343   &Util::LDAPUpdate($ldap, $editdn, 'c', $query->param('country'));
344   &Util::LDAPUpdate($ldap, $editdn, 'postalCode', $query->param('postalcode'));
345   &Util::LDAPUpdate($ldap, $editdn, 'telephoneNumber', $query->param('telephonenumber'));
346   &Util::LDAPUpdate($ldap, $editdn, 'facsimileTelephoneNumber', $query->param('facsimiletelephonenumber'));
347   &Util::LDAPUpdate($ldap, $editdn, 'bATVToken', $query->param('bATVToken'));
348   &Util::LDAPUpdate($ldap, $editdn, 'VoIP', $query->param('VoIP'));
349   &Util::LDAPUpdate($ldap, $editdn, 'loginShell', $query->param('loginshell'));
350   &Util::LDAPUpdate($ldap, $editdn, 'emailForward', $query->param('email'));
351   &Util::LDAPUpdate($ldap, $editdn, 'privateSub', $query->param('privatesub'));
352   &Util::LDAPUpdate($ldap, $editdn, 'ircNick', $query->param('ircnick'));
353   &Util::LDAPUpdate($ldap, $editdn, 'icqUin', $query->param('icquin'));
354   &Util::LDAPUpdate($ldap, $editdn, 'jabberJID', $query->param('jabberjid'));
355   &Util::LDAPUpdate($ldap, $editdn, 'labeledURI', $query->param('labeleduri'));
356   &Util::LDAPUpdate($ldap, $editdn, 'onVacation', $query->param('onvacation'));
357   &Util::LDAPUpdate($ldap, $editdn, 'gender', $gender);
358   &Util::LDAPUpdate($ldap, $editdn, 'birthDate', $query->param('birthdate')) if $bd_ok;
359   &Util::LDAPUpdate($ldap, $editdn, 'mailDisableMessage', $query->param('maildisablemessage'));
360   &Util::LDAPUpdate($ldap, $editdn, 'mailCallout', $callout);
361   &Util::LDAPUpdate($ldap, $editdn, 'mailContentInspectionAction', $mailcontentinspection);
362   &Util::LDAPUpdate($ldap, $editdn, 'mailGreylisting', $greylisting);
363   &Util::LDAPUpdate($ldap, $editdn, 'mailDefaultOptions', $defaultoptions);
364   &Util::LDAPUpdate($ldap, $editdn, 'sudoPassword', \@keepsudo);
365
366   # when we are done, reload the page with the updated details.
367   my $url = "https://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id&authtoken=$authtoken&editdn=";
368   $url .= uri_escape($editdn, "\x00-\x40\x7f-\xff");
369   print "Location: $url\n\n";  
370 }
371
372 $ldap->unbind;