Include accountname in totp url
[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   # Now we have to fill in the rest that needs some processing...
102   $data{id} = $id;
103   $data{authtoken} = $authtoken;
104   $data{editdn} = $editdn;
105   $data{staddress} = $entry->{postaladdress}->[0];
106   $data{staddress} =~ s/\$/\n/;
107   $data{staddress} = CGI::escapeHTML($data{staddress});
108   $data{countryname} = &Util::LookupCountry($data{c});
109
110   if ($data{mailgreylisting} eq "TRUE") {
111     $data{mailgreylisting} = " checked";
112   } else {
113     $data{mailgreylisting} = "";
114   }
115
116   if ($data{mailcallout} eq "TRUE") {
117     $data{mailcallout} = " checked";
118   } else {
119     $data{mailcallout} = "";
120   }
121
122   $data{maildefaultoptions} ||= 'TRUE';
123
124   if ($data{maildefaultoptions} eq "TRUE") {
125     $data{maildefaultoptions} = " checked";
126   } else {
127     $data{maildefaultoptions} = "";
128   }
129
130   $data{mailcontentinspectionaction} ||= 'reject';
131
132   $data{email} = CGI::escapeHTML(join(", ", @{$entry->{emailforward}}));
133
134   my $mailcontentselect = '<select name="mailcontentinspection">'
135                         . '<option value="blackhole"'
136                         . ($data{mailcontentinspectionaction} eq 'blackhole' ? ' selected' : '')
137                         . '>blackhole'
138                         . '<option value="markup"'
139                         . ($data{mailcontentinspectionaction} eq 'markup' ? ' selected' : '')
140                         . '>markup'
141                         . '<option value="reject"'
142                         . ($data{mailcontentinspectionaction} eq 'reject' ? ' selected' : '')
143                         . '>reject';
144
145   my $confirmstring = '';
146   my $sudopassword = '';
147   for my $e(@{$entry->{'sudopassword'}}) {
148     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.,*-]+) ([^ ]+)$/);
149     unless (defined $uuid) {
150       $sudopassword .= "<tr><td>Unparseable line!</td></tr>\n";
151       next;
152     }
153     if ($status =~ /^confirmed:/) {
154       my $data = join(':', 'password-is-confirmed', 'sudo', $data{'uid'}, $uuid, $hosts, $crypted);
155       my $hmac = hmac_sha1_hex( $data, $hmac_key);
156       if ($status eq "confirmed:$hmac") {
157         $status = 'confirmed';
158       } else {
159         $status = 'INVALID';
160       }
161     }
162     my $e = "<tr><td>".CGI::escapeHTML($hosts)."</td>
163                  <td>".CGI::escapeHTML($status)."</td>
164                  <td><small>not shown</small></td>
165                  <!--<td><small><code>".CGI::escapeHTML($uuid)."</code></small></td>-->
166                  <td><input name=\"sudopassword-delete-".CGI::escapeHTML($uuid)."\" type=\"checkbox\" value=\"delete\"> (delete)</td></tr>\n";
167     $sudopassword .= $e;
168     if ($status eq 'unconfirmed') {
169       my $data = join(':', 'confirm-new-password', 'sudo', $data{'uid'}, $uuid, $hosts, $crypted);
170       my $hmac = hmac_sha1_hex( $data, $hmac_key);
171       $confirmstring .= CGI::escapeHTML("confirm sudopassword $uuid $hosts $hmac\n");
172     }
173   };
174   if ($confirmstring ne '') {
175     $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>";
176   }
177
178   my $sudopasswordhosts = '<select name="newsudopass-host"> <option value="*">ALL';
179   for my $dn (sort {$host_entries->{$a}->{host}->[0] cmp $host_entries->{$b}->{host}->[0]} keys(%$host_entries)) {
180       my $data = $host_entries->{$dn};
181       my $host = $data->{'host'}->[0];
182       my $hostname = $data->{'hostname'}->[0];
183       $sudopasswordhosts .= "<option value=\"$hostname\">$host\n";
184   };
185   $sudopasswordhosts .= '</select>';
186
187   # finally we can send output...
188   my ($sub, $substr);
189   &Util::HTMLSendHeader;
190   open (F, "<$config{webupdatehtml}") || &Util::HTMLError($!);
191   while (<F>) {
192     s/~(.+?)~/$data{$1}/g;
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, $newrtcpassword);
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('newrtcpass') && $query->param('newrtcpassvrfy')) {
257     if ($query->param('newrtcpass') ne $query->param('newrtcpassvrfy')) {
258       # passwords don't match...
259       &Util::HTMLError("The rtc-passwords you specified do not match. Please go back and try again.");
260     }
261
262     my ($r, $msg) = &Util::checkPasswordQuality($query->param('newrtcpass'), undef, [@ldapinfo_for_pwcheck]);
263     if ($r) {
264       &Util::HTMLError("Password check failed for rtc-password: $msg.  Please go back and try again.");
265     }
266     # create a md5 crypted password
267     $newrtcpassword = &md5_hex( ldap_explode_dn($editdn)->[0]{UID} . '@debian.org:rtc.debian.org:' . $query->param('newrtcpass') );
268
269     &Util::LDAPUpdate($ldap, $editdn, 'rtcPassword', $newrtcpassword);
270   }
271
272   $newstaddress = $query->param('staddress');
273   $newstaddress =~ s/\n/\$/m;
274
275   my ($bd_ok, $bd_yr, $bd_mo, $bd_day);
276
277   if ($query->param('birthdate') =~ /^([1-9][0-9]{3})([01][0-9])([0-3][0-9])$/) {
278     $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
279     if ($bd_yr > 1850 and $bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
280       if ($bd_mo == 2) {
281          if ($bd_day == 29 and ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0))) {
282            $bd_ok = 1;
283          } elsif ($bd_day <= 28) {
284            $bd_ok = 1;
285          }
286       } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
287         if ($bd_day <= 30) {
288           $bd_ok = 1;
289         }
290       } else {
291         if ($bd_day <= 31) {
292           $bd_ok = 1;
293         }
294       }
295     }
296   } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
297     $bd_ok = 1;
298   }
299   my ($lat, $long);
300   ($lat, $long) = &Util::CheckLatLong($query->param('latitude'),
301                                       $query->param('longitude'));
302   my ($greylisting, $callout, $mailcontentinspection, $defaultoptions);
303
304   $greylisting = $query->param('mailgreylisting');
305   if (!$greylisting or $greylisting ne "TRUE") {
306      $greylisting = "FALSE";
307   }
308
309   $callout = $query->param('mailcallout');
310   if (!$callout or $callout ne "TRUE") {
311      $callout = "FALSE";
312   }
313
314   $mailcontentinspection = $query->param('mailcontentinspection');
315   if (!$mailcontentinspection or ($mailcontentinspection ne "blackhole" and $mailcontentinspection ne "markup")) {
316      $mailcontentinspection = "reject";
317   }
318
319   $defaultoptions = $query->param('maildefaultoptions');
320   if (!$defaultoptions or $defaultoptions ne "TRUE") {
321      $defaultoptions = "FALSE";
322   }
323
324   my $newsudo;
325   my $newsudo_hosts;
326   if ($query->param('newsudopass') && $query->param('newsudopassvrfy')) {
327     my $host = $query->param('newsudopass-host');
328     if ($host =~ /[^a-z0-9.-]/ and $host ne '*') {
329       &Util::HTMLError("The sudo host has weird characters '$host'.");
330     }
331
332     if ($query->param('newsudopass') ne $query->param('newsudopassvrfy')) {
333       &Util::HTMLError("The sudo passwords you specified do not match. Please go back and try again.");
334     }
335
336     my $ldappass = $password;
337     $ldappass = $query->param('newpass') if $query->param('newpass');
338     push @ldapinfo_for_pwcheck, $host, split(/\./, $host);
339     my ($r, $msg) = &Util::checkPasswordQuality($query->param('newsudopass'), $ldappass, [@ldapinfo_for_pwcheck]);
340     if ($r) {
341       &Util::HTMLError("Password check failed for new sudo pass: $msg.  Please go back and try again.");
342     }
343
344     # create a md5 crypted password
345     my $newsudopassword = crypt($query->param('newsudopass'), &Util::CreateCryptSalt(1));
346     my $ug = new Data::UUID;
347     my $uuid = $ug->create_str();
348
349     $newsudo = "$uuid unconfirmed $host $newsudopassword";
350     $newsudo_hosts = $host;
351   }
352
353   my %delete_uuids = map { s/^sudopassword-delete-//; $_ => 1} grep { $query->param($_) eq 'delete' } grep { /^sudopassword-delete-/ } $query->param;
354   my @keepsudo;
355   for my $entry (@{$entry->{'sudopassword'}}) {
356     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.,*-]+) ([^ ]+)$/);
357     next unless defined ($uuid);
358     next if (defined $delete_uuids{$uuid});
359     my %hosts = map { $_ => 1 } split(/,/, $hosts);
360     next if ($hosts{$newsudo_hosts});
361     push @keepsudo, $entry;
362   };
363   if ($newsudo ne '') {
364     push @keepsudo, $newsudo;
365   }
366
367   &Util::LDAPUpdate($ldap, $editdn, 'postalAddress', $newstaddress);
368   &Util::LDAPUpdate($ldap, $editdn, 'l', $query->param('l'));
369   &Util::LDAPUpdate($ldap, $editdn, 'latitude', $lat);
370   &Util::LDAPUpdate($ldap, $editdn, 'longitude', $long);
371   &Util::LDAPUpdate($ldap, $editdn, 'c', $query->param('country'));
372   &Util::LDAPUpdate($ldap, $editdn, 'postalCode', $query->param('postalcode'));
373   &Util::LDAPUpdate($ldap, $editdn, 'telephoneNumber', $query->param('telephonenumber'));
374   &Util::LDAPUpdate($ldap, $editdn, 'facsimileTelephoneNumber', $query->param('facsimiletelephonenumber'));
375   &Util::LDAPUpdate($ldap, $editdn, 'bATVToken', $query->param('bATVToken'));
376   &Util::LDAPUpdate($ldap, $editdn, 'VoIP', $query->param('VoIP'));
377   &Util::LDAPUpdate($ldap, $editdn, 'loginShell', $query->param('loginshell'));
378   &Util::LDAPUpdate($ldap, $editdn, 'emailForward', $query->param('email'));
379   &Util::LDAPUpdate($ldap, $editdn, 'privateSub', $query->param('privatesub'));
380   &Util::LDAPUpdate($ldap, $editdn, 'ircNick', $query->param('ircnick'));
381   &Util::LDAPUpdate($ldap, $editdn, 'icqUin', $query->param('icquin'));
382   &Util::LDAPUpdate($ldap, $editdn, 'jabberJID', $query->param('jabberjid'));
383   &Util::LDAPUpdate($ldap, $editdn, 'labeledURI', $query->param('labeleduri'));
384   &Util::LDAPUpdate($ldap, $editdn, 'onVacation', $query->param('onvacation'));
385   &Util::LDAPUpdate($ldap, $editdn, 'birthDate', $query->param('birthdate')) if $bd_ok;
386   &Util::LDAPUpdate($ldap, $editdn, 'mailDisableMessage', $query->param('maildisablemessage'));
387   &Util::LDAPUpdate($ldap, $editdn, 'mailCallout', $callout);
388   &Util::LDAPUpdate($ldap, $editdn, 'mailContentInspectionAction', $mailcontentinspection);
389   &Util::LDAPUpdate($ldap, $editdn, 'mailGreylisting', $greylisting);
390   &Util::LDAPUpdate($ldap, $editdn, 'mailDefaultOptions', $defaultoptions);
391   &Util::LDAPUpdate($ldap, $editdn, 'sudoPassword', \@keepsudo);
392
393   # when we are done, reload the page with the updated details.
394   my $url = "https://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id;authtoken=$authtoken";
395   print "Location: $url\n\n";
396 }
397
398 $ldap->unbind;