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