Debian Codegraph @

openpgp2x509

raw
1 #!/usr/bin/perl
2
3 # Author: Daniel Kahn Gillmor <[email protected]>
4 # Copyright: 2011, 2013
5 # License: GPL-3+
6
7 # Usage (two examples):
8
9 # openpgp2x509 'Daniel Kahn Gillmor <[email protected]>'
10 # openpgp2x509 ssh://lair.fifthhorseman.net
11
12 # Each invocation will produce a series of PEM-encoded X.509
13 # certificates on stdout corresponding to keys that are well-bound to
14 # the specified OpenPGP User ID.
15
16 # This tool should detect (based on the form of the User ID) what kind
17 # of X.509 certificate to produce
18
19 # It only emits certificates for OpenPGP keys that are marked with the
20 # "Authentication" usage flag. FIXME: make the usage flag selection
21 # adjustable by an environment variable or something.
22
23 # WARNING: This is very rough code! the interface WILL change
24 # dramatically. The only thing I can commit to keeping stable are the
25 # OIDs.
26
27
28 use strict;
29 use warnings;
30 use Crypt::X509 0.50;
31 use Math::BigInt;
32 use GnuPG::Interface 0.43;
33 use Regexp::Common qw /net/;
34 use MIME::Base64;
35
36 my $cert = Crypt::X509::_init('Certificate');
37 $cert->configure('encode' => { 'time' => 'raw' } );
38 my $pgpe = Crypt::X509::_init('PGPExtension');
39 $pgpe->configure('encode' => { 'time' => 'raw' } );
40 my $san = Crypt::X509::_init('SubjectAltName');
41 $san->configure('encode' => { 'time' => 'raw' } );
42 my $rsapubkeyinfo = Crypt::X509::_init('RSAPubKeyInfo');
43
44 my $dntypes = { 'CN' => '2.5.4.3', # common name
45 'emailAddress' => '1.2.840.113549.1.9.1', # e-mail address -- DEPRECATED. should use subjectAltName instead.
46 'C' => '2.5.4.6', # country
47 'ST' => '2.5.4.8', # state
48 'L' => '2.5.4.7', # locality
49 'O' => '2.5.4.10', # organization
50 'OU' => '2.5.4.11', # organization unit (often used as a comment)
51 'PSEUDO' => '2.5.4.65', # pseudonym (used for the parenthetical "comment" in the conventional OpenPGP User ID)
52 };
53
54 my $algos = {
55 'RSA' => '1.2.840.113549.1.1.1',
56 'RSAwithMD2' => '1.2.840.113549.1.1.2',
57 'RSAwithMD4' => '1.2.840.113549.1.1.3',
58 'RSAwithMD5' => '1.2.840.113549.1.1.4',
59 'RSAwithSHA1' => '1.2.840.113549.1.1.5',
60 'OAEP' => '1.2.840.113549.1.1.6',
61 'RSAwithSHA256' => '1.2.840.113549.1.1.11',
62 'RSAwithSHA384' => '1.2.840.113549.1.1.12',
63 'RSAwithSHA512' => '1.2.840.113549.1.1.13',
64 'RSAwithSHA224' => '1.2.840.113549.1.1.14',
65 'NullSignatureUseOpenPGP' => '1.3.6.1.4.1.37210.1.1',
66 'OpenPGPCertificateEmbedded' => '1.3.6.1.4.1.37210.1.2',
67
68 };
69
70 # NullSignatureUseOpenPGP: this X509 certificate is not
71 # self-verifiable. It must be verified by fetching certificate
72 # material from OpenPGP keyservers or from the user's private OpenPGP
73 # keyring.
74
75 # The identity material and usage in the OpenPGP keyservers SHOULD be
76 # tested against the context in which the certificate is being used.
77 # If no context information is explicitly available to the
78 # implementation checking the certificate's validity, the
79 # implementation MUST assume that the context is the full set of
80 # possible contexts asserted by the X.509 material itself (is this
81 # doable?)
82
83 # 0) certificate validity ambiguity -- X.509 certificates are
84 # generally considered to be entirely valid or entirely invalid.
85 # OpenPGP certificates can have some User IDs that are valid, and
86 # others that are not. If an implementation is asked to return a
87 # simple boolean response to a validity inquiry, without knowing
88 # the context in which the certificate was proposed for use, it
89 # MUST validate the full conjunction of all assertions made in the
90 # X.509 certificate itself in order to return "true".
91
92
93
94 # OpenPGPCertificateEmbedded: the "signature" material in the X.509
95 # certificate is actually a set of OpenPGP packets corresponding to a
96 # complete "transferable public key" as specified in
97 # https://tools.ietf.org/html/rfc4880#section-11.1 , in "raw"
98 # (non-ascii-armored) form.
99
100 # If it were implemented, it would be the same as
101 # NullSignatureUseOpenPGP, but with the OpenPGP material transported
102 # in-band in addition.
103
104 ## NOTE: There is no implementation of the OpenPGPCertificateEmbedded,
105 ## and maybe there never will be. Another approach would be to
106 ## transmitting OpenPGP signature packets in the TLS channel itself,
107 ## with an extension comparable to OCSP stapling.
108
109 # the OpenPGPCertificateEmbedded concept has a few downsides:
110
111 # 1) data duplication -- the X.509 Subject Public Key material is
112 # repeated (either in the primary key packet, or in one of the
113 # subkey packets). The X.509 Subject material (and any
114 # subjectAltNames) are also duplicated in the User ID packets.
115 # This increases the size of the certificate. It also creates
116 # potential inconsistencies. If the X.509 Subject Public Key
117 # material is not found found in the OpenPGP Transferable Public
118 # Key (either as a primary key or as a subkey), conforming
119 # implementations MUST reject the certificate.
120
121 # 2) the requirement for out-of-band verification is not entirely
122 # removed, since conformant implementations may want to check the
123 # public keyservers for things like revocation certificates.
124
125
126
127
128 # this is a 5 followed by a 0. it fits into the "Parameters" section
129 # of an ASN.1 algorithmIdentifier object. what does this mean?
130 # I think it means the NULL type.
131 my $noparams = sprintf('%c%c', 5, 0);
132
133 my $extensions = {
134 'PGPExtension' => '1.3.6.1.4.1.3401.8.1.1',
135 'subjectAltName' => '2.5.29.17', # https://tools.ietf.org/html/rfc5280#section-4.2.1.6
136 };
137
138 my $gnupg = GnuPG::Interface::->new();
139 $gnupg->options->quiet(1);
140 $gnupg->options->batch(1);
141
142 sub err {
143 printf STDERR @_;
144 }
145
146
147 sub ts2Time {
148 my $ts = shift;
149
150 if (!defined($ts)) {
151 # see https://tools.ietf.org/html/rfc5280#section-4.1.2.5
152 return {'generalTime' => '99991231235959Z' };
153 } else {
154 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($ts);
155 $year += 1900;
156 if (($year < 1950) ||
157 ($year >= 2050)) {
158 return {'generalTime' => sprintf('%04d%02d%02d%02d%02d%02dZ', $year, $mon+1, $mday, $hour, $min, $sec) };
159 } else {
160 return {'utcTime' => sprintf('%02d%02d%02d%02d%02d%02dZ', ($year%100), $mon+1, $mday, $hour, $min, $sec) };
161 }
162 }
163 }
164
165 sub ts2ISO8601 {
166 my $ts = shift;
167 $ts = time()
168 if (!defined($ts));
169 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($ts);
170 $year += 1900;
171 return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ', $year, $mon+1, $mday, $hour, $min, $sec);
172 };
173
174 sub makeX509CertForUserID {
175 my $userid = shift;
176 my $hostname;
177 my $protocol;
178 my $emailaddress;
179 my $humanname;
180 my $comment;
181 my $subject;
182 my $ret = [];
183 my @subjectAltNames;
184
185 if ($userid =~ /^\s+/) {
186 err("We will not process User IDs with leading whitespace\n");
187 return $ret;
188 }
189 if ($userid =~ /\s+$/) {
190 err("We will not process User IDs with trailing whitespace\n");
191 return $ret;
192 }
193 if ($userid =~ /\n/) {
194 err("We will not process User IDs containing newlines\n");
195 return $ret;
196 }
197 # FIXME: do we want to rule out any other forms of User ID?
198
199 if ($userid =~ /^([^()]*)\s+(\((.*)\)\s+)?<([^><@\s]+\@$RE{net}{domain})>$/ ) {
200 # this is a typical/expected OpenPGP User ID.
201
202 $humanname = $1;
203 $comment = $3;
204 $emailaddress = $4;
205
206 # We're stripping arbitrary amounts of whitespace between the
207 # name, the comment, and the e-mail address here. if that
208 # whitespace is anything but " " then the OpenPGP User ID will not
209 # be reconstructible from the string.
210 my $reconstructeduid;
211 if (defined($comment)) {
212 $reconstructeduid = sprintf('%s (%s) <%s>', $humanname, $comment, $emailaddress);
213 } else {
214 $reconstructeduid = sprintf('%s <%s>', $humanname, $emailaddress);
215 }
216 if ($userid ne $reconstructeduid) {
217 err("This OpenPGP User ID could not be reconstructed from the X.509 certificate we would generate. Maybe a whitespace issue?\n");
218 return $ret;
219 }
220
221 $subject = [
222 [ {
223 'type' => $dntypes->{'CN'},
224 'value' => {
225 'utf8String' => $humanname,
226 },
227 } ],
228 ];
229 push(@{ $subject }, [ { 'type' => $dntypes->{'PSEUDO'},
230 'value' => { 'utf8String' => $comment } } ] )
231 if defined($comment);
232
233 push(@subjectAltNames, { 'rfc822Name' => $emailaddress });
234 } elsif ($userid =~ /^(https|ssh|smtps?|ike|postgresql|imaps?|submission):\/\/($RE{net}{domain})$/) {
235 $protocol = $1;
236 $hostname = $2;
237 $subject = [ [ {
238 'type' => $dntypes->{'CN'},
239 'value' => {
240 'printableString' => $hostname
241 },
242 } ] ];
243 push(@subjectAltNames, { 'dNSName' => $hostname });
244 } else {
245 # Maybe we just assume this is a bare Human Name?
246
247 # what if it's a human name plus a comment? should we treat the
248 # comment like a pseudonym, as above?
249 err("Assuming '%s' is a bare human name.\n", $userid);
250 $humanname = $userid;
251 $subject = [
252 [ {
253 'type' => $dntypes->{'CN'},
254 'value' => {
255 'printableString' => $humanname,
256 },
257 } ],
258 ];
259 }
260
261 foreach my $gpgkey ($gnupg->get_public_keys('='.$userid)) {
262 my $validity = '-';
263 my @sans;
264 foreach my $tryuid ($gpgkey->user_ids) {
265 if ($tryuid->as_string eq $userid) {
266 $validity = $tryuid->validity;
267 }
268
269 if (defined($protocol) &&
270 ($tryuid->validity =~ /^[fu]$/) &&
271 ($tryuid =~ /^$protocol\:\/\/($RE{net}{domain})/ )) {
272 push(@sans, $2);
273 }
274 }
275 if ($validity !~ /^[fu]$/) {
276 err("key 0x%s only has validity %s for User ID '%s' (needs full or ultimate validity)\n", $gpgkey->fingerprint->as_hex_string, $validity, $userid);
277 next;
278 }
279
280 # treat primary keys just like subkeys:
281 foreach my $subkey ($gpgkey, @{$gpgkey->subkeys}) {
282 if ($subkey->{algo_num} != 1) {
283 err("key 0x%s is algorithm %d (not RSA) -- we currently only handle RSA\n", $subkey->fingerprint->as_hex_string, $subkey->algo_num);
284 next;
285 }
286 # FIXME: reject/skip over revoked keys.
287 if (defined($subkey->{expiration_date}) &&
288 $subkey->{expiration_date} <= time()) {
289 err("key 0x%s is expired -- skipping\n", $subkey->fingerprint->as_hex_string);
290 next;
291 }
292 if ($subkey->{usage_flags} =~ /D/) {
293 err("key 0x%s is disabled -- skipping\n", $subkey->fingerprint->as_hex_string);
294 next;
295 }
296 if ($subkey->{usage_flags} !~ /a/) {
297 err("key 0x%s is not authentication-capable -- skipping\n", $subkey->fingerprint->as_hex_string);
298 next
299 }
300 err("making certificate for key 0x%s\n", $subkey->fingerprint->as_hex_string);
301
302 my $pubkey = { 'modulus' => @{$subkey->pubkey_data}[0],
303 'exponent' => @{$subkey->pubkey_data}[1],
304 };
305 my $vnotbefore = $subkey->creation_date;
306
307 my $vnotafter = $subkey->expiration_date;
308 # expiration date should be the minimum of the primary key and the subkey:
309 if (!defined($vnotafter)) {
310 $vnotafter = $gpgkey->expiration_date;
311 } elsif (defined($gpgkey->expiration_date)) {
312 $vnotafter = $gpgkey->expiration_date
313 if ($gpgkey->expiration_date < $vnotafter);
314 }
315
316 my $cnotbefore = ts2Time($vnotbefore);
317 my $cnotafter = ts2Time($vnotafter);
318
319 my $pgpeval = $pgpe->encode({ 'version' => 0, 'keyCreation' => $cnotbefore });
320 print $pgpe->{error}
321 if (!defined($pgpeval));
322
323 my $pubkeybitstring = $rsapubkeyinfo->encode($pubkey);
324 print $rsapubkeyinfo->{error}
325 if (!defined($pubkeybitstring));
326
327 my @extensions;
328 push(@extensions, { 'extnID' => $extensions->{'PGPExtension'},
329 'extnValue' => $pgpeval
330 });
331 if (@subjectAltNames) {
332 my $saneval = $san->encode(\@subjectAltNames);
333 print $san->{error}
334 if (!defined($saneval));
335 push(@extensions, { 'extnID' => $extensions->{'subjectAltName'},
336 'extnValue' => $saneval
337 });
338 }
339
340 # FIXME: base some keyUsage extensions on the type of User ID
341 # and on the usage flags of the key in question.
342
343 # if 'a' is present
344 # if protocol =~ /^https|smtps?|postgresql|imaps?|submission$/ then set TLS server eKU + ???
345 # if protocol eq 'ike' then ??? (ask micah)
346 # if protocol =~ /^smtps?$/ then set TLS client + ???
347 # if defined($humanname) then set TLS client + ???
348
349 # if 'e' is present:
350 # ???
351
352 # if 's' is present:
353 # ???
354
355 # if 'c' is present: I think we should never specify CA:TRUE or
356 # CA:FALSE in these certificates, since (a) we do not expect
357 # these keys to actually be making X.509-style certifications,
358 # but (b) we also don't want to assert that they can't make
359 # any certifications whatsoever.
360
361
362 # FIXME: add subjectAltName that matches the type of information
363 # we believe we're working with (see the cert-id draft).
364
365 # if @sans is present, should we add them as subjectAltNames? i
366 # don't think so. this certificate should be just for the User
367 # ID requested. The user can always make another certificate
368 # for the other user IDs and use that one.
369
370
371 my $newcert = {
372 'tbsCertificate' => {
373 'version' => 2, # 0 == version 1, 1 == version 2, 2 == version 3
374 # this is a convenient way to pass the fpr too.
375 'serialNumber' => Math::BigInt->new('0x'.$subkey->fingerprint->as_hex_string),
376 'subjectPublicKeyInfo' => {
377 'algorithm' => {
378 'parameters' => $noparams,
379 'algorithm' => $algos->{'RSA'},
380 },
381 'subjectPublicKey' => $pubkeybitstring,
382 },
383 'validity' => {
384 'notAfter' => $cnotafter,
385 'notBefore' => $cnotbefore,
386 },
387 'signature' => { # maybe we should make up our own "signature algorithm" here?
388 'parameters' => $noparams,
389 'algorithm' => $algos->{'NullSignatureUseOpenPGP'}
390 },
391 'subject' => {
392 'rdnSequence' => $subject,
393 },
394 'issuer' => {
395 'rdnSequence' => [ [ {
396 'type' => $dntypes->{'OU'},
397 'value' => { 'printableString' => sprintf('Please check the OpenPGP keyservers for certification information. (certificate generated on %s)', ts2ISO8601(time())) },
398 } ] ],
399 },
400 'extensions' => \@extensions,
401 },
402 'signature' => 'use OpenPGP',
403 'signatureAlgorithm' => {
404 'parameters' => $noparams,
405 'algorithm' => $algos->{'NullSignatureUseOpenPGP'}
406 }
407 };
408
409 my $dd = $cert->encode($newcert);
410
411 push(@{$ret}, { 'der' => $dd, 'fpr' => $subkey->fingerprint->as_hex_string});
412 }
413 }
414 return $ret;
415 }
416
417
418 foreach $cert ( @{ makeX509CertForUserID($ARGV[0]) } ) {
419 if (defined($ENV{OPENPGP2X509_EMIT_PKCS12})) {
420 # FIXME: figure out how to do this with certtool instead of openssl;
421 # the PKCS12 files i've tried to generate from certtool --to-p12
422 # can't be loaded by iceweasel for some reason.
423
424 # FIXME: don't do this horrific shell nastiness. be nicer!
425 $ENV{CERTOUTPUT} = sprintf("-----BEGIN CERTIFICATE-----\n%s-----END CERTIFICATE-----\n",
426 encode_base64($cert->{'der'}));
427 $ENV{FPR} = $cert->{'fpr'};
428 $ENV{OPENPGP_UID} = $ARGV[0];
429
430 # Note that while pkcs12(1ssl) claims that the order doesn't
431 # matter, in fact, this doesn't work if you emit the certificate
432 # before you emit the key.
433 system('(gpg --export-options export-reset-subkey-passwd --export-secret-subkeys "0x$FPR"\! |'.
434 'openpgp2ssh "$FPR" && printf "%s" "$CERTOUTPUT") |'.
435 'openssl pkcs12 -export -name "$OPENPGP_UID"');
436 } else {
437 printf("-----BEGIN CERTIFICATE-----\n%s-----END CERTIFICATE-----\n", encode_base64($cert->{'der'}));
438 }
439 }