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