16e495c5c2dcf9fc01d40a7b7088f03c18b0e8c1
[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.7';
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     $data = decode_base64($data) or return undef;
187
188     msvalog('debug', "key properties: %s\n", unpack('H*', $data));
189     my $out = [ ];
190     while (length($data) > 4) {
191       my $size = unpack('N', substr($data, 0, 4));
192       msvalog('debug', "size: 0x%08x\n", $size);
193       return undef if (length($data) < $size + 4);
194       push(@{$out}, substr($data, 4, $size));
195       $data = substr($data, 4 + $size);
196     }
197
198     if ($out->[0] ne "ssh-rsa") {
199       return {error => 'Not an RSA key'};
200     }
201
202     if (scalar(@{$out}) != 3) {
203       return {error => 'Does not contain the right number of bigints for RSA'};
204     }
205
206     return { exponent => Math::BigInt->from_hex('0x'.unpack('H*', $out->[1])),
207              modulus => Math::BigInt->from_hex('0x'.unpack('H*', $out->[2])),
208            } ;
209   }
210
211
212   # return an arrayref of processes which we can detect that have the
213   # given socket open (the socket is specified with its inode)
214   sub getpidswithsocketinode {
215     my $sockid = shift;
216
217     # this appears to be how Linux symlinks open sockets in /proc/*/fd,
218     # as of at least 2.6.26:
219     my $socktarget = sprintf('socket:[%d]', $sockid);
220     my @pids;
221
222     my $procfs;
223     if (opendir($procfs, '/proc')) {
224       foreach my $pid (grep { /^\d+$/ } readdir($procfs)) {
225         my $procdir = sprintf('/proc/%d', $pid);
226         if (-d $procdir) {
227           my $procfds;
228           if (opendir($procfds, sprintf('/proc/%d/fd', $pid))) {
229             foreach my $procfd (grep { /^\d+$/ } readdir($procfds)) {
230               my $fd = sprintf('/proc/%d/fd/%d', $pid, $procfd);
231               if (-l $fd) {
232                 #my ($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($fd);
233                 my $targ = readlink($fd);
234                 push @pids, $pid
235                   if ($targ eq $socktarget);
236               }
237             }
238             closedir($procfds);
239           }
240         }
241       }
242       closedir($procfs);
243     }
244
245     # FIXME: this whole business is very linux-specific, i think.  i
246     # wonder how to get this info in other OSes?
247
248     return \@pids;
249   }
250
251   # return {uid => X, inode => Y}, meaning the numeric ID of the peer
252   # on the other end of $socket, "socket inode" identifying the peer's
253   # open network socket.  each value could be undef if unknown.
254   sub get_client_info {
255     my $socket = shift;
256
257     my $sock = IO::Socket->new_from_fd($socket, 'r');
258     # check SO_PEERCRED -- if this was a TCP socket, Linux
259     # might not be able to support SO_PEERCRED (even on the loopback),
260     # though apparently some kernels (Solaris?) are able to.
261
262     my $clientid;
263     my $remotesocketinode;
264     my $socktype = $sock->sockopt(SO_TYPE) or die "could not get SO_TYPE info";
265     if (defined $socktype) {
266       msvalog('debug', "sockopt(SO_TYPE) = %d\n", $socktype);
267     } else {
268       msvalog('verbose', "sockopt(SO_TYPE) returned undefined.\n");
269     }
270
271     my $peercred = $sock->sockopt(SO_PEERCRED) or die "could not get SO_PEERCRED info";
272     my $client = $sock->peername();
273     my $family = sockaddr_family($client); # should be AF_UNIX (a.k.a. AF_LOCAL) or AF_INET
274
275     msvalog('verbose', "socket family: %d\nsocket type: %d\n", $family, $socktype);
276
277     if ($peercred) {
278       # FIXME: on i386 linux, this appears to be three ints, according to
279       # /usr/include/linux/socket.h.  What about other platforms?
280       my ($pid, $uid, $gid) = unpack('iii', $peercred);
281
282       msvalog('verbose', "SO_PEERCRED: pid: %u, uid: %u, gid: %u\n",
283               $pid, $uid, $gid,
284              );
285       if ($pid != 0 && $uid != 0) { # then we can accept it:
286         $clientid = $uid;
287       }
288       # FIXME: can we get the socket inode as well this way?
289     }
290
291     # another option in Linux would be to parse the contents of
292     # /proc/net/tcp to find the uid of the peer process based on that
293     # information.
294     if (! defined $clientid) {
295       msvalog('verbose', "SO_PEERCRED failed, digging around in /proc/net/tcp\n");
296       my $proto;
297       if ($family == AF_INET) {
298         $proto = '';
299       } elsif ($family == AF_INET6) {
300         $proto = '6';
301       }
302       if (defined $proto) {
303         if ($socktype == &SOCK_STREAM) {
304           $proto = 'tcp'.$proto;
305         } elsif ($socktype == &SOCK_DGRAM) {
306           $proto = 'udp'.$proto;
307         } else {
308           undef $proto;
309         }
310         if (defined $proto) {
311           my ($port, $iaddr) = unpack_sockaddr_in($client);
312           my $iaddrstring = unpack("H*", reverse($iaddr));
313           msvalog('verbose', "Port: %04x\nAddr: %s\n", $port, $iaddrstring);
314           my $remmatch = lc(sprintf("%s:%04x", $iaddrstring, $port));
315           my $infofile = '/proc/net/'.$proto;
316           my $f = new IO::File;
317           if ( $f->open('< '.$infofile)) {
318             my @header = split(/ +/, <$f>);
319             my ($localaddrix, $uidix, $inodeix);
320             my $ix = 0;
321             my $skipcount = 0;
322             while ($ix <= $#header) {
323               $localaddrix = $ix - $skipcount if (lc($header[$ix]) eq 'local_address');
324               $uidix = $ix - $skipcount if (lc($header[$ix]) eq 'uid');
325               $inodeix = $ix - $skipcount if (lc($header[$ix]) eq 'inode');
326               $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
327               $ix++;
328             }
329             if (!defined $localaddrix) {
330               msvalog('info', "Could not find local_address field in %s; unable to determine peer UID\n",
331                       $infofile);
332             } elsif (!defined $uidix) {
333               msvalog('info', "Could not find uid field in %s; unable to determine peer UID\n",
334                       $infofile);
335             } elsif (!defined $inodeix) {
336               msvalog('info', "Could not find inode field in %s; unable to determine peer network socket inode\n",
337                       $infofile);
338             } else {
339               msvalog('debug', "local_address: %d; uid: %d\n", $localaddrix,$uidix);
340               while (my @line = split(/ +/,<$f>)) {
341                 if (lc($line[$localaddrix]) eq $remmatch) {
342                   if (defined $clientid) {
343                     msvalog('error', "Warning! found more than one remote uid! (%s and %s\n", $clientid, $line[$uidix]);
344                   } else {
345                     $clientid = $line[$uidix];
346                     $remotesocketinode = $line[$inodeix];
347                     msvalog('info', "remote peer is uid %d (inode %d)\n",
348                             $clientid, $remotesocketinode);
349                   }
350                 }
351               }
352             msvalog('error', "Warning! could not find peer information in %s.  Not verifying.\n", $infofile) unless defined $clientid;
353             }
354           } else { # FIXME: we couldn't read the file.  what should we
355                    # do besides warning?
356             msvalog('info', "Could not read %s; unable to determine peer UID\n",
357                     $infofile);
358           }
359         }
360       }
361     }
362     return { 'uid' => $clientid,
363              'inode' => $remotesocketinode };
364   }
365
366   sub handle_request {
367     my $self = shift;
368     my $cgi  = shift;
369
370     # This is part of a spawned child process.  We don't want the
371     # child process to destroy the update monitor when it terminates.
372     $self->{updatemonitor}->forget();
373     my $clientinfo = get_client_info(select);
374     my $clientuid = $clientinfo->{uid};
375
376     if (defined $clientuid) {
377       # test that this is an allowed user:
378       if (exists $self->{allowed_uids}->{$clientuid}) {
379         msvalog('verbose', "Allowing access from uid %d (%s)\n", $clientuid, $self->{allowed_uids}->{$clientuid});
380       } else {
381         msvalog('error', "MSVA client connection from uid %d, forbidden.\n", $clientuid);
382         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",
383                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())),);
384         return;
385       }
386     }
387
388     my $path = $cgi->path_info();
389     my $handler = $dispatch{$path};
390
391     if (ref($handler) eq "HASH") {
392       if (! exists $handler->{methods}->{$cgi->request_method()}) {
393         printf("HTTP/1.0 405 Method not allowed\r\nAllow: %s\r\nDate: %s\r\n",
394                join(', ', keys(%{$handler->{methods}})),
395                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())));
396       } elsif (ref($handler->{handler}) ne "CODE") {
397         printf("HTTP/1.0 500 Server Error\r\nDate: %s\r\n",
398                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())));
399       } else {
400         my $data = {};
401         my $ctype = $cgi->content_type();
402         msvalog('verbose', "Got %s %s (Content-Type: %s)\n", $cgi->request_method(), $path, defined $ctype ? $ctype : '**none supplied**');
403         if (defined $ctype) {
404           my @ctypes = split(/; */, $ctype);
405           $ctype = shift @ctypes;
406           if ($ctype eq 'application/json') {
407             $data = from_json($cgi->param('POSTDATA'));
408           }
409         };
410
411         my ($status, $object) = $handler->{handler}($data, $clientinfo);
412         if (ref($object) eq 'HASH' &&
413             ! defined $object->{server}) {
414           $object->{server} = sprintf("MSVA-Perl %s", $VERSION);
415         }
416
417         my $ret = to_json($object);
418         msvalog('info', "returning: %s\n", $ret);
419         printf("HTTP/1.0 %s\r\nDate: %s\r\nContent-Type: application/json\r\n\r\n%s",
420                $status,
421                strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())),
422                $ret);
423       }
424     } else {
425       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",
426              strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())),
427              $path, ' * '.join("\r\n * ", keys %dispatch) );
428     }
429   }
430
431   sub keycomp {
432     my $rsakey = shift;
433     my $gpgkey = shift;
434
435     if ($gpgkey->algo_num != 1) {
436       msvalog('verbose', "Monkeysphere only does RSA keys.  This key is algorithm #%d\n", $gpgkey->algo_num);
437     } else {
438       if ($rsakey->{exponent}->bcmp($gpgkey->pubkey_data->[1]) == 0 &&
439           $rsakey->{modulus}->bcmp($gpgkey->pubkey_data->[0]) == 0) {
440         return 1;
441       }
442     }
443     return 0;
444   }
445
446   sub pem2der {
447     my $pem = shift;
448     my @lines = split(/\n/, $pem);
449     my @goodlines = ();
450     my $ready = 0;
451     foreach my $line (@lines) {
452       if ($line eq '-----END CERTIFICATE-----') {
453         last;
454       } elsif ($ready) {
455         push @goodlines, $line;
456       } elsif ($line eq '-----BEGIN CERTIFICATE-----') {
457         $ready = 1;
458       }
459     }
460     msvalog('debug', "%d lines of base64:\n%s\n", $#goodlines + 1, join("\n", @goodlines));
461     return decode_base64(join('', @goodlines));
462   }
463
464   sub der2key {
465     my $rawdata = shift;
466
467     my $cert = Crypt::X509->new(cert => $rawdata);
468
469     my $key = {error => 'I do not know what happened here'};
470
471     if ($cert->error) {
472       $key->{error} = sprintf("Error decoding X.509 certificate: %s", $cert->error);
473     } else {
474       msvalog('verbose', "cert subject: %s\n", $cert->subject_cn());
475       msvalog('verbose', "cert issuer: %s\n", $cert->issuer_cn());
476       msvalog('verbose', "cert pubkey algo: %s\n", $cert->PubKeyAlg());
477       msvalog('verbose', "cert pubkey: %s\n", unpack('H*', $cert->pubkey()));
478
479       if ($cert->PubKeyAlg() ne 'RSA') {
480         $key->{error} = sprintf('public key was algo "%s" (OID %s).  MSVA.pl only supports RSA',
481                                 $cert->PubKeyAlg(), $cert->pubkey_algorithm);
482       } else {
483         msvalog('debug', "decoding ASN.1 pubkey\n");
484         $key = $rsa_decoder->decode($cert->pubkey());
485         if (! defined $key) {
486           msvalog('verbose', "failed to decode %s\n", unpack('H*', $cert->pubkey()));
487           $key = {error => 'failed to decode the public key'};
488         }
489       }
490     }
491     return $key;
492   }
493
494   sub get_keyserver_policy {
495     if (exists $ENV{MSVA_KEYSERVER_POLICY} and $ENV{MSVA_KEYSERVER_POLICY} ne '') {
496       if ($ENV{MSVA_KEYSERVER_POLICY} =~ /^(always|never|unlessvalid)$/) {
497         return $1;
498       }
499       msvalog('error', "Not a valid MSVA_KEYSERVER_POLICY):\n  %s\n", $ENV{MSVA_KEYSERVER_POLICY});
500     }
501     return $default_keyserver_policy;
502   }
503
504   sub get_keyserver {
505     # We should read from (first hit wins):
506     # the environment
507     if (exists $ENV{MSVA_KEYSERVER} and $ENV{MSVA_KEYSERVER} ne '') {
508       if ($ENV{MSVA_KEYSERVER} =~ /^(((hkps?|finger|ldap):\/\/)?$RE{net}{domain})$/) {
509         return $1;
510       }
511       msvalog('error', "Not a valid keyserver (from MSVA_KEYSERVER):\n  %s\n", $ENV{MSVA_KEYSERVER});
512     }
513
514     # FIXME: some msva.conf or monkeysphere.conf file (system and user?)
515
516     # or else read from the relevant gnupg.conf:
517     my $gpghome;
518     if (exists $ENV{GNUPGHOME} and $ENV{GNUPGHOME} ne '') {
519       $gpghome = untaint($ENV{GNUPGHOME});
520     } else {
521       $gpghome = File::Spec->catfile(File::HomeDir->my_home, '.gnupg');
522     }
523     my $gpgconf = File::Spec->catfile($gpghome, 'gpg.conf');
524     if (-f $gpgconf) {
525       if (-r $gpgconf) {
526         my %gpgconfig = Config::General::ParseConfig($gpgconf);
527         if ($gpgconfig{keyserver} =~ /^(((hkps?|finger|ldap):\/\/)?$RE{net}{domain})$/) {
528           msvalog('debug', "Using keyserver %s from the GnuPG configuration file (%s)\n", $1, $gpgconf);
529           return $1;
530         } else {
531           msvalog('error', "Not a valid keyserver (from gpg config %s):\n  %s\n", $gpgconf, $gpgconfig{keyserver});
532         }
533       } else {
534         msvalog('error', "The GnuPG configuration file (%s) is not readable\n", $gpgconf);
535       }
536     } else {
537       msvalog('info', "Did not find GnuPG configuration file while looking for keyserver '%s'\n", $gpgconf);
538     }
539
540     # the default_keyserver
541     return $default_keyserver;
542   }
543
544   sub fetch_uid_from_keyserver {
545     my $uid = shift;
546
547     my $cmd = IO::Handle->new();
548     my $out = IO::Handle->new();
549     my $nul = IO::File->new("< /dev/null");
550
551     my $ks = get_keyserver();
552     msvalog('debug', "start ks query to %s for UserID: %s\n", $ks, $uid);
553     my $pid = $gnupg->wrap_call
554       ( handles => GnuPG::Handles->new( command => $cmd, stdout => $out, stderr => $nul ),
555         command_args => [ '='.$uid ],
556         commands => [ '--keyserver',
557                       $ks,
558                       qw( --no-tty --with-colons --search ) ]
559       );
560     while (my $line = $out->getline()) {
561       msvalog('debug', "from ks query: (%d) %s", $cmd->fileno, $line);
562       if ($line =~ /^info:(\d+):(\d+)/ ) {
563         $cmd->print(join(' ', ($1..$2))."\n");
564         msvalog('debug', 'to ks query: '.join(' ', ($1..$2))."\n");
565         last;
566       }
567     }
568     # FIXME: can we do something to avoid hanging forever?
569     waitpid($pid, 0);
570     msvalog('debug', "ks query returns %d\n", POSIX::WEXITSTATUS($?));
571   }
572
573   sub reviewcert {
574     my $data  = shift;
575     my $clientinfo  = shift;
576     return if !ref $data;
577
578     msvalog('verbose', "reviewing data...\n");
579
580     my $status = '200 OK';
581     my $ret =  { valid => JSON::false,
582                  message => 'Unknown failure',
583                };
584
585     # check context string
586     if ($data->{context} =~ /^(https|ssh|smtp|ike|postgresql|imaps|imap|submission)$/) {
587         $data->{context} = $1;
588     } else {
589         msvalog('error', "invalid context: %s\n", $data->{context});
590         $ret->{message} = sprintf("Invalid/unknown context: %s", $data->{context});
591         return $status,$ret;
592     }
593     msvalog('verbose', "context: %s\n", $data->{context});
594
595     # checkout peer string
596     # old-style just passed a string as a peer, rather than 
597     # peer: { name: 'whatever', 'type': 'client' }
598     $data->{peer} = { name => $data->{peer} }
599       if (ref($data->{peer}) ne 'HASH');
600
601     if (defined($data->{peer}->{type})) {
602       if ($data->{peer}->{type} =~ /^(client|server|peer)$/) {
603         $data->{peer}->{type} = $1;
604       } else {
605         msvalog('error', "invalid peer type string: %s\n", $data->{peer}->{type});
606         $ret->{message} = sprintf("Invalid peer type string: %s", $data->{peer}->{type});
607         return $status,$ret;
608       }
609     }
610
611     my $prefix = $data->{context}.'://';
612     if (defined $data->{peer}->{type} &&
613         $data->{peer}->{type} eq 'client' &&
614         # ike and smtp clients are effectively other servers, so we'll
615         # exclude them:
616         $data->{context} !~ /^(ike|smtp)$/) {
617       $prefix = '';
618       # clients can have any one-line User ID without NULL characters
619       # and leading or trailing whitespace
620       if ($data->{peer}->{name} =~ /^([^[:space:]][^\n\0]*[^[:space:]]|[^\0[:space:]])$/) {
621         $data->{peer}->{name} = $1;
622       } else {
623         msvalog('error', "invalid client peer name string: %s\n", $data->{peer}->{name});
624         $ret->{message} = sprintf("Invalid client peer name string: %s", $data->{peer}->{name});
625         return $status, $ret;
626       }
627     } elsif ($data->{peer}->{name} =~ /^($RE{net}{domain})$/) {
628       $data->{peer}->{name} = $1;
629     } else {
630       msvalog('error', "invalid peer name string: %s\n", $data->{peer}->{name});
631       $ret->{message} = sprintf("Invalid peer name string: %s", $data->{peer}->{name});
632       return $status,$ret;
633     }
634
635     msvalog('verbose', "peer: %s\n", $data->{peer}->{name});
636
637     # generate uid string
638     my $uid = $prefix.$data->{peer}->{name};
639     msvalog('verbose', "user ID: %s\n", $uid);
640
641     # check pkc type
642     my $key;
643     if (lc($data->{pkc}->{type}) eq 'x509der') {
644       $key = der2key(join('', map(chr, @{$data->{pkc}->{data}})));
645     } elsif (lc($data->{pkc}->{type}) eq 'x509pem') {
646       $key = der2key(pem2der($data->{pkc}->{data}));
647     } elsif (lc($data->{pkc}->{type}) eq 'opensshpubkey') {
648       $key = opensshpubkey2key($data->{pkc}->{data});
649     } elsif (lc($data->{pkc}->{type}) eq 'rfc4716') {
650       $key = rfc47162key($data->{pkc}->{data});
651     } else {
652       $ret->{message} = sprintf("Don't know this public key carrier type: %s", $data->{pkc}->{type});
653       return $status,$ret;
654     }
655
656     if (exists $key->{error}) {
657       $ret->{message} = $key->{error};
658       return $status,$ret;
659     }
660
661     # make sure that the returned integers are Math::BigInts:
662     $key->{exponent} = Math::BigInt->new($key->{exponent}) unless (ref($key->{exponent}));
663     $key->{modulus} = Math::BigInt->new($key->{modulus}) unless (ref($key->{modulus}));
664     msvalog('debug', "pubkey info:\nmodulus: %s\nexponent: %s\n",
665             $key->{modulus}->as_hex(),
666             $key->{exponent}->as_hex(),
667            );
668
669     if ($key->{modulus}->copy()->blog(2) < 1000) {
670       $ret->{message} = sprintf('Public key size is less than 1000 bits (was: %d bits)', $key->{modulus}->copy()->blog(2));
671     } else {
672       $ret->{message} = sprintf('Failed to validate "%s" through the OpenPGP Web of Trust.', $uid);
673       my $lastloop = 0;
674       my $kspolicy;
675       if (defined $data->{keyserverpolicy} &&
676           $data->{keyserverpolicy} =~ /^(always|never|unlessvalid)$/) {
677         $kspolicy = $1;
678         msvalog("verbose", "using requested keyserver policy: %s\n", $1);
679       } else {
680         $kspolicy = get_keyserver_policy();
681       }
682       msvalog('debug', "keyserver policy: %s\n", $kspolicy);
683       # needed because $gnupg spawns child processes
684       $ENV{PATH} = '/usr/local/bin:/usr/bin:/bin';
685       if ($kspolicy eq 'always') {
686         fetch_uid_from_keyserver($uid);
687         $lastloop = 1;
688       } elsif ($kspolicy eq 'never') {
689         $lastloop = 1;
690       }
691       my $foundvalid = 0;
692
693       # fingerprints of keys that are not fully-valid for this User ID, but match
694       # the key from the queried certificate:
695       my @subvalid_key_fprs;
696
697       while (1) {
698         foreach my $gpgkey ($gnupg->get_public_keys('='.$uid)) {
699           my $validity = '-';
700           foreach my $tryuid ($gpgkey->user_ids) {
701             if ($tryuid->as_string eq $uid) {
702               $validity = $tryuid->validity;
703             }
704           }
705           # treat primary keys just like subkeys:
706           foreach my $subkey ($gpgkey, @{$gpgkey->subkeys}) {
707             my $primarymatch = keycomp($key, $subkey);
708             if ($primarymatch) {
709               if ($subkey->usage_flags =~ /a/) {
710                 msvalog('verbose', "key matches, and 0x%s is authentication-capable\n", $subkey->hex_id);
711                 if ($validity =~ /^[fu]$/) {
712                   $foundvalid = 1;
713                   msvalog('verbose', "...and it matches!\n");
714                   $ret->{valid} = JSON::true;
715                   $ret->{message} = sprintf('Successfully validated "%s" through the OpenPGP Web of Trust.', $uid);
716                 } else {
717                   push(@subvalid_key_fprs, { fpr => $subkey->fingerprint, val => $validity }) if $lastloop;
718                 }
719               } else {
720                 msvalog('verbose', "key matches, but 0x%s is not authentication-capable\n", $subkey->hex_id);
721               }
722             }
723           }
724         }
725         if ($lastloop) {
726           last;
727         } else {
728           fetch_uid_from_keyserver($uid) if (!$foundvalid);
729           $lastloop = 1;
730         }
731       }
732
733       # only show the marginal UI if the UID of the corresponding
734       # key is not fully valid.
735       if (!$foundvalid) {
736         my $resp = Crypt::Monkeysphere::MSVA::MarginalUI->ask_the_user($gnupg,
737                                                                        $uid,
738                                                                        \@subvalid_key_fprs,
739                                                                        getpidswithsocketinode($clientinfo->{inode}),
740                                                                        $logger);
741         msvalog('info', "response: %s\n", $resp);
742         if ($resp) {
743           $ret->{valid} = JSON::true;
744           $ret->{message} = sprintf('Manually validated "%s" through the OpenPGP Web of Trust.', $uid);
745         }
746       }
747     }
748     return $status, $ret;
749   }
750
751   sub pre_loop_hook {
752     my $self = shift;
753     my $server = shift;
754
755     $self->spawn_master_subproc($server);
756   }
757
758   sub master_subprocess_died {
759     my $self = shift;
760     my $server = shift;
761     my $subproc_return = shift;
762
763     my $exitstatus = POSIX::WEXITSTATUS($subproc_return);
764     msvalog('verbose', "Subprocess %d terminated; exiting %d.\n", $self->{child_pid}, $exitstatus);
765     $server->set_exit_status($exitstatus);
766     $server->server_close();
767   }
768
769   sub child_dies {
770     my $self = shift;
771     my $pid = shift;
772     my $server = shift;
773
774     msvalog('debug', "Subprocess %d terminated.\n", $pid);
775
776     if (exists $self->{updatemonitor} &&
777         defined $self->{updatemonitor}->getchildpid() &&
778         $self->{updatemonitor}->getchildpid() == $pid) {
779       my $exitstatus = POSIX::WEXITSTATUS($?);
780       msvalog('verbose', "Update monitoring process (%d) terminated with code %d.\n", $pid, $exitstatus);
781       if (0 == $exitstatus) {
782         msvalog('info', "Reloading MSVA due to update request.\n");
783         # sending self a SIGHUP:
784         kill(1, $$);
785       } else {
786         msvalog('error', "Update monitoring process (%d) died unexpectedly with code %d.\nNo longer monitoring for updates; please send HUP manually.\n", $pid, $exitstatus);
787         # it died for some other weird reason; should we respawn it?
788
789         # FIXME: i'm worried that re-spawning would create a
790         # potentially abusive loop, if there are legit, repeatable
791         # reasons for the failure.
792
793 #        $self->{updatemonitor}->spawn();
794
795         # instead, we'll just avoid trying to kill the next process with this PID:
796         $self->{updatemonitor}->forget();
797       }
798     } elsif (exists $self->{child_pid} &&
799              ($self->{child_pid} == 0 ||
800               $self->{child_pid} == $pid)) {
801       $self->master_subprocess_died($server, $?);
802     }
803   }
804
805   # use sparingly!  We want to keep taint mode around for the data we
806   # get over the network.  this is only here because we want to treat
807   # the command line arguments differently for the subprocess.
808   sub untaint {
809     my $x = shift;
810     $x =~ /^(.*)$/ ;
811     return $1;
812   }
813
814   sub post_bind_hook {
815     my $self = shift;
816     my $server = shift;
817
818     $server->{server}->{leave_children_open_on_hup} = 1;
819
820     my $socketcount = @{ $server->{server}->{sock} };
821     if ( $socketcount != 1 ) {
822       msvalog('error', "%d sockets open; should have been 1.\n", $socketcount);
823       $server->set_exit_status(10);
824       $server->server_close();
825     }
826     my $port = @{ $server->{server}->{sock} }[0]->sockport();
827     if ((! defined $port) || ($port < 1) || ($port >= 65536)) {
828       msvalog('error', "got nonsense port: %d.\n", $port);
829       $server->set_exit_status(11);
830       $server->server_close();
831     }
832     if ((exists $ENV{MSVA_PORT}) && (($ENV{MSVA_PORT} + 0) != $port)) {
833       msvalog('error', "Explicitly requested port %d, but got port: %d.", ($ENV{MSVA_PORT}+0), $port);
834       $server->set_exit_status(13);
835       $server->server_close();
836     }
837     $self->port($port);
838     $self->{updatemonitor} = Crypt::Monkeysphere::MSVA::Monitor->new($logger);
839   }
840
841   sub spawn_master_subproc {
842     my $self = shift;
843     my $server = shift;
844
845     if ((exists $ENV{MSVA_CHILD_PID}) && ($ENV{MSVA_CHILD_PID} ne '')) {
846       # this is most likely a re-exec.
847       msvalog('info', "This appears to be a re-exec, continuing with child pid %d\n", $ENV{MSVA_CHILD_PID});
848       $self->{child_pid} = $ENV{MSVA_CHILD_PID} + 0;
849     } elsif ($#ARGV >= 0) {
850       $self->{child_pid} = 0; # indicate that we are planning to fork.
851       # avoid ignoring SIGCHLD right before we fork.
852       $SIG{CHLD} = sub {
853         my $val;
854         while (defined($val = POSIX::waitpid(-1, POSIX::WNOHANG)) && $val > 0) {
855           $self->child_dies($val, $server);
856         }
857       };
858       my $fork = fork();
859       if (! defined $fork) {
860         msvalog('error', "could not fork\n");
861       } else {
862         if ($fork) {
863           msvalog('debug', "Child process has PID %d\n", $fork);
864           $self->{child_pid} = $fork;
865           $ENV{MSVA_CHILD_PID} = $fork;
866         } else {
867           msvalog('verbose', "PID %d executing: \n", $$);
868           for my $arg (@ARGV) {
869             msvalog('verbose', " %s\n", $arg);
870           }
871           # untaint the environment for the subprocess
872           # see: https://labs.riseup.net/code/issues/2461
873           foreach my $e (keys %ENV) {
874             $ENV{$e} = untaint($ENV{$e});
875           }
876           my @args;
877           foreach (@ARGV) {
878             push @args, untaint($_);
879           }
880           # restore default SIGCHLD handling:
881           $SIG{CHLD} = 'DEFAULT';
882           $ENV{MONKEYSPHERE_VALIDATION_AGENT_SOCKET} = sprintf('http://localhost:%d', $self->port);
883           exec(@args) or exit 111;
884         }
885       }
886     } else {
887       printf("MONKEYSPHERE_VALIDATION_AGENT_SOCKET=http://localhost:%d;\nexport MONKEYSPHERE_VALIDATION_AGENT_SOCKET;\n", $self->port);
888       # FIXME: consider daemonizing here to behave more like
889       # ssh-agent.  maybe avoid backgrounding by setting
890       # MSVA_NO_BACKGROUND.
891     };
892   }
893
894   sub extracerts {
895     my $data = shift;
896
897     return '500 not yet implemented', { };
898   }
899
900   1;
901 }