simplify reviewcert by breaking out pkc key extraction code into it's own function
[monkeysphere-validation-agent.git] / Crypt / Monkeysphere / MSVA.pm
1 # Monkeysphere Validation Agent, Perl version
2 # Copyright © 2010 Daniel Kahn Gillmor <dkg@fifthhorseman.net>,
3 #                  Jameson Rollins <jrollins@finestructure.net>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 { package Crypt::Monkeysphere::MSVA;
19
20   use strict;
21   use warnings;
22   use vars qw($VERSION);
23
24   use parent qw(HTTP::Server::Simple::CGI);
25   require Crypt::X509;
26   use Regexp::Common qw /net/;
27   use Convert::ASN1;
28   use MIME::Base64;
29   use IO::Socket;
30   use IO::File;
31   use Socket;
32   use File::Spec;
33   use File::HomeDir;
34   use Config::General;
35   use Crypt::Monkeysphere::MSVA::MarginalUI;
36   use Crypt::Monkeysphere::MSVA::Logger;
37   use Crypt::Monkeysphere::MSVA::Monitor;
38
39   use JSON;
40   use POSIX qw(strftime);
41   # we need the version of GnuPG::Interface that knows about pubkey_data, etc:
42   use GnuPG::Interface 0.42.02;
43
44   $VERSION = '0.8';
45
46   my $gnupg = GnuPG::Interface::->new();
47   $gnupg->options->quiet(1);
48   $gnupg->options->batch(1);
49
50   my %dispatch = (
51                   '/' => { handler => \&noop,
52                            methods => { 'GET' => 1 },
53                          },
54                   '/reviewcert' => { handler => \&reviewcert,
55                                      methods => { 'POST' => 1 },
56                                    },
57                   '/extracerts' => { handler => \&extracerts,
58                                      methods => { 'POST' => 1 },
59                                    },
60                  );
61
62   my $default_keyserver = 'hkp://pool.sks-keyservers.net';
63   my $default_keyserver_policy = 'unlessvalid';
64
65   my $logger = Crypt::Monkeysphere::MSVA::Logger::->new($ENV{MSVA_LOG_LEVEL});
66   sub logger {
67     return $logger;
68   }
69
70   my $rsa_decoder = Convert::ASN1::->new();
71   $rsa_decoder->prepare(q<
72
73    SEQUENCE {
74         modulus INTEGER,
75         exponent INTEGER
76    }
77           >);
78
79   sub net_server {
80     return 'Net::Server::MSVA';
81   };
82
83   sub msvalog {
84     return $logger->log(@_);
85   };
86
87   sub new {
88     my $class = shift;
89
90     my $port = 0;
91     if (exists $ENV{MSVA_PORT} and $ENV{MSVA_PORT} ne '') {
92       msvalog('debug', "MSVA_PORT set to %s\n", $ENV{MSVA_PORT});
93       $port = $ENV{MSVA_PORT} + 0;
94       die sprintf("not a reasonable port %d", $port) if (($port >= 65536) || $port <= 0);
95     }
96     # start the server on requested port
97     my $self = $class->SUPER::new($port);
98     if (! exists $ENV{MSVA_PORT}) {
99       # we can't pass port 0 to the constructor because it evaluates
100       # to false, so HTTP::Server::Simple just uses its internal
101       # default of 8080.  But if we want to select an arbitrary open
102       # port, we *can* set it here.
103       $self->port(0);
104     }
105
106     $self->{allowed_uids} = {};
107     if (exists $ENV{MSVA_ALLOWED_USERS} and $ENV{MSVA_ALLOWED_USERS} ne '') {
108       msvalog('verbose', "MSVA_ALLOWED_USERS environment variable is set.\nLimiting access to specified users.\n");
109       foreach my $user (split(/ +/, $ENV{MSVA_ALLOWED_USERS})) {
110         my ($name, $passwd, $uid);
111         if ($user =~ /^[0-9]+$/) {
112           $uid = $user + 0; # force to integer
113         } else {
114           ($name,$passwd,$uid) = getpwnam($user);
115         }
116         if (defined $uid) {
117           msvalog('verbose', "Allowing access from user ID %d\n", $uid);
118           $self->{allowed_uids}->{$uid} = $user;
119         } else {
120           msvalog('error', "Could not find user '%d'; not allowing\n", $user);
121         }
122       }
123     } else {
124       # default is to allow access only to the current user
125       $self->{allowed_uids}->{POSIX::getuid()} = 'self';
126     }
127
128     bless ($self, $class);
129     return $self;
130   }
131
132   sub noop {
133     my $self = shift;
134     my $cgi = shift;
135     return '200 OK', { available => JSON::true,
136                        protoversion => 1,
137                      };
138   }
139
140   sub opensshpubkey2key {
141     my $data = shift;
142     # FIXME: do we care that the label matches the type of key?
143     my ($label, $prop) = split(/ +/, $data);
144
145     my $out = parse_rfc4716body($prop);
146
147     return $out;
148   }
149
150   sub rfc47162key {
151     my $data = shift;
152
153     my @goodlines;
154     my $continuation = '';
155     my $state = 'outside';
156     foreach my $line (split(/\n/, $data)) {
157       last if ($state eq 'body' && $line eq '---- END SSH2 PUBLIC KEY ----');
158       if ($state eq 'outside' && $line eq '---- BEGIN SSH2 PUBLIC KEY ----') {
159         $state = 'header';
160         next;
161       }
162       if ($state eq 'header') {
163         $line = $continuation.$line;
164         $continuation = '';
165         if ($line =~ /^(.*)\\$/) {
166           $continuation = $1;
167           next;
168         }
169         if (! ($line =~ /:/)) {
170           $state = 'body';
171         }
172       }
173       push(@goodlines, $line) if ($state eq 'body');
174     }
175
176     msvalog('debug', "Found %d lines of RFC4716 body:\n%s\n",
177             scalar(@goodlines),
178             join("\n", @goodlines));
179     my $out = parse_rfc4716body(join('', @goodlines));
180
181     return $out;
182   }
183
184   sub parse_rfc4716body {
185     my $data = shift;
186
187     return undef
188       unless defined($data);
189     $data = decode_base64($data) or return undef;
190
191     msvalog('debug', "key properties: %s\n", unpack('H*', $data));
192     my $out = [ ];
193     while (length($data) > 4) {
194       my $size = unpack('N', substr($data, 0, 4));
195       msvalog('debug', "size: 0x%08x\n", $size);
196       return undef if (length($data) < $size + 4);
197       push(@{$out}, substr($data, 4, $size));
198       $data = substr($data, 4 + $size);
199     }
200
201     if ($out->[0] ne "ssh-rsa") {
202       return {error => 'Not an RSA key'};
203     }
204
205     if (scalar(@{$out}) != 3) {
206       return {error => 'Does not contain the right number of bigints for RSA'};
207     }
208
209     return { exponent => Math::BigInt->from_hex('0x'.unpack('H*', $out->[1])),
210              modulus => Math::BigInt->from_hex('0x'.unpack('H*', $out->[2])),
211            } ;
212   }
213
214
215   # return an arrayref of processes which we can detect that have the
216   # given socket open (the socket is specified with its inode)
217   sub getpidswithsocketinode {
218     my $sockid = shift;
219
220     if (! defined ($sockid)) {
221       msvalog('verbose', "No client socket ID to check.  The MSVA is probably not running as a service.\n");
222       return [];
223     }
224     # this appears to be how Linux symlinks open sockets in /proc/*/fd,
225     # as of at least 2.6.26:
226     my $socktarget = sprintf('socket:[%d]', $sockid);
227     my @pids;
228
229     my $procfs;
230     if (opendir($procfs, '/proc')) {
231       foreach my $pid (grep { /^\d+$/ } readdir($procfs)) {
232         my $procdir = sprintf('/proc/%d', $pid);
233         if (-d $procdir) {
234           my $procfds;
235           if (opendir($procfds, sprintf('/proc/%d/fd', $pid))) {
236             foreach my $procfd (grep { /^\d+$/ } readdir($procfds)) {
237               my $fd = sprintf('/proc/%d/fd/%d', $pid, $procfd);
238               if (-l $fd) {
239                 #my ($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($fd);
240                 my $targ = readlink($fd);
241                 push @pids, $pid
242                   if ($targ eq $socktarget);
243               }
244             }
245             closedir($procfds);
246           }
247         }
248       }
249       closedir($procfs);
250     }
251
252     # FIXME: this whole business is very linux-specific, i think.  i
253     # wonder how to get this info in other OSes?
254
255     return \@pids;
256   }
257
258   # return {uid => X, inode => Y}, meaning the numeric ID of the peer
259   # on the other end of $socket, "socket inode" identifying the peer's
260   # open network socket.  each value could be undef if unknown.
261   sub get_client_info {
262     my $socket = shift;
263
264     my $sock = IO::Socket::->new_from_fd($socket, 'r');
265     # check SO_PEERCRED -- if this was a TCP socket, Linux
266     # might not be able to support SO_PEERCRED (even on the loopback),
267     # though apparently some kernels (Solaris?) are able to.
268
269     my $clientid;
270     my $remotesocketinode;
271     my $socktype = $sock->sockopt(SO_TYPE) or die "could not get SO_TYPE info";
272     if (defined $socktype) {
273       msvalog('debug', "sockopt(SO_TYPE) = %d\n", $socktype);
274     } else {
275       msvalog('verbose', "sockopt(SO_TYPE) returned undefined.\n");
276     }
277
278     my $peercred = $sock->sockopt(SO_PEERCRED) or die "could not get SO_PEERCRED info";
279     my $client = $sock->peername();
280     my $family = sockaddr_family($client); # should be AF_UNIX (a.k.a. AF_LOCAL) or AF_INET
281
282     msvalog('verbose', "socket family: %d\nsocket type: %d\n", $family, $socktype);
283
284     if ($peercred) {
285       # FIXME: on i386 linux, this appears to be three ints, according to
286       # /usr/include/linux/socket.h.  What about other platforms?
287       my ($pid, $uid, $gid) = unpack('iii', $peercred);
288
289       msvalog('verbose', "SO_PEERCRED: pid: %u, uid: %u, gid: %u\n",
290               $pid, $uid, $gid,
291              );
292       if ($pid != 0 && $uid != 0) { # then we can accept it:
293         $clientid = $uid;
294       }
295       # FIXME: can we get the socket inode as well this way?
296     }
297
298     # another option in Linux would be to parse the contents of
299     # /proc/net/tcp to find the uid of the peer process based on that
300     # information.
301     if (! defined $clientid) {
302       msvalog('verbose', "SO_PEERCRED failed, digging around in /proc/net/tcp\n");
303       my $proto;
304       if ($family == AF_INET) {
305         $proto = '';
306       } elsif ($family == AF_INET6) {
307         $proto = '6';
308       }
309       if (defined $proto) {
310         if ($socktype == &SOCK_STREAM) {
311           $proto = 'tcp'.$proto;
312         } elsif ($socktype == &SOCK_DGRAM) {
313           $proto = 'udp'.$proto;
314         } else {
315           undef $proto;
316         }
317         if (defined $proto) {
318           my ($port, $iaddr) = unpack_sockaddr_in($client);
319           my $iaddrstring = unpack("H*", reverse($iaddr));
320           msvalog('verbose', "Port: %04x\nAddr: %s\n", $port, $iaddrstring);
321           my $remmatch = lc(sprintf("%s:%04x", $iaddrstring, $port));
322           my $infofile = '/proc/net/'.$proto;
323           my $f = IO::File::->new();
324           if ( $f->open('< '.$infofile)) {
325             my @header = split(/ +/, <$f>);
326             my ($localaddrix, $uidix, $inodeix);
327             my $ix = 0;
328             my $skipcount = 0;
329             while ($ix <= $#header) {
330               $localaddrix = $ix - $skipcount if (lc($header[$ix]) eq 'local_address');
331               $uidix = $ix - $skipcount if (lc($header[$ix]) eq 'uid');
332               $inodeix = $ix - $skipcount if (lc($header[$ix]) eq 'inode');
333               $skipcount++ if (lc($header[$ix]) eq 'tx_queue') or (lc($header[$ix]) eq 'tr'); # these headers don't actually result in a new column during the data rows
334               $ix++;
335             }
336             if (!defined $localaddrix) {
337               msvalog('info', "Could not find local_address field in %s; unable to determine peer UID\n",
338                       $infofile);
339             } elsif (!defined $uidix) {
340               msvalog('info', "Could not find uid field in %s; unable to determine peer UID\n",
341                       $infofile);
342             } elsif (!defined $inodeix) {
343               msvalog('info', "Could not find inode field in %s; unable to determine peer network socket inode\n",
344                       $infofile);
345             } else {
346               msvalog('debug', "local_address: %d; uid: %d\n", $localaddrix,$uidix);
347               while (my @line = split(/ +/,<$f>)) {
348                 if (lc($line[$localaddrix]) eq $remmatch) {
349                   if (defined $clientid) {
350                     msvalog('error', "Warning! found more than one remote uid! (%s and %s\n", $clientid, $line[$uidix]);
351                   } else {
352                     $clientid = $line[$uidix];
353                     $remotesocketinode = $line[$inodeix];
354                     msvalog('info', "remote peer is uid %d (inode %d)\n",
355                             $clientid, $remotesocketinode);
356                   }
357                 }
358               }
359             msvalog('error', "Warning! could not find peer information in %s.  Not verifying.\n", $infofile) unless defined $clientid;
360             }
361           } else { # FIXME: we couldn't read the file.  what should we
362                    # do besides warning?
363             msvalog('info', "Could not read %s; unable to determine peer UID\n",
364                     $infofile);
365           }
366         }
367       }
368     }
369     return { 'uid' => $clientid,
370              'inode' => $remotesocketinode };
371   }
372
373   sub handle_request {
374     my $self = shift;
375     my $cgi  = shift;
376
377     # This is part of a spawned child process.  We don't want the
378     # child process to destroy the update monitor when it terminates.
379     $self->{updatemonitor}->forget();
380     my $clientinfo = get_client_info(select);
381     my $clientuid = $clientinfo->{uid};
382
383     if (defined $clientuid) {
384       # test that this is an allowed user:
385       if (exists $self->{allowed_uids}->{$clientuid}) {
386         msvalog('verbose', "Allowing access from uid %d (%s)\n", $clientuid, $self->{allowed_uids}->{$clientuid});
387       } else {
388         msvalog('error', "MSVA client connection from uid %d, forbidden.\n", $clientuid);
389         printf("HTTP/1.0 403 Forbidden -- peer does not match local user ID\r\nContent-Type: text/plain\r\nDate: %s\r\n\r\nHTTP/1.1 403 Not Found -- peer does not match the local user ID.  Are you sure the agent is running as the same user?\r\n",
390                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())),);
391         return;
392       }
393     }
394
395     my $path = $cgi->path_info();
396     my $handler = $dispatch{$path};
397
398     if (ref($handler) eq "HASH") {
399       if (! exists $handler->{methods}->{$cgi->request_method()}) {
400         printf("HTTP/1.0 405 Method not allowed\r\nAllow: %s\r\nDate: %s\r\n",
401                join(', ', keys(%{$handler->{methods}})),
402                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())));
403       } elsif (ref($handler->{handler}) ne "CODE") {
404         printf("HTTP/1.0 500 Server Error\r\nDate: %s\r\n",
405                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())));
406       } else {
407         my $data = {};
408         my $ctype = $cgi->content_type();
409         msvalog('verbose', "Got %s %s (Content-Type: %s)\n", $cgi->request_method(), $path, defined $ctype ? $ctype : '**none supplied**');
410         if (defined $ctype) {
411           my @ctypes = split(/; */, $ctype);
412           $ctype = shift @ctypes;
413           if ($ctype eq 'application/json') {
414             $data = from_json($cgi->param('POSTDATA'));
415           }
416         };
417
418         my ($status, $object) = $handler->{handler}($data, $clientinfo);
419         if (ref($object) eq 'HASH' &&
420             ! defined $object->{server}) {
421           $object->{server} = sprintf("MSVA-Perl %s", $VERSION);
422         }
423
424         my $ret = to_json($object);
425         msvalog('info', "returning: %s\n", $ret);
426         printf("HTTP/1.0 %s\r\nDate: %s\r\nContent-Type: application/json\r\n\r\n%s",
427                $status,
428                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())),
429                $ret);
430       }
431     } else {
432       printf("HTTP/1.0 404 Not Found -- not handled by Monkeysphere validation agent\r\nContent-Type: text/plain\r\nDate: %s\r\n\r\nHTTP/1.0 404 Not Found -- the path:\r\n   %s\r\nis not handled by the MonkeySphere validation agent.\r\nPlease try one of the following paths instead:\r\n\r\n%s\r\n",
433              strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())),
434              $path, ' * '.join("\r\n * ", keys %dispatch) );
435     }
436   }
437
438   sub keycomp {
439     my $rsakey = shift;
440     my $gpgkey = shift;
441
442     if ($gpgkey->algo_num != 1) {
443       msvalog('verbose', "Monkeysphere only does RSA keys.  This key is algorithm #%d\n", $gpgkey->algo_num);
444     } else {
445       if ($rsakey->{exponent}->bcmp($gpgkey->pubkey_data->[1]) == 0 &&
446           $rsakey->{modulus}->bcmp($gpgkey->pubkey_data->[0]) == 0) {
447         return 1;
448       }
449     }
450     return 0;
451   }
452
453   sub pem2der {
454     my $pem = shift;
455     my @lines = split(/\n/, $pem);
456     my @goodlines = ();
457     my $ready = 0;
458     foreach my $line (@lines) {
459       if ($line eq '-----END CERTIFICATE-----') {
460         last;
461       } elsif ($ready) {
462         push @goodlines, $line;
463       } elsif ($line eq '-----BEGIN CERTIFICATE-----') {
464         $ready = 1;
465       }
466     }
467     msvalog('debug', "%d lines of base64:\n%s\n", $#goodlines + 1, join("\n", @goodlines));
468     return decode_base64(join('', @goodlines));
469   }
470
471   sub der2key {
472     my $rawdata = shift;
473
474     my $cert = Crypt::X509::->new(cert => $rawdata);
475
476     my $key = {error => 'I do not know what happened here'};
477
478     if ($cert->error) {
479       $key->{error} = sprintf("Error decoding X.509 certificate: %s", $cert->error);
480     } else {
481       msvalog('verbose', "cert subject: %s\n", $cert->subject_cn());
482       msvalog('verbose', "cert issuer: %s\n", $cert->issuer_cn());
483       msvalog('verbose', "cert pubkey algo: %s\n", $cert->PubKeyAlg());
484       msvalog('verbose', "cert pubkey: %s\n", unpack('H*', $cert->pubkey()));
485
486       if ($cert->PubKeyAlg() ne 'RSA') {
487         $key->{error} = sprintf('public key was algo "%s" (OID %s).  MSVA.pl only supports RSA',
488                                 $cert->PubKeyAlg(), $cert->pubkey_algorithm);
489       } else {
490         msvalog('debug', "decoding ASN.1 pubkey\n");
491         $key = $rsa_decoder->decode($cert->pubkey());
492         if (! defined $key) {
493           msvalog('verbose', "failed to decode %s\n", unpack('H*', $cert->pubkey()));
494           $key = {error => 'failed to decode the public key'};
495         }
496       }
497     }
498     return $key;
499   }
500
501   sub get_keyserver_policy {
502     if (exists $ENV{MSVA_KEYSERVER_POLICY} and $ENV{MSVA_KEYSERVER_POLICY} ne '') {
503       if ($ENV{MSVA_KEYSERVER_POLICY} =~ /^(always|never|unlessvalid)$/) {
504         return $1;
505       }
506       msvalog('error', "Not a valid MSVA_KEYSERVER_POLICY):\n  %s\n", $ENV{MSVA_KEYSERVER_POLICY});
507     }
508     return $default_keyserver_policy;
509   }
510
511   sub get_keyserver {
512     # We should read from (first hit wins):
513     # the environment
514     if (exists $ENV{MSVA_KEYSERVER} and $ENV{MSVA_KEYSERVER} ne '') {
515       if ($ENV{MSVA_KEYSERVER} =~ /^(((hkps?|hkpms|finger|ldap):\/\/)?$RE{net}{domain})$/) {
516         return $1;
517       }
518       msvalog('error', "Not a valid keyserver (from MSVA_KEYSERVER):\n  %s\n", $ENV{MSVA_KEYSERVER});
519     }
520
521     # FIXME: some msva.conf or monkeysphere.conf file (system and user?)
522
523     # or else read from the relevant gnupg.conf:
524     my $gpghome;
525     if (exists $ENV{GNUPGHOME} and $ENV{GNUPGHOME} ne '') {
526       $gpghome = untaint($ENV{GNUPGHOME});
527     } else {
528       $gpghome = File::Spec->catfile(File::HomeDir->my_home, '.gnupg');
529     }
530     my $gpgconf = File::Spec->catfile($gpghome, 'gpg.conf');
531     if (-f $gpgconf) {
532       if (-r $gpgconf) {
533         my %gpgconfig = Config::General::ParseConfig($gpgconf);
534         if ($gpgconfig{keyserver} =~ /^(((hkps?|hkpms|finger|ldap):\/\/)?$RE{net}{domain})$/) {
535           msvalog('debug', "Using keyserver %s from the GnuPG configuration file (%s)\n", $1, $gpgconf);
536           return $1;
537         } else {
538           msvalog('error', "Not a valid keyserver (from gpg config %s):\n  %s\n", $gpgconf, $gpgconfig{keyserver});
539         }
540       } else {
541         msvalog('error', "The GnuPG configuration file (%s) is not readable\n", $gpgconf);
542       }
543     } else {
544       msvalog('info', "Did not find GnuPG configuration file while looking for keyserver '%s'\n", $gpgconf);
545     }
546
547     # the default_keyserver
548     return $default_keyserver;
549   }
550
551   sub fetch_uid_from_keyserver {
552     my $uid = shift;
553
554     my $cmd = IO::Handle::->new();
555     my $out = IO::Handle::->new();
556     my $nul = IO::File::->new("< /dev/null");
557
558     my $ks = get_keyserver();
559     msvalog('debug', "start ks query to %s for UserID: %s\n", $ks, $uid);
560     my $pid = $gnupg->wrap_call
561       ( handles => GnuPG::Handles::->new( command => $cmd, stdout => $out, stderr => $nul ),
562         command_args => [ '='.$uid ],
563         commands => [ '--keyserver',
564                       $ks,
565                       qw( --no-tty --with-colons --search ) ]
566       );
567     while (my $line = $out->getline()) {
568       msvalog('debug', "from ks query: (%d) %s", $cmd->fileno, $line);
569       if ($line =~ /^info:(\d+):(\d+)/ ) {
570         $cmd->print(join(' ', ($1..$2))."\n");
571         msvalog('debug', 'to ks query: '.join(' ', ($1..$2))."\n");
572         last;
573       }
574     }
575     # FIXME: can we do something to avoid hanging forever?
576     waitpid($pid, 0);
577     msvalog('debug', "ks query returns %d\n", POSIX::WEXITSTATUS($?));
578   }
579
580 ##################################################
581 ## PKC KEY EXTRACTION ############################
582
583   sub pkcextractkey {
584     my $data = shift;
585     my $key;
586
587     if (lc($data->{pkc}->{type}) eq 'x509der') {
588       $key = der2key(join('', map(chr, @{$data->{pkc}->{data}})));
589     } elsif (lc($data->{pkc}->{type}) eq 'x509pem') {
590       $key = der2key(pem2der($data->{pkc}->{data}));
591     } elsif (lc($data->{pkc}->{type}) eq 'opensshpubkey') {
592       $key = opensshpubkey2key($data->{pkc}->{data});
593     } elsif (lc($data->{pkc}->{type}) eq 'rfc4716') {
594       $key = rfc47162key($data->{pkc}->{data});
595     } else {
596       $key->{error} = sprintf("Don't know this public key carrier type: %s", $data->{pkc}->{type});
597     }
598
599     # make sure that the returned integers are Math::BigInts:
600     $key->{exponent} = Math::BigInt::->new($key->{exponent}) unless (ref($key->{exponent}));
601     $key->{modulus} = Math::BigInt::->new($key->{modulus}) unless (ref($key->{modulus}));
602     msvalog('debug', "pubkey info:\nmodulus: %s\nexponent: %s\n",
603             $key->{modulus}->as_hex(),
604             $key->{exponent}->as_hex(),
605            );
606
607     if ($key->{modulus}->copy()->blog(2) < 1000) {
608       $key->{error} = sprintf('Public key size is less than 1000 bits (was: %d bits)', $key->{modulus}->copy()->blog(2));
609     }
610     return $key;
611   }
612
613 ##################################################
614
615   sub reviewcert {
616     my $data  = shift;
617     my $clientinfo  = shift;
618     return if !ref $data;
619
620     msvalog('verbose', "reviewing data...\n");
621
622     my $status = '200 OK';
623     my $ret =  { valid => JSON::false,
624                  message => 'Unknown failure',
625                };
626
627     # check context string
628     if ($data->{context} =~ /^(https|ssh|smtp|ike|postgresql|imaps|imap|submission)$/) {
629         $data->{context} = $1;
630     } else {
631         msvalog('error', "invalid context: %s\n", $data->{context});
632         $ret->{message} = sprintf("Invalid/unknown context: %s", $data->{context});
633         return $status,$ret;
634     }
635     msvalog('verbose', "context: %s\n", $data->{context});
636
637     # checkout peer string
638     # old-style just passed a string as a peer, rather than 
639     # peer: { name: 'whatever', 'type': 'client' }
640     $data->{peer} = { name => $data->{peer} }
641       if (ref($data->{peer}) ne 'HASH');
642
643     if (defined($data->{peer}->{type})) {
644       if ($data->{peer}->{type} =~ /^(client|server|peer)$/) {
645         $data->{peer}->{type} = $1;
646       } else {
647         msvalog('error', "invalid peer type string: %s\n", $data->{peer}->{type});
648         $ret->{message} = sprintf("Invalid peer type string: %s", $data->{peer}->{type});
649         return $status,$ret;
650       }
651     }
652
653     my $prefix = $data->{context}.'://';
654     if (defined $data->{peer}->{type} &&
655         $data->{peer}->{type} eq 'client' &&
656         # ike and smtp clients are effectively other servers, so we'll
657         # exclude them:
658         $data->{context} !~ /^(ike|smtp)$/) {
659       $prefix = '';
660       # clients can have any one-line User ID without NULL characters
661       # and leading or trailing whitespace
662       if ($data->{peer}->{name} =~ /^([^[:space:]][^\n\0]*[^[:space:]]|[^\0[:space:]])$/) {
663         $data->{peer}->{name} = $1;
664       } else {
665         msvalog('error', "invalid client peer name string: %s\n", $data->{peer}->{name});
666         $ret->{message} = sprintf("Invalid client peer name string: %s", $data->{peer}->{name});
667         return $status, $ret;
668       }
669     } elsif ($data->{peer}->{name} =~ /^($RE{net}{domain}(:[[:digit:]]+)?)$/) {
670       $data->{peer}->{name} = $1;
671     } else {
672       msvalog('error', "invalid peer name string: %s\n", $data->{peer}->{name});
673       $ret->{message} = sprintf("Invalid peer name string: %s", $data->{peer}->{name});
674       return $status,$ret;
675     }
676
677     msvalog('verbose', "peer: %s\n", $data->{peer}->{name});
678
679     # generate uid string
680     my $uid = $prefix.$data->{peer}->{name};
681     msvalog('verbose', "user ID: %s\n", $uid);
682
683     # check pkc type
684     my $key;
685     $key = pkcextractkey($data);
686     if (exists $key->{error}) {
687       $ret->{message} = $key->{error};
688       return $status,$ret;
689     }
690
691     $ret->{message} = sprintf('Failed to validate "%s" through the OpenPGP Web of Trust.', $uid);
692     my $lastloop = 0;
693     my $kspolicy;
694     if (defined $data->{keyserverpolicy} &&
695         $data->{keyserverpolicy} =~ /^(always|never|unlessvalid)$/) {
696       $kspolicy = $1;
697       msvalog("verbose", "using requested keyserver policy: %s\n", $1);
698     } else {
699       $kspolicy = get_keyserver_policy();
700     }
701     msvalog('debug', "keyserver policy: %s\n", $kspolicy);
702     # needed because $gnupg spawns child processes
703     $ENV{PATH} = '/usr/local/bin:/usr/bin:/bin';
704     if ($kspolicy eq 'always') {
705       fetch_uid_from_keyserver($uid);
706       $lastloop = 1;
707     } elsif ($kspolicy eq 'never') {
708       $lastloop = 1;
709     }
710     my $foundvalid = 0;
711
712     # fingerprints of keys that are not fully-valid for this User ID, but match
713     # the key from the queried certificate:
714     my @subvalid_key_fprs;
715
716     while (1) {
717       foreach my $gpgkey ($gnupg->get_public_keys('='.$uid)) {
718         my $validity = '-';
719         foreach my $tryuid ($gpgkey->user_ids) {
720           if ($tryuid->as_string eq $uid) {
721             $validity = $tryuid->validity;
722           }
723         }
724         # treat primary keys just like subkeys:
725         foreach my $subkey ($gpgkey, @{$gpgkey->subkeys}) {
726           my $primarymatch = keycomp($key, $subkey);
727           if ($primarymatch) {
728             if ($subkey->usage_flags =~ /a/) {
729               msvalog('verbose', "key matches, and 0x%s is authentication-capable\n", $subkey->hex_id);
730               if ($validity =~ /^[fu]$/) {
731                 $foundvalid = 1;
732                 msvalog('verbose', "...and it matches!\n");
733                 $ret->{valid} = JSON::true;
734                 $ret->{message} = sprintf('Successfully validated "%s" through the OpenPGP Web of Trust.', $uid);
735               } else {
736                 push(@subvalid_key_fprs, { fpr => $subkey->fingerprint, val => $validity }) if $lastloop;
737               }
738             } else {
739               msvalog('verbose', "key matches, but 0x%s is not authentication-capable\n", $subkey->hex_id);
740             }
741           }
742         }
743       }
744       if ($lastloop) {
745         last;
746       } else {
747         fetch_uid_from_keyserver($uid) if (!$foundvalid);
748         $lastloop = 1;
749       }
750     }
751
752     # only show the marginal UI if the UID of the corresponding
753     # key is not fully valid.
754     if (!$foundvalid) {
755       my $resp = Crypt::Monkeysphere::MSVA::MarginalUI->ask_the_user($gnupg,
756                                                                      $uid,
757                                                                      \@subvalid_key_fprs,
758                                                                      getpidswithsocketinode($clientinfo->{inode}),
759                                                                      $logger);
760       msvalog('info', "response: %s\n", $resp);
761       if ($resp) {
762         $ret->{valid} = JSON::true;
763         $ret->{message} = sprintf('Manually validated "%s" through the OpenPGP Web of Trust.', $uid);
764       }
765     }
766
767     return $status, $ret;
768   }
769
770   sub pre_loop_hook {
771     my $self = shift;
772     my $server = shift;
773
774     $self->spawn_master_subproc($server);
775   }
776
777   sub master_subprocess_died {
778     my $self = shift;
779     my $server = shift;
780     my $subproc_return = shift;
781
782     my $exitstatus = POSIX::WEXITSTATUS($subproc_return);
783     msvalog('verbose', "Subprocess %d terminated; exiting %d.\n", $self->{child_pid}, $exitstatus);
784     $server->set_exit_status($exitstatus);
785     $server->server_close();
786   }
787
788   sub child_dies {
789     my $self = shift;
790     my $pid = shift;
791     my $server = shift;
792
793     msvalog('debug', "Subprocess %d terminated.\n", $pid);
794
795     if (exists $self->{updatemonitor} &&
796         defined $self->{updatemonitor}->getchildpid() &&
797         $self->{updatemonitor}->getchildpid() == $pid) {
798       my $exitstatus = POSIX::WEXITSTATUS($?);
799       msvalog('verbose', "Update monitoring process (%d) terminated with code %d.\n", $pid, $exitstatus);
800       if (0 == $exitstatus) {
801         msvalog('info', "Reloading MSVA due to update request.\n");
802         # sending self a SIGHUP:
803         kill(1, $$);
804       } else {
805         msvalog('error', "Update monitoring process (%d) died unexpectedly with code %d.\nNo longer monitoring for updates; please send HUP manually.\n", $pid, $exitstatus);
806         # it died for some other weird reason; should we respawn it?
807
808         # FIXME: i'm worried that re-spawning would create a
809         # potentially abusive loop, if there are legit, repeatable
810         # reasons for the failure.
811
812 #        $self->{updatemonitor}->spawn();
813
814         # instead, we'll just avoid trying to kill the next process with this PID:
815         $self->{updatemonitor}->forget();
816       }
817     } elsif (exists $self->{child_pid} &&
818              ($self->{child_pid} == 0 ||
819               $self->{child_pid} == $pid)) {
820       $self->master_subprocess_died($server, $?);
821     }
822   }
823
824   # use sparingly!  We want to keep taint mode around for the data we
825   # get over the network.  this is only here because we want to treat
826   # the command line arguments differently for the subprocess.
827   sub untaint {
828     my $x = shift;
829     $x =~ /^(.*)$/ ;
830     return $1;
831   }
832
833   sub post_bind_hook {
834     my $self = shift;
835     my $server = shift;
836
837     $server->{server}->{leave_children_open_on_hup} = 1;
838
839     my $socketcount = @{ $server->{server}->{sock} };
840     if ( $socketcount != 1 ) {
841       msvalog('error', "%d sockets open; should have been 1.\n", $socketcount);
842       $server->set_exit_status(10);
843       $server->server_close();
844     }
845     my $port = @{ $server->{server}->{sock} }[0]->sockport();
846     if ((! defined $port) || ($port < 1) || ($port >= 65536)) {
847       msvalog('error', "got nonsense port: %d.\n", $port);
848       $server->set_exit_status(11);
849       $server->server_close();
850     }
851     if ((exists $ENV{MSVA_PORT}) && (($ENV{MSVA_PORT} + 0) != $port)) {
852       msvalog('error', "Explicitly requested port %d, but got port: %d.", ($ENV{MSVA_PORT}+0), $port);
853       $server->set_exit_status(13);
854       $server->server_close();
855     }
856     $self->port($port);
857     $self->{updatemonitor} = Crypt::Monkeysphere::MSVA::Monitor::->new($logger);
858   }
859
860   sub spawn_master_subproc {
861     my $self = shift;
862     my $server = shift;
863
864     if ((exists $ENV{MSVA_CHILD_PID}) && ($ENV{MSVA_CHILD_PID} ne '')) {
865       # this is most likely a re-exec.
866       msvalog('info', "This appears to be a re-exec, continuing with child pid %d\n", $ENV{MSVA_CHILD_PID});
867       $self->{child_pid} = $ENV{MSVA_CHILD_PID} + 0;
868     } elsif ($#ARGV >= 0) {
869       $self->{child_pid} = 0; # indicate that we are planning to fork.
870       # avoid ignoring SIGCHLD right before we fork.
871       $SIG{CHLD} = sub {
872         my $val;
873         while (defined($val = POSIX::waitpid(-1, POSIX::WNOHANG)) && $val > 0) {
874           $self->child_dies($val, $server);
875         }
876       };
877       my $fork = fork();
878       if (! defined $fork) {
879         msvalog('error', "could not fork\n");
880       } else {
881         if ($fork) {
882           msvalog('debug', "Child process has PID %d\n", $fork);
883           $self->{child_pid} = $fork;
884           $ENV{MSVA_CHILD_PID} = $fork;
885         } else {
886           msvalog('verbose', "PID %d executing: \n", $$);
887           for my $arg (@ARGV) {
888             msvalog('verbose', " %s\n", $arg);
889           }
890           # untaint the environment for the subprocess
891           # see: https://labs.riseup.net/code/issues/2461
892           foreach my $e (keys %ENV) {
893             $ENV{$e} = untaint($ENV{$e});
894           }
895           my @args;
896           foreach (@ARGV) {
897             push @args, untaint($_);
898           }
899           # restore default SIGCHLD handling:
900           $SIG{CHLD} = 'DEFAULT';
901           $ENV{MONKEYSPHERE_VALIDATION_AGENT_SOCKET} = sprintf('http://localhost:%d', $self->port);
902           exec(@args) or exit 111;
903         }
904       }
905     } else {
906       printf("MONKEYSPHERE_VALIDATION_AGENT_SOCKET=http://localhost:%d;\nexport MONKEYSPHERE_VALIDATION_AGENT_SOCKET;\n", $self->port);
907       # FIXME: consider daemonizing here to behave more like
908       # ssh-agent.  maybe avoid backgrounding by setting
909       # MSVA_NO_BACKGROUND.
910     };
911   }
912
913   sub extracerts {
914     my $data = shift;
915
916     return '500 not yet implemented', { };
917   }
918
919   1;
920 }