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