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