lib/Crypt/OpenSSL/CA.pm

filter: Statementstmt 97.0% 533 / 549 Branchbran 72.5% 87 / 120 Conditioncond 60.6% 20 / 33 MC/DCmcdc 38.1% 8 / 21 Subroutinesub 96.0% 121 / 126 Podpod n/a totaltotal 90.5% 769 / 849 CC 77 SCAR 17.2
CC
77
Cov
91%
add_extension
21.5
add_extension
17.3
add_entry
11.5
CRAP 5.6
« blib/lib/Crypt/OpenSSL/CA.pm ↑ Summary lib/Crypt/OpenSSL/CA/Inline/C.pm »
1 #!perl -w
2 # -*- coding: utf-8; -*-
3  
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 package Crypt::OpenSSL::CA;
8  
9 1 our $VERSION = "0.91";
10 # Maintainer note: Inline::C doesn't like pre-releases (eg 0.21_01), which are not needed
11 # for PAUSE developer releases anyway (http://www.cpan.org/modules/04pause.html#developerreleases)
12  
13 =head1 NAME
14  
15 Crypt::OpenSSL::CA - The crypto parts of an X509v3 Certification Authority
16  
17 =head1 SYNOPSIS
18  
19 =for My::Tests::Below "synopsis" begin
20  
21 1 ▶ use Crypt::OpenSSL::CA;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 my $dn = Crypt::OpenSSL::CA::X509_NAME->new
24 (C => "fr", CN => "test");
25  
26 my $privkey = Crypt::OpenSSL::CA::PrivateKey
27 ->parse($pem_private_key, -password => "secret");
28 my $pubkey = $privkey->get_public_key;
29  
30 my $x509 = Crypt::OpenSSL::CA::X509->new($pubkey);
31 $x509->set_serial("0xdeadbeef");
32 $x509->set_subject_DN($dn);
33 $x509->set_issuer_DN($dn);
34 $x509->set_extension("basicConstraints", "CA:TRUE",
35 -critical => 1);
36 $x509->set_extension("subjectKeyIdentifier",
37 $pubkey->get_openssl_keyid);
38 $x509->set_extension("authorityKeyIdentifier",
39 { keyid => $pubkey->get_openssl_keyid });
40 my $pem = $x509->sign($privkey, "sha1");
41  
42 =for My::Tests::Below "synopsis" end
43  
44 =head1 DESCRIPTION
45  
46 This module performs the cryptographic operations necessary to issue
47 X509 certificates and certificate revocation lists (CRLs). It is
48 implemented as a Perl wrapper around the popular OpenSSL library.
49  
50 I<Crypt::OpenSSL::CA> is an essential building block to create an
51 X509v3 B<Certification Authority> or CA, a crucial part of an X509
52 Public Key Infrastructure (PKI). A CA is defined by RFC4210 and
53 friends (see L<Crypt::OpenSSL::CA::Resources>) as a piece of software
54 that can (among other things) issue and revoke X509v3 certificates.
55 To perform the necessary cryptographic operations, it needs a private
56 key that is kept secret (currently only RSA is supported).
57  
58 Despite the name and unlike the C<openssl ca> command-line tool,
59 I<Crypt::OpenSSL::CA> is not designed as a full-fledged X509v3
60 Certification Authority (CA) in and of itself: some key features are
61 missing, most notably persistence (e.g. to remember issued and revoked
62 certificates between two CRL issuances) and security-policy based
63 screening of certificate requests. I<Crypt::OpenSSL::CA> mostly does
64 ``just the crypto'', and this is deliberate: OpenSSL's features such
65 as configuration file parsing, that are best implemented in Perl, have
66 been left out for maximum flexibility.
67  
68 =head2 API Overview
69  
70 The crypto in I<Crypt::OpenSSL::CA> is implemented using the OpenSSL
71 cryptographic library, which is lifted to Perl thanks to a bunch of
72 glue code in C and a lot of magic in L<Inline::C> and
73 L<Crypt::OpenSSL::CA::Inline::C>.
74  
75 Most of said glue code is accessible as class and instance methods in
76 the ancillary classes such as L</Crypt::OpenSSL::CA::X509> and
77 L</Crypt::OpenSSL::CA::X509_CRL>; the parent namespace
78 I<Crypt::OpenSSL::CA> is basically empty. Each of these ancillary
79 classes wrap around OpenSSL's ``object class'' with the same name
80 (e.g. L</Crypt::OpenSSL::CA::X509_NAME> corresponds to the
81 C<X509_NAME_foo> functions in C<libcrypto.so>). OpenSSL concepts are
82 therefore made available in an elegant object-oriented API; moreover,
83 they are subjugated to Perl's automatic garbage collection, which
84 allows the programmer to stop worrying about that. Additionally,
85 I<Crypt::OpenSSL::CA> provides some glue in Perl too, which is mostly
86 syntactic sugar to get a more Perlish API out of the C in OpenSSL.
87  
88 Note that the OpenSSL-wrapping classes don't strive for completeness
89 of the exposed API; rather, they seek to export enough features to
90 make them simultaneously testable and useful for the purpose of
91 issuing X509 certificates and CRLs. In particular,
92 I<Crypt::OpenSSL::CA> is currently not so good at parsing
93 already-existing cryptographic artifacts (However, L</PATCHES
94 WELCOME>, plus there are other modules on the CPAN that already do
95 that.)
96  
97 =head2 Error Management
98  
99 All functions and methods in this module, including XS code, throw
100 exceptions as if by L<perlfunc/die> if anything goes wrong. The
101 resulting exception is either a plain string (in case of memory
102 exhaustion problems, incorrect arguments, and so on) or an exception
103 blessed in class I<Crypt::OpenSSL::CA::Error> with the following
104 structure:
105  
106  
107 {
108 -message => $message,
109 -openssl => [
110 $openssl_error_1,
111 $openssl_error_2,
112 ...
113 ]
114 }
115  
116 where C<$message> is a message by I<Crypt::OpenSSL::CA> and the
117 C<-openssl> list is the contents of OpenSSL's error stack at the time
118 when the exception was raised.
119  
120 =begin internals
121  
122 =head3 _sslcroak_callback (-message => $val)
123  
124 =head3 _sslcroak_callback (-openssl => $val)
125  
126 =head3 _sslcroak_callback ("DONE")
127  
128 Callback that gets invoked one or several times whenever
129 L<Crypt::OpenSSL::CA::Inline::C/sslcroak> is run, in order to
130 implement L</Error Management>. I<_sslcroak_callback> is expected to
131 accumulate the exception data in $@, but to not bless it until
132 C<<_sslcroak_callback("DONE")>> is called; in this way, I<_sslcroak>
133 will be able to tell that the sequence of callback invocations
134 terminated successfully.
135  
136 A word of caution to hackers who wish to reimplement
137 I<_sslcroak_callback>, e.g. for testability purposes: if I<_sslcroak>
138 calls C<eval>, it will wipe out $@ which kind of defeats its purpose
139 (unless one is smart and sets $@ only at C<DONE> time); and if
140 I<_sslcroak_callback> throws an exception, the text thereof will end
141 up intermingled with the one from OpenSSL!
142  
143 =cut
144  
145 30 ▶sub _sslcroak_callback {
Subroutine _sslcroak_callback: called CC=8 SCAR=22.6
146 30 my ($key, $val) = @_;
147 30 ▶ if ($key eq "-message") {
Branch: 3 branches
BranchTrueFalseTotal
if ($key eq '-message') { } 8 22 30
elsif ($key eq '-openssl' and ref $@ eq 'HASH') { } 14 8 22
elsif ($key eq 'DONE' and ref $@ eq 'HASH') { } 8 0 8
148 8 $@ = { -message => $val };
149 ▶ } elsif ( ($key eq "-openssl") && (ref($@) eq "HASH") ) {
Condition66%2/3
$key eq "-openssl" and ref $@ eq "HASH"
!ll&&!rl&&r
8014
MC/DC50%1/2
$key eq "-openssl" and ref $@ eq "HASH"
$key eq "-openssl" ref $@ eq "HASH"
Truth table66%2/3
A and B
A= $key eq "-openssl"B= ref $@ eq "HASH"
ABresult
0X0
100
111
150 14 ▶ $@->{-openssl} ||= [];
Condition100%2/2
$@->{"-openssl"} ||= []
l!l
86
MC/DC100%1/1
$@->{"-openssl"} ||= []
$@->{"-openssl"}
Truth table100%2/2
A
A= $@->{"-openssl"}
Aresult
11
00
151 14 push(@{$@->{-openssl}}, $val);
152 ▶ } elsif ( ($key eq "DONE") && (ref($@) eq "HASH") ) {
Condition33%1/3
$key eq "DONE" and ref $@ eq "HASH"
!ll&&!rl&&r
008
MC/DC0%0/2
$key eq "DONE" and ref $@ eq "HASH"
$key eq "DONE" ref $@ eq "HASH"
Truth table33%1/3
A and B
A= $key eq "DONE"B= ref $@ eq "HASH"
ABresult
0X0
100
111
153 8 bless($@, "Crypt::OpenSSL::CA::Error");
154 } else {
155 0 ▶ warn sprintf
Branch: 1 branch
BranchTrueFalseTotal
'Data::Dumper'->can('Dumper') ? : 0 0 0
156 ("Bizarre callback state%s",
157 (Data::Dumper->can("Dumper") ?
158 " " . Data::Dumper::Dumper($@) : ""));
159 }
160 }
161  
162 =head3 Crypt::OpenSSL::CA::Error::stringify
163  
164 String overload for displaying error messages in a friendly manner.
165 See L</Error management>.
166  
167 =cut
168  
169 {
170 package Crypt::OpenSSL::CA::Error;
171 1 ▶ use overload '""' => \&stringify;
Subroutine BEGIN: called CC=1 SCAR=0.0
172  
173 0 ▶ sub stringify {
Subroutine stringify: not called CC=2 SCAR=17.9
174 0 my ($E) = @_;
175 return join("\n",
176 "Crypt::OpenSSL::CA: error: " . $E->{-message},
177 0 ▶ @{$E->{-openssl} || []});
Condition0%0/2
$E->{'-openssl'} || []
l!l
00
MC/DC0%0/1
$E->{'-openssl'} || []
$E->{'-openssl'}
Truth table0%0/2
A
A= $E->{'-openssl'}
Aresult
11
00
178 }
179 }
180  
181 =end internals
182  
183 =head1 Crypt::OpenSSL::CA::ASN1_INTEGER
184  
185 This Perl class wraps an integer of arbitrary size to be handled by
186 OpenSSL. It is used for serial numbers of certificates and CRLs (see
187 L</Crypt::OpenSSL::CA::X509> and L</Crypt::OpenSSL::CA::X509_CRL>).
188  
189 =cut
190  
191 1 package Crypt::OpenSSL::CA::ASN1_INTEGER;
192  
193 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"ASN1_INTEGER_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
194 #include <openssl/asn1.h>
195  
196 static
197 void DESTROY(SV* sv_self) {
198 1 ASN1_INTEGER_free(perl_unwrap("${\__PACKAGE__}",
199 ASN1_INTEGER *, sv_self));
200 }
201  
202 ASN1_INTEGER_BASE
203  
204 =head2 parse ($that)
205  
206 Parses C<$that>, which can be either a Perl integer, an object with a
207 C<to_hex> method (such as instance of L<Math::BigInt>), or a
208 hexadecimal string that starts with "0x". Returns an instance of
209 C<Crypt::OpenSSL::CA::ASN1_INTEGER>.
210  
211 =cut
212  
213 158024 ▶sub parse {
Subroutine parse: called CC=5 SCAR=16.2
214 158024 my ($class, $that) = @_;
215 158024 ▶ if (UNIVERSAL::isa($that, $class)) {
Branch: 3 branches
BranchTrueFalseTotal
if (UNIVERSAL::isa($that, $class)) { } 0 158024 158024
elsif (UNIVERSAL::can($that, 'to_hex')) { } 1 158023 158024
elsif ($that =~ /^-?0x/) { } 158019 4 158023
216 0 return $that;
217 } elsif (UNIVERSAL::can($that, "to_hex")) {
218 1 $that = $that->to_hex();
219 1 $that =~ s/^(-?)/${1}0x/;
220 } elsif ($that =~ m/^-?0x/) {
221 # Already in hex form; do nothing
222 } else {
223 # Assume numeric
224 4 ▶ $that = sprintf("%s0x%x", ($that < 0 ? "-" : ""), abs($that));
Branch: 1 branch
BranchTrueFalseTotal
$that < 0 ? : 1 3 4
225 }
226 158024 return $class->parse_hex($that);
227 }
228  
229 =head2 parse_hex ($hexserial)
230  
231 Parses $hexserial, a lowercase, hexadecimal string that starts with
232 either "0x" or "-0x"; and returns it as an instance of
233 C<Crypt::OpenSSL::CA::ASN1_INTEGER>. Raises an exception in case of
234 failure.
235  
236 =cut
237  
238 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"ASN1_INTEGER_PARSE_HEX";
Subroutine BEGIN: called CC=1 SCAR=0.0
239 #include <openssl/bn.h>
240  
241 static
242 SV* parse_hex(SV* class, const char* hexserial) {
243 BIGNUM* serial = NULL;
244 ASN1_INTEGER* retval;
245 int is_negative = 0;
246  
247 if (hexserial[0] == '-') {
248 is_negative = 1;
249 hexserial++;
250 }
251 if (! (hexserial[0] == '0' && hexserial[1] == 'x')) {
252 sslcroak("Bad serial string, should start with 0x");
253 }
254  
255 if (! BN_hex2bn(&serial, hexserial + 2)) {
256 sslcroak("BN_hex2bn failed");
257 }
258 BN_set_negative(serial, is_negative);
259  
260 retval = BN_to_ASN1_INTEGER(serial, NULL);
261 BN_free(serial);
262 if (! retval) {
263 sslcroak("BN_to_ASN1_INTEGER failed");
264 }
265 1 return perl_wrap("${\__PACKAGE__}", retval);
266 }
267  
268 ASN1_INTEGER_PARSE_HEX
269  
270 =head2 serialize ()
271  
272 Returns this C<Crypt::OpenSSL::CA::ASN1_INTEGER> as a lowercase
273 hexadecimal string starting with 0x. This is also the method that
274 implements stringification overload.
275  
276 =cut
277  
278 10012 ▶sub serialize {
Subroutine serialize: called CC=1 SCAR=0.0
279 10012 my ($self) = @_;
280 10012 local $_ = lc($self->_serialize_openssl());
281 10012 s/^(-?)0*(.)/${1}0x${2}/;
282 10012 return $_;
283 }
284  
285 1 ▶use overload '""' => \&serialize;
Subroutine BEGIN: called CC=1 SCAR=0.0
286  
287 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"ASN1_INTEGER_SERIALIZE";
Subroutine BEGIN: called CC=1 SCAR=0.0
288  
289 static
290 SV* _serialize_openssl(SV* sv_self) {
291 1 ASN1_INTEGER* serial = perl_unwrap("${\__PACKAGE__}", ASN1_INTEGER *, sv_self);
292  
293 BIGNUM* serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
294 if (! serial_bn) {
295 sslcroak("ASN1_INTEGER_to_BN failed");
296 }
297  
298 char* serial_hex = BN_bn2hex(serial_bn);
299 BN_free(serial_bn);
300 if (! serial_hex) {
301 sslcroak("BN_bn2hex failed");
302 }
303  
304 SV* retval = newSVpv(serial_hex, 0);
305 OPENSSL_free(serial_hex);
306 return retval;
307 }
308  
309 ASN1_INTEGER_SERIALIZE
310  
311 =head1 Crypt::OpenSSL::CA::ASN1_TIME
312  
313 This Perl class wraps a timestamp to be handled by OpenSSL. It is used for
314 NotBefore and NotAfter fields in certificates, and validity and
315 revocation dates (*not* compromise times) in CRLs.
316  
317 =cut
318  
319 package Crypt::OpenSSL::CA::ASN1_TIME;
320 1 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
321  
322 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"ASN1_TIME_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
323 #include <openssl/asn1.h>
324  
325 static
326 void DESTROY(SV* sv_self) {
327 1 ASN1_TIME_free(perl_unwrap("${\__PACKAGE__}",
328 ASN1_TIME *, sv_self));
329 }
330  
331 ASN1_TIME_BASE
332  
333 =head2 parse ($datetime)
334  
335 Parses C<$datetime>, a date in "Zulu" format (that is,
336 yyyymmddhhmmssZ, with a literal Z at the end), and returns a
337 newly-allocated C<Crypt::OpenSSL::CA::ASN1_TIME> object.
338  
339 The internal encoding is C<utcTime> for dates in the year 2049 or
340 before and C<generalizedTime> for dates in 2050 and after. RFC3280
341 dictates that this convention should apply to most date-related fields
342 in X509 certificates and CRLs (as per sections 4.1.2.5 for certificate
343 validity periods, and 5.1.2.4 through 5.1.2.6 for CRL validity periods
344 and certificate revocation times). By contrast, the C<invalidityDate>
345 CRL revocation reason extension is always in C<generalizedTime> and
346 this function should not be used there.
347  
348 =cut
349  
350 148016 ▶sub parse {
Subroutine parse: called CC=2 SCAR=7.6
351 148016 my ($class, $that) = @_;
352 148016 ▶ if (UNIVERSAL::isa($that, $class)) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($that, $class)) { } 0 148016 148016
353 0 return $that;
354 } else {
355 148016 return $class->_parse($that);
356 }
357 }
358  
359 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"ASN1_TIME_PARSE";
Subroutine BEGIN: called CC=1 SCAR=0.0
360  
361 /* RFC3280, section 4.1.2.5 */
362 #define RFC3280_cutoff_date "20500000" "000000"
363  
364 static
365 SV* _parse(SV* class, char* date) {
366 if (strlen(date) != strlen(RFC3280_cutoff_date) + 1) {
367 croak("Wrong date length");
368 }
369 if (date[strlen(RFC3280_cutoff_date)] != 'Z') {
370 croak("Wrong date format");
371 }
372  
373 ASN1_TIME* retval = ASN1_TIME_new();
374 if (! retval) {
375 sslcroak("ASN1_TIME_new failed");
376 }
377  
378 if (strcmp(date, RFC3280_cutoff_date) > 0) {
379 if (! ASN1_GENERALIZEDTIME_set_string(retval, date)) {
380 ASN1_TIME_free(retval);
381 sslcroak("ASN1_GENERALIZEDTIME_set_string failed (bad date format?)");
382 }
383 } else {
384 if (! ASN1_UTCTIME_set_string(retval, date + 2)) {
385 ASN1_TIME_free(retval);
386 sslcroak("ASN1_UTCTIME_set_string failed (bad date format?)");
387 }
388 }
389 1 return perl_wrap("${\__PACKAGE__}", retval);
390 }
391  
392 ASN1_TIME_PARSE
393  
394 =head2 serialize ()
395  
396 Return the date contained in this C<Crypt::OpenSSL::CA::ASN1_TIME>
397 object in human-readable form (English, 3-letter month first, GMT).
398  
399 =cut
400  
401 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"ASN1_TIME_SERIALIZE";
Subroutine BEGIN: called CC=1 SCAR=0.0
402 #include <openssl/bio.h>
403  
404 static
405 SV* serialize(SV* sv_self) {
406 1 ASN1_TIME* time = perl_unwrap("${\__PACKAGE__}", ASN1_TIME *, sv_self);
407  
408 BIO* bio = BIO_new(BIO_s_mem());
409 if (! bio) {
410 sslcroak("cannot allocate BIO");
411 }
412  
413 if (!(
414 ASN1_TIME_print(bio, time) &&
415 BIO_write(bio, "\\0", 1)
416 )) {
417 BIO_free(bio);
418 sslcroak("cannot stringify ASN1_TIME");
419 }
420  
421 SV* retval = BIO_mem_to_SV(bio);
422 if (! retval) {
423 croak("cannot copy revocation date into SV");
424 }
425  
426 return retval;
427 }
428  
429 ASN1_TIME_SERIALIZE
430  
431  
432 =head2 zulu ()
433  
434 Returns the date as a string in the GMT timezone, with the format
435 yyyymmddhhmmssZ (it's a literal Z at the end, meaning "Zulu" in case
436 you care).
437  
438 =cut
439  
440 22006 ▶sub zulu {
Subroutine zulu: called CC=5 SCAR=16.2
441 22006 my ($self) = @_;
442 22006 my $time = $self->serialize();
443  
444 # https://www.openssl.org/docs/man1.1.1/man3/ASN1_TIME_print.html
445 22006 ▶ croak "Unexpected time format returned by ASN1_TIME_print: $time"
Branch: 1 branch
BranchTrueFalseTotal
unless () = $time =~ /^(\w{3}) ([ 0-9]{2}) (\d{2}):(\d{2}):(\d{2}) (\d{4}) GMT$/ 0 22006 22006
446 unless my ($mon, $day, $hr, $min, $sec, $year) =
447 ($time =~ m/^(\w{3}) ([ 0-9]{2}) (\d{2}):(\d{2}):(\d{2}) (\d{4}) GMT$/);
448  
449 22006 my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
450 22006 my $month;
451 22006 foreach my $i (0..$#months) {
452 202033 ▶ if ($mon eq $months[$i]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mon eq $months[$i]) 22006 180027 202033
453 22006 $month = $i + 1;
454 22006 last;
455 }
456 }
457 22006 ▶ croak "Weird month returned by ASN1_TIME_print: $mon" unless $month;
Branch: 1 branch
BranchTrueFalseTotal
unless $month 0 22006 22006
458  
459 22006 return sprintf("%d%02d%02d%02d%02d%02dZ",
460 $year, $month, $day, $hr, $min, $sec);
461 }
462  
463 =head1 Crypt::OpenSSL::CA::X509_NAME
464  
465 This Perl class wraps around the X509_NAME_* functions of OpenSSL,
466 that deal with X500 DNs. Unlike OpenSSL's X509_NAME,
467 I<Crypt::OpenSSL::CA::X509_NAME> objects are immutable: only the
468 constructor can alter them.
469  
470 =cut
471  
472 package Crypt::OpenSSL::CA::X509_NAME;
473 1 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
474 1 ▶use utf8 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
475  
476 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"X509_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
477  
478 #include <openssl/x509.h>
479  
480 static
481 void DESTROY(SV* sv_self) {
482 1 X509_NAME_free(perl_unwrap("${\__PACKAGE__}", X509_NAME *, sv_self));
483 }
484  
485 X509_BASE
486  
487 =head2 new ($dnkey1, $dnval1, ...)
488  
489 Constructs and returns a new I<Crypt::OpenSSL::CA::X509_NAME> object;
490 implemented in terms of B<X509_NAME_add_entry_by_txt(3)>. The RDN
491 elements are to be passed in the same order as they will appear in the
492 C<RDNSequence> ASN.1 object that will be constructed, that is, the
493 B<most-significant parts of the DN> (e.g. C<C>) must come B<first>.
494 Be warned that this is order is the I<reverse> of RFC4514-compliant
495 DNs such as those that appear in LDAP, as per section 2.1 of said
496 RFC4514.
497  
498 Keys can be given either as uppercase short names (e.g. C<OU> - C<ou>
499 is not allowed), long names with the proper case
500 (C<organizationalUnitName>) or dotted-integer OIDs ("2.5.4.11").
501 Values are interpreted as strings. Certain keys (especially
502 C<countryName>) limit the range of acceptable values.
503  
504 All DN values will be converted to UTF-8 if needed, and the returned
505 DN string encodes all its RDN components as C<UTF8String>s regardless
506 of their value, as mandated by RFC3280 section 4.1.2.4.
507  
508 I<new_utf8> does not support multiple AVAs in a single RDN. If you
509 don't understand this sentence, consider yourself a lucky programmer.
510  
511 See also L</get_subject_DN> and L</get_issuer_DN> for an alternative
512 way of constructing instances of this class.
513  
514 =head2 new_utf8 ($dnkey1, $dnval1, ...)
515  
516 Backward-compatible alias for L</new>.
517  
518 =cut
519  
520 144015 ▶sub new {
Subroutine new: called CC=3 SCAR=11.0
521 144015 my ($class, @args) = @_;
522 144015 ▶ croak("odd number of arguments required") if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 144014 144015
523  
524 144014 my $self = $class->_new;
525 144014 ▶ while(my ($k, $v) = splice(@args, 0, 2)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@args, 0, 2)) 480025 144014 624039
526 480025 utf8::upgrade($v);
527 480025 $self->_add_RDN_utf8($k, $v);
528 }
529 144014 return $self;
530 }
531  
532 10000 ▶sub new_utf8 { goto &new; }
Subroutine new_utf8: called CC=1 SCAR=0.0
533  
534 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"MUTABLE_X509_NAME";
Subroutine BEGIN: called CC=1 SCAR=0.0
535  
536 static
537 SV* _new(char* class) {
538 X509_NAME *retval = X509_NAME_new();
539 if (!retval) { croak("not enough memory for X509_NAME_new"); }
540 1 return perl_wrap("${\__PACKAGE__}", retval);
541 }
542  
543 static
544 void _add_RDN_utf8(SV* sv_self, SV* sv_key, SV* sv_val) {
545 1 X509_NAME* self = perl_unwrap("${\__PACKAGE__}", X509_NAME *, sv_self);
546 char* key = char0_value(sv_key);
547 char* val = char0_value(sv_val);
548 X509_NAME_ENTRY* tmpentry;
549  
550 if (! SvUTF8(sv_val)) {
551 croak("Expected UTF8-encoded value");
552 }
553  
554 /* use X509_NAME_ENTRY_create_by_txt to validate the contents of the
555 field first, because as documented in
556 X509_NAME_add_entry_by_txt(3ssl) there will be no such checks
557 when using V_ASN1_UTF8STRING: */
558 if (! (tmpentry = X509_NAME_ENTRY_create_by_txt
559 (NULL, key, MBSTRING_UTF8, (unsigned char*) val, -1)) ) {
560 sslcroak("X509_NAME_ENTRY_create_by_txt failed for %s=%s",
561 key, val);
562 }
563 X509_NAME_ENTRY_free(tmpentry);
564  
565 if (! X509_NAME_add_entry_by_txt
566 (self, key, V_ASN1_UTF8STRING,
567 (unsigned char*) val, -1, -1, 0)) {
568 sslcroak("X509_NAME_add_entry_by_txt failed for %s=%s", key, val);
569 }
570 }
571 MUTABLE_X509_NAME
572  
573 =head2 to_string ()
574  
575 Returns a string representation of this DN object. Uses
576 B<X509_NAME_oneline(3)>. The return value does not conform to any
577 standard; in particular it does B<not> comply with RFC4514, and
578 embedded Unicode characters will B<not> be dealt with elegantly.
579 I<to_string()> is therefore intended only for debugging.
580  
581 =cut
582  
583 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"TO_STRING";
Subroutine BEGIN: called CC=1 SCAR=0.0
584  
585 static
586 SV* to_string(SV* sv_self) {
587 1 X509_NAME* self = perl_unwrap("${\__PACKAGE__}", X509_NAME *, sv_self);
588 return openssl_string_to_SV(X509_NAME_oneline(self, NULL, 4096));
589 }
590  
591 TO_STRING
592  
593 =head2 to_asn1 ()
594  
595 Returns an ASN.1 DER representation of this DN object, as a string of
596 bytes.
597  
598 =cut
599  
600 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"TO_ASN1";
Subroutine BEGIN: called CC=1 SCAR=0.0
601  
602 static
603 SV* to_asn1(SV* sv_self) {
604 unsigned char* asn1buf = NULL;
605 SV* retval = NULL;
606 int length;
607 1 X509_NAME* self = perl_unwrap("${\__PACKAGE__}", X509_NAME *, sv_self);
608 length = i2d_X509_NAME(self, &asn1buf);
609 if (length < 0) { croak("i2d_X509_NAME failed"); }
610 retval = openssl_buf_to_SV((char *)asn1buf, length);
611 SvUTF8_off(retval);
612 return retval;
613 }
614  
615 TO_ASN1
616  
617  
618 =head1 Crypt::OpenSSL::CA::PublicKey
619  
620 This Perl class wraps around the public key abstraction of OpenSSL.
621 I<Crypt::OpenSSL::CA::PublicKey> objects are immutable.
622  
623 =cut
624  
625 package Crypt::OpenSSL::CA::PublicKey;
626  
627 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"PUBLICKEY_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
628 #include <openssl/pem.h>
629 #include <openssl/bio.h>
630 #include <openssl/evp.h>
631 #include <openssl/x509.h> /* For validate_SPKAC */
632 #include <openssl/x509v3.h> /* For get_openssl_keyid() */
633 #include <openssl/objects.h> /* For NID_subject_key_identifier
634 in get_openssl_keyid() */
635  
636 static
637 void DESTROY(SV* sv_self) {
638 1 EVP_PKEY_free(perl_unwrap("${\__PACKAGE__}", EVP_PKEY *, sv_self));
639 }
640  
641 PUBLICKEY_BASE
642  
643 =head2 parse_RSA ($pemstring)
644  
645 Parses an RSA public key from $pemstring and returns an
646 I<Crypt::OpenSSL::CA::PublicKey> instance. See also
647 L</get_public_key> for an alternative way of creating instances of
648 this class.
649  
650 =cut
651  
652 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"PARSE_RSA";
Subroutine BEGIN: called CC=1 SCAR=0.0
653  
654 static
655 SV* parse_RSA(char *class, const char* pemkey) {
656 BIO* keybio;
657 RSA* pubkey;
658 EVP_PKEY* retval;
659  
660 keybio = BIO_new_mem_buf((void *) pemkey, -1);
661 if (keybio == NULL) {
662 croak("BIO_new_mem_buf failed");
663 }
664  
665 pubkey = PEM_read_bio_RSA_PUBKEY(keybio, NULL, NULL, NULL);
666 BIO_free(keybio);
667 if (pubkey == NULL) {
668 sslcroak("unable to parse RSA public key");
669 }
670  
671 retval = EVP_PKEY_new();
672 if (! retval) {
673 RSA_free(pubkey);
674 croak("Not enough memory for EVP_PKEY_new");
675 }
676  
677 if (! EVP_PKEY_assign_RSA(retval, pubkey)) {
678 RSA_free(pubkey);
679 EVP_PKEY_free(retval);
680 sslcroak("EVP_PKEY_assign_RSA failed");
681 }
682  
683 1 return perl_wrap("${\__PACKAGE__}", retval);
684 }
685  
686 PARSE_RSA
687  
688 =head2 validate_SPKAC ($spkacstring)
689  
690 =head2 validate_PKCS10 ($pkcs10string)
691  
692 Validates a L<Crypt::OpenSSL::CA::AlphabetSoup/CSR> of the respective
693 type and returns the public key as an object of class
694 L<Crypt::OpenSSL::CA::PublicKey> if the signature is correct. Throws
695 an error if the signature is invalid. I<validate_SPKAC($spkacstring)>
696 wants the ``naked'' Base64 string, without a leading C<SPKAC=> marker,
697 URI escapes, newlines or any such thing.
698  
699 Note that those methods are in I<Crypt::OpenSSL::CA> only by virtue of
700 them requiring cryptographic operations, best implemented using
701 OpenSSL. We definitely do B<not> want to emulate the request validity
702 checking features of C<openssl ca>, which are extremely inflexible and
703 that a full-fledged PKI built on top of I<Crypt::OpenSSL::CA> would
704 have to reimplement anyway. If one wants to parse other details of
705 the SPKAC or PKCS#10 messages (including the challenge password if
706 present), one should use other means such as L<Convert::ASN1>; ditto
707 if one just wants to extract the public key and doesn't care about the
708 signature.
709  
710 =cut
711  
712 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"VALIDATE";
Subroutine BEGIN: called CC=1 SCAR=0.0
713 static
714 SV* validate_SPKAC(char *class, const char* base64_spkac) {
715 NETSCAPE_SPKI* spkac;
716 EVP_PKEY* retval;
717  
718 if (! (spkac = NETSCAPE_SPKI_b64_decode(base64_spkac, -1)) ) {
719 sslcroak("Unable to load Netscape SPKAC structure");
720 }
721 if (! (retval=NETSCAPE_SPKI_get_pubkey(spkac)) ) {
722 NETSCAPE_SPKI_free(spkac);
723 sslcroak("Unable to extract public key from SPKAC structure");
724 }
725 if (NETSCAPE_SPKI_verify(spkac, retval) < 0) {
726 EVP_PKEY_free(retval);
727 NETSCAPE_SPKI_free(spkac);
728 sslcroak("SPKAC signature verification failed");
729 }
730 NETSCAPE_SPKI_free(spkac);
731 1 return perl_wrap("${\__PACKAGE__}", retval);
732 }
733  
734 static
735 SV* validate_PKCS10(char *class, const char* pem_pkcs10) {
736 BIO* pkcs10bio;
737 X509_REQ* req;
738 EVP_PKEY* retval;
739 int status;
740  
741 pkcs10bio = BIO_new_mem_buf((void *) pem_pkcs10, -1);
742 if (pkcs10bio == NULL) {
743 croak("BIO_new_mem_buf failed");
744 }
745  
746 req = PEM_read_bio_X509_REQ(pkcs10bio, NULL, NULL, NULL);
747 BIO_free(pkcs10bio);
748 if (! req) { sslcroak("Error parsing PKCS#10 request"); }
749  
750 if (! (retval = X509_REQ_get_pubkey(req))) {
751 X509_REQ_free(req);
752 sslcroak("Error extracting public key from PKCS#10 request");
753 }
754 status = X509_REQ_verify(req, retval);
755 X509_REQ_free(req);
756 if (status < 0) {
757 sslcroak("PKCS#10 signature verification problems");
758 } else if (status == 0) {
759 sslcroak("PKCS#10 signature does not match the certificate");
760 }
761 1 return perl_wrap("${\__PACKAGE__}", retval);
762 }
763 VALIDATE
764  
765 =head2 to_PEM
766  
767 Returns the contents of the public key as a PEM string.
768  
769 =cut
770  
771 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"TO_PEM";
Subroutine BEGIN: called CC=1 SCAR=0.0
772  
773 static
774 SV* to_PEM(SV* sv_self) {
775 1 EVP_PKEY* self = perl_unwrap("${\__PACKAGE__}", EVP_PKEY *, sv_self);
776 BIO* mem;
777 int printstatus;
778  
779 if (! (mem = BIO_new(BIO_s_mem()))) {
780 croak("Cannot allocate BIO");
781 }
782  
783 RSA* rsa;
784 DSA* dsa;
785 if ( (rsa = EVP_PKEY_get0_RSA(self)) ) {
786 printstatus = PEM_write_bio_RSA_PUBKEY(mem, rsa);
787 } else if ( (dsa = EVP_PKEY_get0_DSA(self)) ) {
788 printstatus = PEM_write_bio_DSA_PUBKEY(mem, dsa);
789 } else {
790 BIO_free(mem);
791 croak("Could not extract public key (type %d)", EVP_PKEY_base_id(self));
792 }
793 printstatus = printstatus && ( BIO_write(mem, "\\0", 1) > 0 );
794 if (! printstatus) {
795 BIO_free(mem);
796 sslcroak("Serializing public key failed");
797 }
798 return BIO_mem_to_SV(mem);
799 }
800  
801 TO_PEM
802  
803 =head2 get_modulus ()
804  
805 Returns the modulus of this I<Crypt::OpenSSL::CA::PublicKey> instance,
806 assuming that it is an RSA or DSA key. This is similar to the output
807 of C<openssl x509 -modulus>, except that the leading C<< Modulus= >>
808 identifier is trimmed and the returned string is not
809 newline-terminated.
810  
811 =cut
812  
813 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_MODULUS";
Subroutine BEGIN: called CC=1 SCAR=0.0
814  
815 static
816 SV* get_modulus(SV* sv_self) {
817 1 EVP_PKEY* self = perl_unwrap("${\__PACKAGE__}", EVP_PKEY *, sv_self);
818 BIO* mem;
819 SV* retval;
820 int printstatus;
821  
822 if (! (mem = BIO_new(BIO_s_mem()))) {
823 croak("Cannot allocate BIO");
824 }
825  
826 RSA* rsa;
827 DSA* dsa;
828 const BIGNUM* modulus = NULL;
829 if ( (rsa = EVP_PKEY_get0_RSA(self)) ) {
830 RSA_get0_key(rsa, &modulus, NULL, NULL);
831 } else if ( (dsa = EVP_PKEY_get0_DSA(self)) ) {
832 DSA_get0_key(dsa, &modulus, NULL);
833 } else {
834 BIO_free(mem);
835 croak("Could not extract public key (type %d)", EVP_PKEY_base_id(self));
836 }
837  
838 printstatus = BN_print(mem, modulus) && ( BIO_write(mem, "\\0", 1) > 0 );
839 if (! printstatus) {
840 BIO_free(mem);
841 sslcroak("Serializing modulus failed");
842 }
843 return BIO_mem_to_SV(mem);
844 }
845  
846 GET_MODULUS
847  
848 =head2 get_openssl_keyid ()
849  
850 Returns a cryptographic hash over this public key, as OpenSSL's
851 C<subjectKeyIdentifier=hash> configuration directive to C<openssl ca>
852 would compute it for a certificate that contains this key. The return
853 value is a string of colon-separated pairs of uppercase hex digits,
854 adequate e.g. for passing as the $value parameter to
855 L</set_extension>.
856  
857 =cut
858  
859 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_OPENSSL_KEYID";
Subroutine BEGIN: called CC=1 SCAR=0.0
860  
861 static
862 SV* get_openssl_keyid(SV* sv_self) {
863 1 EVP_PKEY* self = perl_unwrap("${\__PACKAGE__}", EVP_PKEY *, sv_self);
864 X509* fakecert = NULL;
865 X509V3_CTX ctx;
866 ASN1_OCTET_STRING* hash = NULL;
867 char* hash_hex = NULL;
868 char* err = NULL;
869  
870 /* Find OpenSSL's "object class" that deals with subject
871 * key identifiers: */
872 const X509V3_EXT_METHOD* method = X509V3_EXT_get_nid(NID_subject_key_identifier);
873 if (! method) {
874 err = "X509V3_EXT_get_nid failed"; goto end;
875 }
876  
877 /* Pass the public key as part of a fake certificate, itself
878 * part of a mostly dummy X509V3_CTX, because that's what
879 * X509V3_EXT_METHOD*'s want: */
880 fakecert = X509_new();
881 if (! fakecert) {
882 err = "not enough memory for X509_new()"; goto end;
883 }
884 if (! X509_set_pubkey(fakecert, self)) {
885 err = "X509_set_pubkey failed"; goto end;
886 }
887 X509V3_set_ctx(&ctx, NULL, fakecert, NULL, NULL, 0);
888  
889 /* Invoke the method */
890 hash = (ASN1_OCTET_STRING*) method->s2i(method, &ctx, "hash");
891  
892 /* Convert the result to hex */
893 hash_hex = i2s_ASN1_OCTET_STRING((X509V3_EXT_METHOD*) method, hash);
894 if (! hash_hex) {
895 err = "i2s_ASN1_OCTET_STRING failed"; goto end;
896 }
897  
898 end:
899  
900 if (fakecert) { X509_free(fakecert); }
901 /* method seems to be statically allocated (no X509V3_EXT_METHOD_free
902 in sight) */
903 /* ctx is on the stack */
904 if (hash) { ASN1_OCTET_STRING_free(hash); }
905 /* hash_hex cannot be set (else we wouldn't have an error) */
906  
907 if (err) {
908 sslcroak(err);
909 }
910 return openssl_string_to_SV(hash_hex);
911 }
912  
913 GET_OPENSSL_KEYID
914  
915 =head1 Crypt::OpenSSL::CA::PrivateKey
916  
917 This Perl class wraps around the private key abstraction of OpenSSL.
918 I<Crypt::OpenSSL::CA::PrivateKey> objects are immutable.
919  
920 =cut
921  
922 package Crypt::OpenSSL::CA::PrivateKey;
923 1 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
924  
925 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"PRIVATEKEY_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
926 #include <openssl/pem.h>
927 #include <openssl/bio.h>
928 #include <openssl/engine.h>
929 #include <openssl/ui.h>
930 #include <openssl/evp.h>
931  
932 static
933 void DESTROY(SV* sv_self) {
934 1 EVP_PKEY_free(perl_unwrap("${\__PACKAGE__}", EVP_PKEY *, sv_self));
935 }
936  
937 PRIVATEKEY_BASE
938  
939 =head2 parse ($pemkey, %named_options)
940  
941 Parses a private key $pemkey and returns an instance of
942 I<Crypt::OpenSSL::CA::PrivateKey>. Available named options are:
943  
944 =over
945  
946 =item I<< -password => $password >>
947  
948 Tells that $pemkey is a software key encrypted with password
949 $password.
950  
951 =back
952  
953 Only software keys are supported for now (see L</TODO> about engine
954 support).
955  
956 =cut
957  
958 1009 ▶sub parse {
Subroutine parse: called CC=3 SCAR=11.0
959 1009 ▶ croak("incorrect number of arguments to parse()")
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 0 1009 1009
960 if (@_ % 2);
961 1009 my ($self, $keytext, %options) = @_;
962 1009 ▶ if (defined(my $pass = $options{-password})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $pass = $options{'-password'})) { } 3 1006 1009
963 3 return $self->_parse($keytext, $pass, undef, undef);
964 } else {
965 1006 return $self->_parse($keytext, undef, undef, undef);
966 }
967 }
968  
969 =begin internals
970  
971 =head2 _parse ($pemkey, $password, $engineobj, $use_engine_format)
972  
973 The XS counterpart of L</parse>, sans the syntactic sugar. Parses a
974 PEM-encoded private key and returns an instance of
975 I<Crypt::OpenSSL::CA::PrivateKey> wrapping a OpenSSL C<EVP_PKEY *>
976 handle. All four arguments are mandatory. I<$engineobj> and
977 I<$use_engine_format> are B<UNIMPLEMENTED> and should both be passed
978 as undef.
979  
980 =end internals
981  
982 =cut
983  
984 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"_PARSE";
Subroutine BEGIN: called CC=1 SCAR=0.0
985 /* Returns a password stored in memory. Callback invoked by
986 PEM_read_bio_PrivateKey() when parsing a password-protected
987 software private key */
988 static int gimme_password(char *buf, int bufsiz, int __unused_verify,
989 void *cb_data) {
990 int pwlength;
991 const char *password = (const char *) cb_data;
992 if (!password) { return -1; }
993 pwlength = strlen(password);
994 if (pwlength > bufsiz) { pwlength = bufsiz; }
995 memcpy(buf, password, pwlength);
996 return pwlength;
997 }
998  
999 /* Ditto, but using the ui_method API. Callback invoked by
1000 ENGINE_load_private_key when parsing an engine-based
1001 private key */
1002 /* UNIMPLEMENTED */
1003  
1004 static
1005 SV* _parse(char *class, const char* pemkey, SV* svpass,
1006 SV* engine, SV* parse_using_engine_p) {
1007 /* UNIMPLEMENTED: engine and parse_using_engine don't work */
1008 BIO* keybio = NULL;
1009 EVP_PKEY* pkey = NULL;
1010 ENGINE* e;
1011 char* pass = NULL;
1012  
1013 if (SvOK(svpass)) { pass = char0_value(svpass); }
1014  
1015 if (SvTRUE(parse_using_engine_p)) {
1016 static UI_METHOD *ui_method = NULL;
1017  
1018 croak("UNIMPLEMENTED, UNTESTED");
1019  
1020 if (! (engine &&
1021 (e = perl_unwrap("Crypt::OpenSSL::CA::ENGINE",
1022 ENGINE*, engine)))) {
1023 croak("no engine specified");
1024 }
1025  
1026 /* UNIMPLEMENTED: must parse from memory not file; must coerce
1027 that wonky ui_method stuff into * passing C<pass> to the
1028 engine */
1029 /* pkey = (EVP_PKEY *)ENGINE_load_private_key
1030 (e, file, ui_method, (void *) pass); */
1031 } else {
1032 keybio = BIO_new_mem_buf((void *) pemkey, -1);
1033 if (keybio == NULL) {
1034 croak("BIO_new failed");
1035 }
1036 pkey=PEM_read_bio_PrivateKey(keybio, NULL,
1037 gimme_password, (void *) pass);
1038 }
1039 if (keybio != NULL) BIO_free(keybio);
1040 if (pkey == NULL) {
1041 sslcroak("unable to parse private key");
1042 }
1043 1 return perl_wrap("${\__PACKAGE__}", pkey);
1044 }
1045 _PARSE
1046  
1047 =head2 get_public_key ()
1048  
1049 Returns the public key associated with this
1050 I<Crypt::OpenSSL::CA::PrivateKey> instance, as an
1051 L</Crypt::OpenSSL::CA::PublicKey> object.
1052  
1053 =cut
1054  
1055 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_PUBLIC_KEY";
Subroutine BEGIN: called CC=1 SCAR=0.0
1056  
1057 #if OPENSSL_VERSION_NUMBER < 0x00908000
1058 #define CONST_IF_D2I_PUBKEY_WANTS_ONE
1059 #else
1060 #define CONST_IF_D2I_PUBKEY_WANTS_ONE const
1061 #endif
1062  
1063 static
1064 SV* get_public_key(SV* sv_self) {
1065 1 EVP_PKEY* self = perl_unwrap("${\__PACKAGE__}", EVP_PKEY *, sv_self);
1066 EVP_PKEY* retval = NULL;
1067 unsigned char* asn1buf = NULL;
1068 CONST_IF_D2I_PUBKEY_WANTS_ONE unsigned char* asn1buf_copy;
1069 int size;
1070  
1071 /* This calling idiom requires OpenSSL 0.9.7 */
1072 size = i2d_PUBKEY(self, &asn1buf);
1073 if (size < 0) { sslcroak("i2d_PUBKEY failed"); }
1074  
1075 /* d2i_PUBKEY advances the pointer that is passed to it,
1076 so we need to make a copy: */
1077 asn1buf_copy = asn1buf;
1078 d2i_PUBKEY(&retval, &asn1buf_copy, size);
1079 OPENSSL_free(asn1buf);
1080 if (! retval) {
1081 sslcroak("d2i_PUBKEY failed");
1082 }
1083 return perl_wrap("Crypt::OpenSSL::CA::PublicKey", retval);
1084 }
1085  
1086 GET_PUBLIC_KEY
1087  
1088 =begin OBSOLETE
1089  
1090 =head2 get_RSA_modulus ()
1091  
1092 For compatibility with 0.03. Use ->get_public_key->get_modulus
1093 instead.
1094  
1095 =end OBSOLETE
1096  
1097 =cut
1098  
1099 1 ▶sub get_RSA_modulus { shift->get_public_key->get_modulus }
Subroutine get_RSA_modulus: called CC=1 SCAR=0.0
1100  
1101 =begin UNIMPLEMENTED
1102  
1103 =head1 Crypt::OpenSSL::CA::ENGINE
1104  
1105 This package models the C<ENGINE_*> functions of OpenSSL.
1106  
1107 =cut
1108  
1109 package Crypt::OpenSSL::CA::ENGINE;
1110  
1111 #use Crypt::OpenSSL::CA::Inline::C <<"ENGINE_BASE";
1112 1 (undef) = <<"ENGINE_BASE";
1113 #include <openssl/engine.h>
1114  
1115 static
1116 void DESTROY(SV* sv_self) {
1117 1 ENGINE_free(perl_unwrap("${\__PACKAGE__}", ENGINE *, sv_self));
1118 }
1119  
1120 ENGINE_BASE
1121  
1122 =head2 setup_simple ($engine, $debugp)
1123  
1124 Starts engine $engine (a string), optionally enabling debug if $debugp
1125 (an integer) is true. Returns a structural reference to same (see
1126 B<engine(3)> to find out what that means).
1127  
1128 The code is lifted from OpenSSL's C<setup_engine()> in C<apps.c>, which despite
1129 falling short from C<engine.c> feature-wise (hence the name, I<setup_simple>)
1130 proves sufficient in practice to have the C</usr/bin/openssl> command-line tool
1131 perform all relevant RSA operations with a variety of
1132 L<Crypt::OpenSSL::CA::AlphabetSoup/HSM>s. Therefore, in spite of not having
1133 tested it due to lack of appropriate hardware, I am confident that
1134 I<Crypt::OpenSSL::CA> can be make to work with the hardware OpenSSL engines with
1135 relatively little fuss.
1136  
1137 =cut
1138  
1139 #use Crypt::OpenSSL::CA::Inline::C <<"ENGINE_CODE";
1140 1 (undef) = <<"ENGINE_CODE";
1141 static
1142 SV* setup_simple(const char *engine, int debug) {
1143 ENGINE *e = NULL;
1144  
1145 if (! engine) { croak("Expected engine name"); }
1146  
1147 if(strcmp(engine, "auto") == 0) {
1148 croak("engine \\"auto\\" is not supported.");
1149 }
1150 if((e = ENGINE_by_id(engine)) == NULL
1151 && (e = try_load_engine(err, engine, debug)) == NULL) {
1152 croak("invalid engine \\"%s\\", engine);
1153 }
1154 if (debug) {
1155 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM,
1156 0, err, 0);
1157 }
1158 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1159 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1160 ENGINE_free(e);
1161 croak("can't use that engine");
1162 }
1163  
1164 1 return perl_wrap("${\__PACKAGE__}", e);
1165 }
1166  
1167 ENGINE_CODE
1168  
1169 =end UNIMPLEMENTED
1170  
1171 =begin internals
1172  
1173 =head1 Crypt::OpenSSL::CA::CONF
1174  
1175 A wrapper around an OpenSSL C<CONF *> data structure that contains the
1176 OpenSSL configuration data. Used by L</add_extension> and friends.
1177  
1178 This POD is not made visible in the man pages (for now), as
1179 L</add_extension> totally shadows the use of this class.
1180  
1181 =cut
1182  
1183 package Crypt::OpenSSL::CA::CONF;
1184  
1185 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"CONF_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
1186 #include <openssl/conf.h>
1187 #include <string.h> /* for strlen */
1188  
1189 static
1190 void DESTROY(SV* sv_self) {
1191 1 NCONF_free(perl_unwrap("${\__PACKAGE__}", CONF *, sv_self));
1192 }
1193  
1194 CONF_BASE
1195  
1196 =head2 new ($confighash)
1197  
1198 Creates the configuration file data structure. C<$confighash>
1199 parameter is a reference to a hash of hashes; the first-level keys are
1200 section names, and the second-level keys are parameter names. Returns
1201 an immutable object of class I<Crypt::OpenSSL::CA::CONF>.
1202  
1203 =cut
1204  
1205 320530 ▶sub new {
Subroutine new: called CC=3 SCAR=11.0
1206 320530 my ($class, $conf) = @_;
1207  
1208 320530 my $config_text = "";
1209  
1210 320530 foreach my $section (keys %$conf) {
1211 80108 $config_text .= "[$section]\n\n";
1212 80108 my $section_struct = $conf->{$section};
1213 80108 foreach my $k (keys %$section_struct) {
1214 280123 my $v = $section_struct->{$k};
1215  
1216 280123 $config_text .= "$k = $v\n";
1217 }
1218 }
1219  
1220 320528 return $class->parse($config_text);
1221 }
1222  
1223 =head2 parse ($config_string)
1224  
1225 Deserializes the configuration file data structure from a multiline string.
1226  
1227 =cut
1228  
1229 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"NEW";
Subroutine BEGIN: called CC=1 SCAR=0.0
1230 static
1231 SV* parse(SV* class, char* config_text) {
1232 CONF* self = NCONF_new(NULL);
1233 if (! self) {
1234 croak("NCONF_new failed");
1235 }
1236  
1237 BIO* mem = BIO_new(BIO_s_mem());
1238 if (! mem) {
1239 NCONF_free(self);
1240 croak("Cannot allocate BIO");
1241 }
1242  
1243 size_t len = strlen(config_text);
1244 if (BIO_write(mem, config_text, len) < len) {
1245 NCONF_free(self);
1246 BIO_free(mem);
1247 croak("Cannot copy config_text to OpenSSL memory");
1248 }
1249  
1250 long errline = 0;
1251 int load_status = NCONF_load_bio(self, mem, &errline);
1252 BIO_free(mem);
1253 if (errline || ! load_status) {
1254 NCONF_free(self);
1255 if (errline) {
1256 sslcroak("CONF->parse: error on line %l", errline);
1257 } else {
1258 sslcroak("CONF->parse: NCONF_load_bio failed");
1259 }
1260 }
1261  
1262 1 return perl_wrap("${\__PACKAGE__}", self);
1263 }
1264 NEW
1265  
1266 =head2 get_string ($section, $key)
1267  
1268 Calls OpenSSL's C<CONF_get_string>. Throws an exception as described
1269 in L</Error Management> if the configuration entry is not found.
1270 Unused in I<Crypt::OpenSSL::CA>, for test purposes only.
1271  
1272 =cut
1273  
1274 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_STRING";
Subroutine BEGIN: called CC=1 SCAR=0.0
1275  
1276 static
1277 SV* get_string(SV* sv_self, char* section, char* key) {
1278 1 CONF* self = perl_unwrap("${\__PACKAGE__}", CONF *, sv_self);
1279 char* retval;
1280  
1281 retval = NCONF_get_string(self, section, key);
1282 if (! retval) { sslcroak("NCONF_get_string failed"); }
1283 return newSVpv(retval, 0);
1284 }
1285  
1286 GET_STRING
1287  
1288 =head1 Crypt::OpenSSL::CA::X509V3_EXT
1289  
1290 Instances of this class model OpenSSL's C<X509V3_EXT *> extensions
1291 just before they get added to a certificate or a CRL by
1292 L</add_extension>. They are immutable.
1293  
1294 Like L</Crypt::OpenSSL::CA::CONF>, this POD section is not made
1295 visible in the man pages (for now), as L</add_extension> totally
1296 shadows the use of this class. Furthermore, the API of this class
1297 stinks from a Perl's hacker point of view (mainly because of the
1298 positional parameters). Granted, the only point of this class is to
1299 have several constructors, so as to introduce polymorphism into
1300 ->_do_add_extension without overflowing its argument list in an even
1301 more inelegant fashion.
1302  
1303 =cut
1304  
1305 package Crypt::OpenSSL::CA::X509V3_EXT;
1306  
1307 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"X509V3_EXT_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
1308 #include <openssl/x509v3.h>
1309  
1310 static
1311 void DESTROY(SV* sv_self) {
1312 1 X509_EXTENSION_free(perl_unwrap("${\__PACKAGE__}",
1313 X509_EXTENSION *, sv_self));
1314 }
1315  
1316 X509V3_EXT_BASE
1317  
1318 =head2 new_from_X509V3_EXT_METHOD ($ext_name, $value, $CONF)
1319  
1320 Creates and returns an extension using OpenSSL's I<X509V3_EXT_METHOD>
1321 mechanism, which is summarily described in
1322 L<Crypt::OpenSSL::CA::Resources/openssl.txt>. $ext_name is a string
1323 whose value can be whatever OpenSSL's C<OBJ_txt2nid> function accepts,
1324 i.e. an extension short name, an extension long name, or an Object
1325 Identifier (OID) in dotted notation. $value is the string value as it
1326 would be found in OpenSSL's configuration file under the entry that
1327 defines this extension (e.g. "critical,CA:FALSE"). $CONF is an
1328 instance of L</Crypt::OpenSSL::CA::CONF> that provides additional
1329 configuration for complex X509v3 extensions.
1330  
1331 =cut
1332  
1333 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"NEW_FROM_X509V3_EXT_METHOD";
Subroutine BEGIN: called CC=1 SCAR=0.0
1334 static
1335 SV* new_from_X509V3_EXT_METHOD(SV* class, const char* ext_name, const char* value, SV* sv_config) {
1336 if (! ext_name) { croak("No extension specified"); }
1337 if (! value) { croak("No value specified"); }
1338  
1339 X509V3_CTX ctx;
1340 X509V3_set_ctx(&ctx, NULL, NULL, NULL, NULL, 0);
1341  
1342 CONF* config = perl_unwrap("Crypt::OpenSSL::CA::CONF",
1343 CONF *, sv_config);
1344 X509V3_set_nconf(&ctx, config);
1345  
1346 X509_EXTENSION* self = X509V3_EXT_nconf(config, &ctx, ext_name, value);
1347 if (!self) { sslcroak("X509V3_EXT_nconf failed"); }
1348  
1349 1 return perl_wrap("${\__PACKAGE__}", self);
1350 }
1351  
1352 NEW_FROM_X509V3_EXT_METHOD
1353  
1354 =head2 new_authorityKeyIdentifier (critical => $critical,
1355 keyid => $keyid, issuer => $issuerobj,
1356 serial => $serial_hexstring)
1357  
1358 Creates and returns an X509V3 authorityKeyIdentifier extension as per
1359 RFC3280 section 4.2.1.1, with the keyid set to $keyid (if not undef)
1360 and the issuer and serial set to $issuer and $serial, respectively (if
1361 both are not undef). This extension is adequate both for certificates
1362 and CRLs. Oddly enough, such a construct is not possible using
1363 L</new_from_X509V3_EXT_METHOD>: OpenSSL does not support storing a
1364 literal value in the configuration file for C<authorityKeyIdentifier>,
1365 it only supports copying it from the CA certificate (whereas we don't
1366 want to insist on the user of I<Crypt::OpenSSL::CA> having said CA
1367 certificate at hand).
1368  
1369 $critical is a boolean indicating whether the extension should be
1370 marked critical. $keyid (if defined) is a string of colon-separated
1371 pairs of uppercase hex digits typically obtained using
1372 L</get_subject_keyid> or L</get_openssl_keyid>. $issuerobj (if
1373 defined) is an L</Crypt::OpenSSL::CA::X509_NAME> object.
1374 $serial_hexstring (if defined) is a scalar containing a lowercase,
1375 hexadecimal string that starts with "0x".
1376  
1377 Note that identifying the authority key by issuer name and serial
1378 number (that is, passing non-undef values for $issuerobj and
1379 $serial_hexstring) is frowned upon in
1380 L<Crypt::OpenSSL::CA::Resources/X509 Style Guide>.
1381  
1382 =cut
1383  
1384 {
1385 1 my $fake_pubkey;
1386  
1387 100012 ▶ sub new_authorityKeyIdentifier {
Subroutine new_authorityKeyIdentifier: called CC=7 SCAR=19.6
1388 100012 ▶ $fake_pubkey ||=
Condition66%2/3
$fake_pubkey ||= "Crypt::OpenSSL::CA::PublicKey"->parse_RSA("-----BEGIN PUBLIC KEY-----\nMCAwDQYJKoZIhvcNAQEBBQADDwAwDAIFAM7azvECAwEAAQ==\n-----END PUBLIC KEY-----\n")
l!l&&r!l&&!r
10001110
MC/DC0%0/2
$fake_pubkey ||= "Crypt::OpenSSL::CA::PublicKey"->parse_RSA("-----BEGIN PUBLIC KEY-----\nMCAwDQYJKoZIhvcNAQEBBQADDwAwDAIFAM7azvECAwEAAQ==\n-----END PUBLIC KEY-----\n")
$fake_pubkey "Crypt::OpenSSL::CA::PublicKey"->parse_RSA("-----BEGIN PUBLIC KEY-----\nMCAwDQYJKoZIhvcNAQEBBQADDwAwDAIFAM7azvECAwEAAQ==\n-----END PUBLIC KEY-----\n")
Truth table66%2/3
A ||= B
A= $fake_pubkeyB= "Crypt::OpenSSL::CA::PublicKey"->parse_RSA("-----BEGIN PUBLIC KEY-----\nMCAwDQYJKoZIhvcNAQEBBQADDwAwDAIFAM7azvECAwEAAQ==\n-----END PUBLIC KEY-----\n")
ABresult
1X1
011
000
1389 Crypt::OpenSSL::CA::PublicKey->parse_RSA(<<"RSA_32BIT");
1390 -----BEGIN PUBLIC KEY-----
1391 MCAwDQYJKoZIhvcNAQEBBQADDwAwDAIFAM7azvECAwEAAQ==
1392 -----END PUBLIC KEY-----
1393 RSA_32BIT
1394  
1395 100012 my ($class, %opts) = @_;
1396  
1397 100012 my $fakecert = Crypt::OpenSSL::CA::X509->new($fake_pubkey);
1398 my $wants_serial_and_issuer =
1399 100012 ▶ ($opts{serial} && $opts{issuer}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'serial'} && $opts{'issuer'} ? : 60005 40007 100012
Condition66%2/3
$opts{"serial"} and $opts{"issuer"}
!ll&&!rl&&r
40007060005
MC/DC50%1/2
$opts{"serial"} and $opts{"issuer"}
$opts{"serial"} $opts{"issuer"}
Truth table66%2/3
A and B
A= $opts{"serial"}B= $opts{"issuer"}
ABresult
0X0
100
111
1400 100012 ▶ if ($wants_serial_and_issuer) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_serial_and_issuer) 60005 40007 100012
1401 60005 $fakecert->set_serial($opts{serial});
1402 60005 $fakecert->set_issuer_DN($opts{issuer});
1403 }
1404 100012 ▶ if ($opts{keyid}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"keyid"}) 100011 1 100012
1405 100011 $fakecert->add_extension(subjectKeyIdentifier => $opts{keyid});
1406 }
1407  
1408 return $class->_new_authorityKeyIdentifier_from_fake_cert
1409 100012 ▶ ($fakecert, ($opts{critical} ? 1 : 0),
Branch: 1 branch
BranchTrueFalseTotal
$opts{'critical'} ? : 0 100012 100012
1410 $wants_serial_and_issuer);
1411 }
1412 }
1413  
1414 =head2 _new_authorityKeyIdentifier_from_fake_cert
1415 ($fakecert, $is_critical, $wants_serial_and_issuer)
1416  
1417 Does the job of L</new_authorityKeyIdentifier>: creates an
1418 C<authorityKeyIdentifier> extension by extracting the keyid, serial
1419 and issuer information from $fakecert, as OpenSSL would. $fakecert is
1420 an L</Crypt::OpenSSL::CA::X509> object that mimics the issuer of the
1421 certificate with which the returned extension will be fitted; it is
1422 typcally created on the spot by I<new_authorityKeyIdentifier()>, and
1423 may be almost completely bogus, as all its fields except the
1424 aforementioned three are ignored. $is_critical is 1 or 0, depending
1425 on whether the extension should be made critical.
1426 $wants_serial_and_issuer is 1 or 0, depending on whether the C<issuer>
1427 and C<serial> authority key identifier information should be scavenged
1428 from $fakecert (by contrast,
1429 I<_new_authorityKeyIdentifier_from_fake_cert> will always attempt to
1430 duplicate $fakecert's C<subjectKeyIdentifier>, so if you don't want
1431 one in the returned extension, simply don't put it there).
1432  
1433 This supremely baroque kludge is needed because creating an
1434 authorityKeyIdentifier X509_EXTENSION ``by hand'' with OpenSSL is
1435 nothing short of impossible: the AUTHORITY_KEYID ASN.1 structure,
1436 which would be the ASN.1 value of the extension, is not exported by
1437 OpenSSL.
1438  
1439 =cut
1440  
1441 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"_NEW_AUTHORITYKEYIDENTIFIER_ETC";
Subroutine BEGIN: called CC=1 SCAR=0.0
1442 static
1443 SV* _new_authorityKeyIdentifier_from_fake_cert(SV* class, SV* fakecert_sv,
1444 int is_critical, int wants_serial_and_issuer) {
1445 X509V3_CTX ctx;
1446 X509* fakecert = perl_unwrap("Crypt::OpenSSL::CA::X509",
1447 X509 *, fakecert_sv);
1448 X509_EXTENSION* self;
1449  
1450 X509V3_set_ctx_nodb(&ctx);
1451 X509V3_set_ctx(&ctx, fakecert, fakecert, NULL, NULL, 0);
1452  
1453 self = X509V3_EXT_nconf_nid(NULL, &ctx, NID_authority_key_identifier,
1454 (wants_serial_and_issuer ? "keyid,issuer:always" : "keyid"));
1455 if (!self) {
1456 sslcroak("failed to copy the key identifier as a new extension");
1457 }
1458 X509_EXTENSION_set_critical(self, is_critical ? 1 : 0);
1459 1 return perl_wrap("${\__PACKAGE__}", self);
1460 }
1461 _NEW_AUTHORITYKEYIDENTIFIER_ETC
1462  
1463 =head2 new_CRL_serial ($critical, $oid, $serial)
1464  
1465 This constructor implements the C<crlNumber> and C<deltaCRLIndicator>
1466 CRL extensions as described in L</Crypt::OpenSSL::CA::X509_CRL>.
1467 $critical is the criticality flag, as integer (to be interpreted as a
1468 Boolean). $oid is the extension's OID, as a dot-separated sequence of
1469 decimal integers. $serial is an instance of
1470 L</Crypt::OpenSSL::CA::ASN1_INTEGER> (or something that can be
1471 C<< ->parse() >>d into one).
1472  
1473 =cut
1474  
1475 20001 ▶sub new_CRL_serial {
Subroutine new_CRL_serial: called CC=1 SCAR=0.0
1476 20001 my ($self, $critical, $oid, $serial) = @_;
1477 20001 return $self->_new_CRL_serial(
1478 $critical, $oid,
1479 Crypt::OpenSSL::CA::ASN1_INTEGER->parse($serial));
1480 }
1481  
1482 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"NEW_CRL_SERIAL";
Subroutine BEGIN: called CC=1 SCAR=0.0
1483 static
1484 SV* _new_CRL_serial(char* class, int critical, char* oidtxt, SV* sv_serial) {
1485 int nid;
1486 X509_EXTENSION* self;
1487 ASN1_INTEGER* serial = perl_unwrap("Crypt::OpenSSL::CA::ASN1_INTEGER",
1488 ASN1_INTEGER *, sv_serial);
1489  
1490 if (! strcmp(oidtxt, "2.5.29.20")) { /* crlNumber */
1491 nid = NID_crl_number;
1492 } else if (! strcmp(oidtxt, "2.5.29.27")) { /* deltaCRLIndicator */
1493 nid = NID_delta_crl;
1494 } else {
1495 croak("Unknown serial-like CRL extension %s", oidtxt);
1496 }
1497  
1498 self = X509V3_EXT_i2d(nid, critical, serial);
1499 if (! self) { sslcroak("X509V3_EXT_i2d failed"); }
1500 1 return perl_wrap("${\__PACKAGE__}", self);
1501 }
1502 NEW_CRL_SERIAL
1503  
1504 =head2 new_freshestCRL ($value, $CONF)
1505  
1506 This constructor implements the C<freshestCRL> CRL extension, as
1507 described in L</Crypt::OpenSSL::CA::X509_CRL>. The parameters
1508 C<$value> and C<$CONF> work the same as in
1509 L</new_from_X509V3_EXT_METHOD>, including the criticality-in-$value
1510 trick.
1511  
1512 =cut
1513  
1514 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"NEW_FRESHESTCRL";
Subroutine BEGIN: called CC=1 SCAR=0.0
1515 static
1516 SV* new_freshestCRL(char* class, char* value, SV* sv_config) {
1517 X509V3_CTX ctx;
1518 X509_EXTENSION* self;
1519 CONF* config = perl_unwrap("Crypt::OpenSSL::CA::CONF",
1520 CONF *, sv_config);
1521 static int nid_freshest_crl = 0;
1522  
1523 if (! value) { croak("No value specified"); }
1524  
1525 if (! nid_freshest_crl && ! (nid_freshest_crl = OBJ_txt2nid("freshestCRL"))) {
1526 nid_freshest_crl = OBJ_create("2.5.29.46", "freshestCRL",
1527 "Delta CRL distribution points");
1528 }
1529  
1530 X509V3_set_ctx(&ctx, NULL, NULL, NULL, NULL, 0);
1531 X509V3_set_nconf(&ctx, config);
1532 self = X509V3_EXT_nconf_nid
1533 (config, &ctx, NID_crl_distribution_points, value);
1534 if (!self) { sslcroak("X509V3_EXT_nconf_nid failed"); }
1535 if (! X509_EXTENSION_set_object(self, OBJ_nid2obj(nid_freshest_crl))) {
1536 sslcroak("X509_EXTENSION_set_object failed");
1537 }
1538 1 return perl_wrap("${\__PACKAGE__}", self);
1539 }
1540  
1541 NEW_FRESHESTCRL
1542  
1543 =end internals
1544  
1545 =head1 Crypt::OpenSSL::CA::X509
1546  
1547 This Perl class wraps around the X509 certificate creation routines of
1548 OpenSSL. I<Crypt::OpenSSL::CA::X509> objects are mutable; they
1549 typically get constructed piecemeal, and signed once at the end with
1550 L</sign>.
1551  
1552 There is also limited support in this class for parsing certificates
1553 using L</parse> and various read accessors, but only insofar as it
1554 helps I<Crypt::OpenSSL::CA> be feature-compatible with OpenSSL's
1555 command-line CA. Namely, I<Crypt::OpenSSL::CA::X509> is currently
1556 only able to extract the information that customarily gets copied over
1557 from the CA's own certificate to the certificates it issues: the DN
1558 (with L</get_subject_DN> on the CA's certificate), the serial number
1559 (with L</get_serial>) and the public key identifier (with
1560 L</get_subject_keyid>). Patches are of course welcome, but TIMTOWTDI:
1561 please consider using a dedicated ASN.1 parser such as
1562 L<Convert::ASN1> or L<Crypt::X509> instead.
1563  
1564 =cut
1565  
1566 package Crypt::OpenSSL::CA::X509;
1567 1 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
1568  
1569 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"X509_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
1570 #include <openssl/pem.h>
1571 #include <openssl/bio.h>
1572 #include <openssl/x509.h>
1573 #include <openssl/x509v3.h>
1574 #include <openssl/evp.h> /* For EVP_get_digestbyname() */
1575 #include <openssl/bn.h> /* For BN_hex2bn in set_serial() */
1576 static
1577 void DESTROY(SV* sv_self) {
1578 1 X509_free(perl_unwrap("${\__PACKAGE__}", X509 *, sv_self));
1579 }
1580 X509_BASE
1581  
1582 =head2 Support for OpenSSL-style extensions
1583  
1584 L</set_extension> and L</add_extension> work with OpenSSL's
1585 I<X509V3_EXT_METHOD> mechanism, which is summarily described in
1586 L<Crypt::OpenSSL::CA::Resources/openssl.txt>. This means that most
1587 X509v3 extensions that can be set through OpenSSL's configuration file
1588 can be passed to this module as Perl strings in exactly the same way;
1589 see L</set_extension> for details.
1590  
1591 =head2 Constructors and Methods
1592  
1593 =head3 new ($pubkey)
1594  
1595 Create an empty certificate shell waiting to be signed for public key
1596 C<$pubkey>, an instance of L</Crypt::OpenSSL::CA::PublicKey>. All
1597 mandatory values in an X509 certificate are set to a dummy default
1598 value, which the caller will probably want to alter using the various
1599 I<set_*> methods in this class. Returns an instance of the class
1600 I<Crypt::OpenSSL::CA::X509>, wrapping around an OpenSSL C<X509 *>
1601 handle.
1602  
1603 =cut
1604  
1605 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"NEW";
Subroutine BEGIN: called CC=1 SCAR=0.0
1606 static
1607 SV* new(char* class, SV* sv_pubkey) {
1608 X509* self;
1609 EVP_PKEY* pubkey = perl_unwrap("Crypt::OpenSSL::CA::PublicKey",
1610 EVP_PKEY *, sv_pubkey);
1611 char* err;
1612  
1613 self = X509_new();
1614 if (! self) { err = "not enough memory for X509_new"; goto error; }
1615 if (! X509_set_version(self, 2))
1616 { err = "X509_set_version failed"; goto error; }
1617 if (! X509_set_pubkey(self, pubkey))
1618 { err = "X509_set_pubkey failed"; goto error; }
1619 if (! ASN1_INTEGER_set(X509_get_serialNumber(self), 1))
1620 { err = "ASN1_INTEGER_set failed"; goto error; }
1621 if (! ASN1_TIME_set(X509_get_notBefore(self), 0))
1622 { err = "ASN1_TIME_set failed for notBefore"; goto error; }
1623 if (! ASN1_TIME_set(X509_get_notAfter(self), 0))
1624 { err = "ASN1_TIME_set failed for notAfter"; goto error; }
1625  
1626 1 return perl_wrap("${\__PACKAGE__}", self);
1627  
1628 error:
1629 if (self) { X509_free(self); }
1630 sslcroak(err);
1631 return NULL; // Not reached
1632 }
1633 NEW
1634  
1635 =head3 parse ($pemcert)
1636  
1637 Parses a PEM-encoded X509 certificate and returns an instance of
1638 I<Crypt::OpenSSL::CA::X509> that already has a number of fields set.
1639 Despite this, the returned object can be L</sign>ed anew if one wants.
1640  
1641 =cut
1642  
1643 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"PARSE";
Subroutine BEGIN: called CC=1 SCAR=0.0
1644 static
1645 SV* parse(char *class, const char* pemcert) {
1646 BIO* keybio = NULL;
1647 X509* retval = NULL;
1648  
1649 keybio = BIO_new_mem_buf((void *) pemcert, -1);
1650 if (keybio == NULL) {
1651 croak("BIO_new failed");
1652 }
1653 retval = PEM_read_bio_X509(keybio, NULL, NULL, NULL);
1654 BIO_free(keybio);
1655  
1656 if (retval == NULL) {
1657 sslcroak("unable to parse certificate");
1658 }
1659 1 return perl_wrap("${\__PACKAGE__}", retval);
1660 }
1661 PARSE
1662  
1663 =head3 verify ($pubkey)
1664  
1665 Verifies that this certificate is validly signed by $pubkey, an
1666 instance of L</Crypt::OpenSSL::CA::PublicKey>, and throws an exception
1667 if not.
1668  
1669 =cut
1670  
1671 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"VERIFY";
Subroutine BEGIN: called CC=1 SCAR=0.0
1672 static
1673 int verify(SV* sv_self, SV* sv_pubkey) {
1674 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1675 EVP_PKEY* pubkey = perl_unwrap("Crypt::OpenSSL::CA::PublicKey",
1676 EVP_PKEY *, sv_pubkey);
1677 int result;
1678  
1679 result = X509_verify(self, pubkey);
1680  
1681 if (result > 0) { return result; }
1682 sslcroak("Certificate verify failed");
1683 return -1; /* Not reached */
1684 }
1685 VERIFY
1686  
1687 =head3 get_public_key ()
1688  
1689 Returns an instance of L</Crypt::OpenSSL::CA::PublicKey> that
1690 corresponds to the RSA or DSA public key in this certificate.
1691 Memory-management wise, this performs a copy of the underlying
1692 C<EVP_PKEY *> structure; therefore it is safe to destroy this
1693 certificate object afterwards and keep only the returned public key.
1694  
1695 =cut
1696  
1697 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_PUBLIC_KEY";
Subroutine BEGIN: called CC=1 SCAR=0.0
1698 static
1699 SV* get_public_key(SV* sv_self) {
1700 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1701 EVP_PKEY* pkey = X509_get_pubkey(self);
1702 if (! pkey) { sslcroak("Huh, no public key in this certificate?!"); }
1703  
1704 return perl_wrap("Crypt::OpenSSL::CA::PublicKey", pkey);
1705 }
1706 GET_PUBLIC_KEY
1707  
1708 =head3 get_subject_DN ()
1709  
1710 =head3 get_issuer_DN ()
1711  
1712 Returns the subject DN (resp. issuer DN) of this
1713 I<Crypt::OpenSSL::CA::X509> instance, as an
1714 L</Crypt::OpenSSL::CA::X509_NAME> instance. Memory-management wise,
1715 this performs a copy of the underlying C<X509_NAME *> structure;
1716 therefore it is safe to destroy this certificate object afterwards and
1717 keep only the returned DN.
1718  
1719 =cut
1720  
1721 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_DN";
Subroutine BEGIN: called CC=1 SCAR=0.0
1722 static
1723 SV* get_subject_DN(SV* sv_self) {
1724 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1725 X509_NAME* name = X509_get_subject_name(self);
1726  
1727 if (! name) { sslcroak("Huh, no subject name in certificate?!"); }
1728  
1729 name = X509_NAME_dup(name);
1730 if (! name) { croak("Not enough memory for get_subject_DN"); }
1731  
1732 return perl_wrap("Crypt::OpenSSL::CA::X509_NAME", name);
1733 }
1734  
1735 static
1736 SV* get_issuer_DN(SV* sv_self) {
1737 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1738 X509_NAME* name = X509_get_issuer_name(self);
1739  
1740 if (! name) { sslcroak("Huh, no issuer name in certificate?!"); }
1741  
1742 name = X509_NAME_dup(name);
1743 if (! name) { croak("Not enough memory for get_issuer_DN"); }
1744  
1745 return perl_wrap("Crypt::OpenSSL::CA::X509_NAME", name);
1746 }
1747 GET_DN
1748  
1749  
1750 =head3 set_subject_DN ($dn_object)
1751  
1752 =head3 set_issuer_DN ($dn_object)
1753  
1754 Sets the subject and issuer DNs from L</Crypt::OpenSSL::CA::X509_NAME>
1755 objects.
1756  
1757 =cut
1758  
1759 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"SET_DN";
Subroutine BEGIN: called CC=1 SCAR=0.0
1760 static
1761 void set_subject_DN(SV* sv_self, SV* dn_object) {
1762 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1763 X509_NAME* dn = perl_unwrap("Crypt::OpenSSL::CA::X509_NAME",
1764 X509_NAME *, dn_object);
1765 if (! X509_set_subject_name(self, dn)) {
1766 sslcroak("X509_set_subject_name failed");
1767 }
1768 }
1769  
1770 static
1771 void set_issuer_DN(SV* sv_self, SV* dn_object) {
1772 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1773 X509_NAME* dn = perl_unwrap("Crypt::OpenSSL::CA::X509_NAME",
1774 X509_NAME *, dn_object);
1775 if (! X509_set_issuer_name(self, dn)) {
1776 sslcroak("X509_set_issuer_name failed");
1777 }
1778 }
1779  
1780 SET_DN
1781  
1782 =head3 get_subject_keyid ()
1783  
1784 Returns the contents of the C<subjectKeyIdentifier> field, if present,
1785 as a string of colon-separated pairs of uppercase hex digits. If no
1786 such extension is available, returns undef. Depending on the whims of
1787 the particular CA that signed this certificate, this may or may not be
1788 the same as C<< $self->get_public_key->get_openssl_keyid >>.
1789  
1790 =cut
1791  
1792 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_SUBJECT_KEYID";
Subroutine BEGIN: called CC=1 SCAR=0.0
1793 static
1794 SV* get_subject_keyid(SV* sv_self) {
1795 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1796 X509_EXTENSION *ext;
1797 ASN1_OCTET_STRING *ikeyid;
1798 char* retval;
1799 int i;
1800  
1801 i = X509_get_ext_by_NID(self, NID_subject_key_identifier, -1);
1802 if (i < 0) {
1803 return newSVsv(&PL_sv_undef);
1804 }
1805 if (! ((ext = X509_get_ext(self, i)) &&
1806 (ikeyid = X509V3_EXT_d2i(ext))) ) {
1807 sslcroak("Failed extracting subject keyID from certificate");
1808 return NULL; /* Not reached */
1809 }
1810 retval = i2s_ASN1_OCTET_STRING(NULL, ikeyid);
1811 ASN1_OCTET_STRING_free(ikeyid);
1812 if (! retval) { croak("Converting to hex failed"); }
1813 return openssl_string_to_SV(retval);
1814 }
1815  
1816 GET_SUBJECT_KEYID
1817  
1818 =head3 get_serial ()
1819  
1820 Returns the serial number as an instance of L</Crypt::OpenSSL::CA::ASN1_INTEGER>.
1821  
1822 =cut
1823  
1824 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_SERIAL";
Subroutine BEGIN: called CC=1 SCAR=0.0
1825 static
1826 SV* get_serial(SV* sv_self) {
1827 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1828  
1829 ASN1_INTEGER* serial = X509_get_serialNumber(self);
1830 if (! serial) {
1831 sslcroak("X509_get_serialNumber failed");
1832 }
1833  
1834 ASN1_INTEGER* serial_dup = ASN1_INTEGER_dup(serial);
1835 if (! serial_dup) {
1836 sslcroak("ASN1_INTEGER_dup failed");
1837 }
1838  
1839 return perl_wrap("Crypt::OpenSSL::CA::ASN1_INTEGER", serial_dup);
1840 }
1841  
1842 GET_SERIAL
1843  
1844 =head3 set_serial ($serial)
1845  
1846 Sets the serial number to C<$serial>, which must be an instance of
1847 L</Crypt::OpenSSL::CA::ASN1_INTEGER> (or something that can be
1848 C<< ->parse() >>d into one).
1849  
1850 =cut
1851  
1852 120009 ▶sub set_serial {
Subroutine set_serial: called CC=1 SCAR=0.0
1853 120009 my ($self, $serial) = @_;
1854 120009 $self->_set_serial_ASN1_INTEGER(Crypt::OpenSSL::CA::ASN1_INTEGER->parse($serial));
1855 }
1856  
1857 # Undocumented and obsolete helper:
1858 1 ▶sub set_serial_hex {
Subroutine set_serial_hex: called CC=1 SCAR=0.0
1859 1 my ($self, $serial) = @_;
1860 1 $serial =~ s/^(-?)/${1}0x/;
1861 1 return $self->set_serial($serial);
1862 }
1863  
1864 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"SET_SERIAL";
Subroutine BEGIN: called CC=1 SCAR=0.0
1865  
1866 static
1867 void _set_serial_ASN1_INTEGER(SV* sv_self, SV* sv_serial) {
1868 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1869 ASN1_INTEGER* serial = perl_unwrap("Crypt::OpenSSL::CA::ASN1_INTEGER",
1870 ASN1_INTEGER *, sv_serial);
1871 if (! X509_set_serialNumber(self, serial)) {
1872 sslcroak("X509_set_serialNumber failed");
1873 }
1874 }
1875  
1876 SET_SERIAL
1877  
1878 =head3 get_notBefore ()
1879  
1880 =head3 set_notBefore ($startdate)
1881  
1882 =head3 get_notAfter ()
1883  
1884 =head3 set_notAfter ($enddate)
1885  
1886 Gets or sets the validity period of the certificate. The setter parameter
1887 must be an instance of L</Crypt::OpenSSL::CA::ASN1_TIME> (or something
1888 that can be C<< ->parse() >>d into one). The getter return value is in
1889 "Zulu" format (see L</zulu>).
1890  
1891 =cut
1892  
1893 1001 ▶sub get_notBefore { shift->_get_notBefore_raw->zulu }
Subroutine get_notBefore: called CC=1 SCAR=0.0
1894 1001 ▶sub get_notAfter { shift->_get_notAfter_raw->zulu }
Subroutine get_notAfter: called CC=1 SCAR=0.0
1895  
1896 40002 ▶sub set_notBefore {
Subroutine set_notBefore: called CC=1 SCAR=0.0
1897 40002 my ($self, $startdate) = @_;
1898 40002 $self->_set_notBefore(Crypt::OpenSSL::CA::ASN1_TIME->parse($startdate));
1899 }
1900  
1901 40002 ▶sub set_notAfter {
Subroutine set_notAfter: called CC=1 SCAR=0.0
1902 40002 my ($self, $enddate) = @_;
1903 40002 $self->_set_notAfter(Crypt::OpenSSL::CA::ASN1_TIME->parse($enddate));
1904 }
1905  
1906 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_SET_DATES";
Subroutine BEGIN: called CC=1 SCAR=0.0
1907  
1908 static SV* _ASN1_TIME_perlify(const ASN1_TIME* time) {
1909 ASN1_TIME* time_dup =
1910 ASN1_dup_of(ASN1_TIME, i2d_ASN1_TIME, d2i_ASN1_TIME, time);
1911 if (! time_dup) {
1912 sslcroak("Cannot ASN1_dup_of(time)");
1913 }
1914  
1915 return perl_wrap("Crypt::OpenSSL::CA::ASN1_TIME", time_dup);
1916 }
1917  
1918 static
1919 SV* _get_notBefore_raw(SV* sv_self) {
1920 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1921  
1922 const ASN1_TIME* notBefore = X509_get0_notBefore(self);
1923 if (! notBefore) {
1924 sslcroak("Cannot X509_get0_notBefore()");
1925 }
1926  
1927 return _ASN1_TIME_perlify(notBefore);
1928 }
1929  
1930 static
1931 SV* _get_notAfter_raw(SV* sv_self) {
1932 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1933  
1934 const ASN1_TIME* notAfter = X509_get0_notAfter(self);
1935 if (! notAfter) {
1936 sslcroak("Cannot X509_get0_notAfter()");
1937 }
1938  
1939 return _ASN1_TIME_perlify(notAfter);
1940 }
1941  
1942 static
1943 void _set_notBefore(SV* sv_self, SV* sv_startdate) {
1944 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1945 ASN1_TIME* time = perl_unwrap("Crypt::OpenSSL::CA::ASN1_TIME", ASN1_TIME *, sv_startdate);
1946 X509_set_notBefore(self, time);
1947 }
1948  
1949 static
1950 void _set_notAfter(SV* sv_self, SV* sv_enddate) {
1951 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
1952 ASN1_TIME* time = perl_unwrap("Crypt::OpenSSL::CA::ASN1_TIME", ASN1_TIME *, sv_enddate);
1953 X509_set_notAfter(self, time);
1954 }
1955 GET_SET_DATES
1956  
1957 =head3 extension_by_name ($extname)
1958  
1959 Returns true if and only if $extname is a valid X509v3 certificate
1960 extension, susceptible of being passed to L</set_extension> and
1961 friends.
1962  
1963 =begin internal
1964  
1965 Specifically, returns the OpenSSL NID associated with
1966 $extname, as an integer.
1967  
1968 =end internal
1969  
1970 =cut
1971  
1972 # This one is callable from both Perl and C, kewl!
1973 1 ▶use Crypt::OpenSSL::CA::Inline::C << "EXTENSION_BY_NAME";
Subroutine BEGIN: called CC=1 SCAR=0.0
1974 static
1975 int extension_by_name(SV* unused, char* extname) {
1976 int nid;
1977  
1978 if (! extname) { return 0; }
1979 nid = OBJ_txt2nid(extname);
1980  
1981 if (nid == NID_undef) { return 0; }
1982 const X509V3_EXT_METHOD* method = X509V3_EXT_get_nid(nid);
1983 if (!method) { return 0; }
1984  
1985 /* Extensions that cannot be created are obviously not supported. */
1986 if (! (method->v2i || method->s2i || method->r2i) ) { return 0; }
1987 /* This is also how we check whether this extension is for
1988 certificates or for CRLs: there simply is no support for
1989 creating the latter! When CRL extension support finally gets
1990 added to OpenSSL, we'll have to change that. */
1991  
1992 return nid;
1993 }
1994 EXTENSION_BY_NAME
1995  
1996 =head3 set_extension ($extname, $value, %options, %more_openssl_config)
1997  
1998 Sets X509 extension $extname to the value $value in the certificate,
1999 erasing any extension previously set for $extname in this certificate.
2000 To make a long story short, $extname and $value may be almost any
2001 B<explicit> legit key-value pair in the OpenSSL configuration file's
2002 section that is pointed to by the C<x509_extensions> parameter (see
2003 the details in the B<x509v3_config(5ssl)> manpage provided with
2004 OpenSSL). For example, OpenSSL's
2005  
2006 subjectKeyIdentifier=00:DE:AD:BE:EF
2007  
2008 becomes
2009  
2010 =for My::Tests::Below "set_extension subjectKeyIdentifier" begin
2011  
2012 $cert->set_extension( subjectKeyIdentifier => "00:DE:AD:BE:EF");
2013  
2014 =for My::Tests::Below "set_extension subjectKeyIdentifier" end
2015  
2016 However, B<implicit> extension values (ie, deducted from the CA
2017 certificate or the subject DN) are B<not> supported:
2018  
2019 =for My::Tests::Below "nice try with set_extension, no cigar" begin
2020  
2021 $cert->set_extension("authorityKeyIdentifier",
2022 "keyid:always,issuer:always"); # WRONG!
2023  
2024 =for My::Tests::Below "nice try with set_extension, no cigar" end
2025  
2026 $cert->set_extension(subjectAltName => 'email:copy'); # WRONG!
2027  
2028 The reason is that we don't want the API to insist on the CA certificate when
2029 setting these extensions. You can do this instead:
2030  
2031 =for My::Tests::Below "set_extension authorityKeyIdentifier" begin
2032  
2033 40003 $cert->set_extension(authorityKeyIdentifier =>
2034 { keyid => $ca->get_subject_keyid(),
2035 issuer => $ca->get_issuer_dn(),
2036 serial => $ca->get_serial() });
2037  
2038 40003 $cert->set_extension(subjectAltName => 'foo@example.com');
2039  
2040 =for My::Tests::Below "set_extension authorityKeyIdentifier" end
2041  
2042 where $ca is the CA's L</Crypt::OpenSSL::CA::X509> object, constructed
2043 for instance with L</parse>.
2044  
2045 (Note in passing, that using the C<issuer> and C<serial> elements for
2046 an authorityKeyIdentifier, while discussed in RFC3280 section 4.2.1.1,
2047 is frowned upon in L<Crypt::OpenSSL::CA::Resources/X509 Style Guide>).
2048  
2049 The arguments to I<set_extension> after the first two are interpreted
2050 as a list of key-value pairs. Those that start with a hyphen are the
2051 named options; they are interpreted like so:
2052  
2053 =over
2054  
2055 =item I<< -critical => 1 >>
2056  
2057 Sets the extension as critical. You may alternatively use the OpenSSL
2058 trick of prepending "critical," to $value, but that's ugly.
2059  
2060 =item I<< -critical => 0 >>
2061  
2062 Do not set the extension as critical. If C<critical> is present in
2063 $value, an exception will be raised.
2064  
2065 =back
2066  
2067 The extra key-value key arguments that do B<not> start with a hyphen
2068 are passed to OpenSSL as sections in its configuration file object;
2069 the corresponding values must therefore be references to hash tables.
2070 For example, here is how to transcribe the C<certificatePolicies>
2071 example from L<Crypt::OpenSSL::CA::Resources/openssl.txt> into Perl:
2072  
2073 =for My::Tests::Below "set_extension certificatePolicies" begin
2074  
2075 40003 $cert->set_extension(certificatePolicies =>
2076 'ia5org,1.2.3.4,1.5.6.7.8,@polsect',
2077 -critical => 0,
2078 polsect => {
2079 policyIdentifier => '1.3.5.8',
2080 "CPS.1" => 'http://my.host.name/',
2081 "CPS.2" => 'http://my.your.name/',
2082 "userNotice.1" => '@notice',
2083 },
2084 notice => {
2085 explicitText => "Explicit Text Here",
2086 organization => "Organisation Name",
2087 noticeNumbers => '1,2,3,4',
2088 });
2089  
2090 =for My::Tests::Below "set_extension certificatePolicies" end
2091  
2092 =cut
2093  
2094 280425 ▶sub set_extension {
Subroutine set_extension: called CC=2 SCAR=6.9
2095 280425 my ($self, $extname, @stuff) = @_;
2096 280425 my $real_extname = $extname;
2097 280425 ▶ $real_extname = "authorityKeyIdentifier" if
Branch: 1 branch
BranchTrueFalseTotal
if $extname =~ /^authorityKeyIdentifier/i 80010 200415 280425
2098 ($extname =~ m/^authorityKeyIdentifier/i); # OBSOLETE support
2099 # for authorityKeyIdentifier_keyid as was present in 0.04
2100 280425 $self->remove_extension($real_extname);
2101 280425 $self->add_extension($extname, @stuff);
2102 }
2103  
2104 =head3 add_extension ($extname, $value, %options, %more_openssl_config)
2105  
2106 Just like L</set_extension>, except that if there is already a
2107 value for this extension, it will not be removed; instead there will
2108 be a duplicate extension in the certificate. Note that this is
2109 explicitly forbiden by RFC3280 section 4.2, third paragraph, so maybe
2110 you shouldn't do that.
2111  
2112 =cut
2113  
2114 380439 ▶sub add_extension {
Subroutine add_extension: called CC=17 SCAR=28.5
2115 380439 ▶ die("incorrect number of arguments to add_extension()")
Branch: 1 branch
BranchTrueFalseTotal
unless @_ % 2 0 380439 380439
2116 unless (@_ % 2);
2117 380439 my ($self, $extname, $value, %options) = @_;
2118 380439 ▶ croak("add_extension: name is mandatory") unless
Branch: 1 branch
BranchTrueFalseTotal
unless $extname and length $extname 1 380438 380439
Condition66%2/3
$extname and length $extname
!ll&&!rl&&r
10380438
MC/DC50%1/2
$extname and length $extname
$extname length $extname
Truth table66%2/3
A and B
A= $extnameB= length $extname
ABresult
0X0
100
111
2119 ($extname && length($extname));
2120 380438 ▶ croak("add_extension: value is mandatory") unless
Branch: 1 branch
BranchTrueFalseTotal
unless $value and length $value 1 380437 380438
Condition66%2/3
$value and length $value
!ll&&!rl&&r
10380437
MC/DC50%1/2
$value and length $value
$value length $value
Truth table66%2/3
A and B
A= $valueB= length $value
ABresult
0X0
100
111
2121 ($value && length($value));
2122  
2123 380437 my $critical = "";
2124 380437 ▶ $critical = "critical," if ($value =~ s/^critical(,|$)//i);
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ s/^critical(,|$)//i 0 380437 380437
2125  
2126 380437 foreach my $k (keys %options) {
2127 200014 ▶ next unless $k =~ m/^-/;
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /^-/ 80006 120008 200014
2128 120008 my $v = delete $options{$k};
2129  
2130 120008 ▶ if ($k eq "-critical") {
Branch: 1 branch
BranchTrueFalseTotal
if ($k eq "-critical") 120008 0 120008
2131 120008 ▶ if ($v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v) { } 40003 80005 120008
2132 40003 $critical = "critical,";
2133 } else {
2134 80005 ▶ croak("add_extension: -critical => 0 conflicts" .
Branch: 1 branch
BranchTrueFalseTotal
if $critical 0 80005 80005
2135 " with ``$_[2]''") if ($critical);
2136 }
2137 }
2138 # Other named options may be added later.
2139 }
2140  
2141 # OBSOLETE, for compatibility only:
2142 380437 ▶ if ($extname eq "authorityKeyIdentifier_keyid") {
Branch: 1 branch
BranchTrueFalseTotal
if ($extname eq "authorityKeyIdentifier_keyid") 1 380436 380437
2143 1 $extname = "authorityKeyIdentifier";
2144 1 $value = { keyid => $value };
2145 }
2146  
2147 380437 my $ext;
2148 380437 ▶ if ($extname eq "authorityKeyIdentifier") {
Branch: 2 branches
BranchTrueFalseTotal
if ($extname eq 'authorityKeyIdentifier') { } 80010 300427 380437
elsif ($self->extension_by_name($extname)) { } 300426 1 300427
2149 80010 $ext = Crypt::OpenSSL::CA::X509V3_EXT->
2150 new_authorityKeyIdentifier(critical => $critical, %$value);
2151 } elsif ($self->extension_by_name($extname)) {
2152 300426 ▶ if (($extname eq "subjectAltName")
Branch: 1 branch
BranchTrueFalseTotal
if ($extname eq "subjectAltName" and not $value =~ /:/) 40003 260423 300426
Condition100%3/3
$extname eq "subjectAltName" and not $value =~ /:/
!ll&&!rl&&r
2204214000240003
MC/DC100%2/2
$extname eq "subjectAltName" and not $value =~ /:/
$extname eq "subjectAltName" not $value =~ /:/
Truth table100%3/3
A and not(B)
A= $extname eq "subjectAltName"B= not $value =~ /:/
ABresult
0X0
100
111
2153 and ($value !~ m/:/)) {
2154 # Once upon a time, it was possible to get away with an
2155 # untagged subjectAltName. Pretend we still can for the sake
2156 # of upward compatibility / green bar:
2157 40003 $value = "email:$value";
2158 }
2159  
2160 300426 $ext = Crypt::OpenSSL::CA::X509V3_EXT->new_from_X509V3_EXT_METHOD(
2161 $extname, "$critical$value", Crypt::OpenSSL::CA::CONF->new(\%options));
2162 } else {
2163 1 croak "Unknown extension name $extname";
2164 }
2165 380435 $self->_do_add_extension($ext);
2166 }
2167  
2168  
2169  
2170 =head3 remove_extension ($extname)
2171  
2172 Removes any and all extensions named $extname in this certificate.
2173  
2174 =cut
2175  
2176 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"REMOVE_EXTENSION";
Subroutine BEGIN: called CC=1 SCAR=0.0
2177 static
2178 void remove_extension(SV* sv_self, char* key) {
2179 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
2180 X509_EXTENSION* deleted;
2181 int nid, i;
2182  
2183 nid = extension_by_name(NULL, key);
2184 if (nid == NID_undef) { croak("Unknown extension specified"); }
2185  
2186 while( (i = X509_get_ext_by_NID(self, nid, -1)) >= 0) {
2187 if (! (deleted = X509_delete_ext(self, i)) ) {
2188 sslcroak("X509_delete_ext failed");
2189 }
2190 X509_EXTENSION_free(deleted);
2191 }
2192 }
2193 REMOVE_EXTENSION
2194  
2195 =begin internals
2196  
2197 =head3 _do_add_extension ($extension)
2198  
2199 Does the actual job of L</add_extension>, sans all the syntactic
2200 sugar. $extension is an instance of
2201 L</Crypt::OpenSSL::CA::X509V3_EXT>.
2202  
2203 =end internals
2204  
2205 =cut
2206  
2207 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"DO_ADD_EXTENSION";
Subroutine BEGIN: called CC=1 SCAR=0.0
2208 static
2209 void _do_add_extension(SV* sv_self, SV* sv_extension) {
2210 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
2211 X509_EXTENSION *ex = perl_unwrap("Crypt::OpenSSL::CA::X509V3_EXT",
2212 X509_EXTENSION *, sv_extension);
2213  
2214 if (! X509_add_ext(self, ex, -1)) {
2215 sslcroak("X509_add_ext failed");
2216 }
2217 }
2218 DO_ADD_EXTENSION
2219  
2220 =head3 dump ()
2221  
2222 Returns a textual representation of all the fields inside the
2223 (unfinished) certificate. This is done using OpenSSL's
2224 C<X509_print()>.
2225  
2226 =cut
2227  
2228 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"DUMP";
Subroutine BEGIN: called CC=1 SCAR=0.0
2229 static
2230 SV* dump(SV* sv_self) {
2231 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
2232 BIO* mem = BIO_new(BIO_s_mem());
2233  
2234 if (! mem) {
2235 croak("Cannot allocate BIO");
2236 }
2237  
2238 if (! (X509_print(mem, self) && ( BIO_write(mem, "\\0", 1) > 0)) ) {
2239 sslcroak("X509_print failed");
2240 }
2241  
2242 return BIO_mem_to_SV(mem);
2243 }
2244 DUMP
2245  
2246 =head3 sign ($privkey, $digestname)
2247  
2248 Signs the certificate (TADA!!). C<$privkey> is an instance of
2249 L</Crypt::OpenSSL::CA::PrivateKey>; C<$digestname> is the name of one
2250 of cryptographic digests supported by OpenSSL, e.g. "sha1" or "sha256"
2251 (notice that using "md5" is B<strongly discouraged> due to security
2252 considerations; see
2253 L<http://www.win.tue.nl/~bdeweger/CollidingCertificates/>). Returns
2254 the PEM-encoded certificate as a string.
2255  
2256 =cut
2257  
2258 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"SIGN";
Subroutine BEGIN: called CC=1 SCAR=0.0
2259 static
2260 SV* sign(SV* sv_self, SV* privkey, char* digestname) {
2261 1 X509* self = perl_unwrap("${\__PACKAGE__}", X509 *, sv_self);
2262 EVP_PKEY* key = perl_unwrap("Crypt::OpenSSL::CA::PrivateKey",
2263 EVP_PKEY *, privkey);
2264 const EVP_MD* digest;
2265 BIO* mem;
2266  
2267 if (! (digest = EVP_get_digestbyname(digestname))) {
2268 sslcroak("Unknown digest name: %s", digestname);
2269 }
2270  
2271 if (! X509_sign(self, key, digest)) {
2272 sslcroak("X509_sign failed");
2273 }
2274  
2275 if (! (mem = BIO_new(BIO_s_mem()))) {
2276 croak("Cannot allocate BIO");
2277 }
2278 if (! (PEM_write_bio_X509(mem, self) &&
2279 (BIO_write(mem, "\\0", 1) > 0)) ) {
2280 BIO_free(mem);
2281 croak("Serializing certificate failed");
2282 }
2283 return BIO_mem_to_SV(mem);
2284 }
2285  
2286 SIGN
2287  
2288 =head2 supported_digests()
2289  
2290 This is a class method (invoking it as an instance method also works
2291 though). Returns the list of all supported digest names for the
2292 second argument of L</sign>. The contents of this list depends on the
2293 OpenSSL version and the details of how it was compiled.
2294  
2295 =cut
2296  
2297 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"SUPPORTED_DIGESTS";
Subroutine BEGIN: called CC=1 SCAR=0.0
2298 #include <openssl/objects.h>
2299  
2300 static void _push_name_to_Perl(const OBJ_NAME* obj, void* unused) {
2301 /* Use dSP here ("declare stack pointer") instead of the more heavyweight
2302 * Inline_Stack_Vars (aka dXSARGS), which would truncate the Perl stack
2303 * every time. See L<perlapi/dSP> and L<perlapi/dXSARGS>.
2304 */
2305 dSP;
2306 Inline_Stack_Push(sv_2mortal(newSVpv(obj->name, 0)));
2307 Inline_Stack_Done; /* It's okay if we are actually not quite done yet. */
2308 }
2309  
2310 static
2311 void supported_digests(SV* unused_self) {
2312 Inline_Stack_Vars;
2313 Inline_Stack_Reset;
2314 OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, &_push_name_to_Perl, NULL);
2315 /* No Inline_Stack_Done here: that would reinstate *our* copy of the stack
2316 * pointer, like it was at function entry (ie empty stack).
2317 */
2318 }
2319  
2320 SUPPORTED_DIGESTS
2321  
2322 =head1 Crypt::OpenSSL::CA::X509_CRL
2323  
2324 This Perl class wraps around OpenSSL's CRL creation features.
2325  
2326 =cut
2327  
2328 package Crypt::OpenSSL::CA::X509_CRL;
2329 1 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
2330 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"X509_CRL_BASE";
Subroutine BEGIN: called CC=1 SCAR=0.0
2331 #include <openssl/pem.h>
2332 #include <openssl/bio.h>
2333 #include <openssl/x509.h>
2334 #include <openssl/x509v3.h>
2335  
2336 static
2337 void DESTROY(SV* sv_self) {
2338 1 X509_CRL_free(perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self));
2339 }
2340 X509_CRL_BASE
2341  
2342 =head2 new ()
2343  
2344 =head2 new ($version)
2345  
2346 Creates and returns an empty I<Crypt::OpenSSL::CA::X509_CRL> object.
2347 $version is the CRL version, e.g. C<1> or C<2> or C<CRLv1> or C<CRLv2>
2348 for idiomatics. The default is CRLv2, as per RFC3280. Setting the
2349 version to 1 will cause I<add_extension()> and L</add_entry> with
2350 extensions to throw an exception instead of working.
2351  
2352 =cut
2353  
2354 103 ▶sub new {
Subroutine new: called CC=3 SCAR=11.3
2355 103 my ($class, $version) = @_;
2356 103 ▶ $version = "CRLv2" if (! defined $version);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version 102 1 103
2357 103 ▶ unless ($version =~ m/([12])$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($version =~ /([12])$/) 0 103 103
2358 0 croak("Incorrect version string $version");
2359 }
2360 103 return $class->_new($1 - 1);
2361 }
2362  
2363 =head2 parse ($pem_crl)
2364  
2365 Creates and returns I<Crypt::OpenSSL::CA::X509_CRL> object parsed from
2366 C<$pem_crl>.
2367  
2368 =cut
2369  
2370 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"PARSE_CRL";
Subroutine BEGIN: called CC=1 SCAR=0.0
2371  
2372 static
2373 SV* parse(char *class, const char* pemcrl) {
2374 BIO *crlbio;
2375 X509_CRL *crl = NULL;
2376  
2377 crlbio = BIO_new_mem_buf((void *) pemcrl, -1);
2378 if (crlbio == NULL) {
2379 sslcroak("BIO_new_mem_buf failed");
2380 }
2381  
2382 crl = PEM_read_bio_X509_CRL(crlbio, NULL, NULL, NULL);
2383 BIO_free(crlbio);
2384 if (crl == NULL) {
2385 sslcroak("unable to parse CRL");
2386 }
2387  
2388 1 return perl_wrap("${\__PACKAGE__}", crl);
2389 }
2390  
2391 PARSE_CRL
2392  
2393 =head3 get_entries ()
2394  
2395 Get information on the revoked certificates in the CRL.
2396  
2397 In scalar context, return the number of revoked certificates. In list
2398 context, return a list of hash references with keys "revocation_date" and
2399 "serial".
2400  
2401 =cut
2402  
2403 2102 ▶sub get_entries {
Subroutine get_entries: called CC=2 SCAR=6.9
2404 2102 my ($self) = @_;
2405 2102 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 2101 1 2102
2406 # If I don't have to, I don't want to learn about
2407 # https://metacpan.org/dist/Inline-C/view/lib/Inline/C/Cookbook.pod#Multiple-Return-Values
2408 # (or what happens when one sslcroak()s in the middle of
2409 # such a construct):
2410 2101 my ($arrayref) = $self->_get_entries_arrayref();
2411 2101 return @$arrayref;
2412 } else {
2413 1 return $self->_get_entries_arrayref();
2414 }
2415 }
2416  
2417 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"ENTRIES";
Subroutine BEGIN: called CC=1 SCAR=0.0
2418  
2419 static
2420 SV* _get_entries_arrayref(SV* sv_self) {
2421 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2422  
2423 U8 gimme = GIMME_V;
2424 if (gimme == G_VOID) { return NULL; }
2425  
2426 STACK_OF(X509_REVOKED) *rev = X509_CRL_get_REVOKED(self);
2427 if (! rev) {
2428 sslcroak("X509_CRL_get_REVOKED failed");
2429 }
2430  
2431 int revnum = sk_X509_REVOKED_num(rev);
2432 int extnum;
2433 if (gimme == G_SCALAR) {
2434 return newSViv(revnum);
2435 }
2436  
2437 AV* ret = newAV();
2438  
2439 const char* revocation_date_label = "revocation_date";
2440 const char* serial_label = "serial";
2441 const char* revexts_label = "exts";
2442 char* failmsg;
2443  
2444 int i, j;
2445 for(i = 0; i < revnum; i++) {
2446 HV* hash = newHV();
2447 if (! hash) {
2448 failmsg = "cannot allocate HV";
2449 goto fail;
2450 }
2451 av_push(ret, newRV_noinc((SV*)hash));
2452 // av_push has void return value => have to trust Perl
2453 // to do the right thing in out-of-memory conditions...
2454  
2455 X509_REVOKED *rev_entry = NULL;
2456 if (!(rev_entry = sk_X509_REVOKED_value(rev, i))) {
2457 failmsg = "sk_X509_REVOKED_value failed";
2458 goto fail;
2459 }
2460  
2461 /***** Extract serial for this revocation entry *****/
2462  
2463 const ASN1_INTEGER* serial = X509_REVOKED_get0_serialNumber(rev_entry);
2464 if (! serial) {
2465 failmsg = "X509_REVOKED_get0_serialNumber failed";
2466 goto fail;
2467 }
2468 ASN1_INTEGER* serial_dup = ASN1_INTEGER_dup(serial);
2469 if (! serial_dup) {
2470 failmsg = "ASN1_INTEGER_dup failed";
2471 goto fail;
2472 }
2473  
2474 // Like perl_wrap, except we deal with errors ourselves:
2475 SV* serial_sv = sv_setref_pv(newSV(0), "Crypt::OpenSSL::CA::ASN1_INTEGER", serial_dup);
2476 if (! serial_sv) {
2477 ASN1_INTEGER_free(serial_dup);
2478  
2479 failmsg = "not enough memory to allocate serial_sv";
2480 goto fail;
2481 }
2482 SvREADONLY_on(SvRV(serial_sv));
2483  
2484 if (! hv_store(hash, serial_label, strlen(serial_label), serial_sv, 0)) {
2485 failmsg = "not enough memory to store serial in hash ref";
2486 goto fail;
2487 }
2488  
2489 /***** Extract revocation date for this revocation entry *****/
2490  
2491 const ASN1_TIME* revocation_date = X509_REVOKED_get0_revocationDate(rev_entry);
2492 if (! revocation_date) {
2493 failmsg = "cannot extract revocation date";
2494 goto fail;
2495 }
2496  
2497 ASN1_TIME* revocation_date_dup =
2498 ASN1_dup_of(ASN1_TIME, i2d_ASN1_TIME, d2i_ASN1_TIME, revocation_date);
2499 if (! revocation_date_dup) {
2500 failmsg = "cannot ASN1_dup_of() the revocation date";
2501 goto fail;
2502 }
2503  
2504 SV* revocation_date_sv = sv_setref_pv(newSV(0), "Crypt::OpenSSL::CA::ASN1_INTEGER", revocation_date_dup);
2505 if (! revocation_date_sv) {
2506 ASN1_TIME_free(revocation_date_dup);
2507  
2508 failmsg = "Not enough memory to allocate revocation_date_sv";
2509 goto fail;
2510 }
2511 SvREADONLY_on(SvRV(revocation_date_sv));
2512  
2513 if (! hv_store(hash, revocation_date_label, strlen(revocation_date_label),
2514 revocation_date_sv, 0)) {
2515 ASN1_TIME_free(revocation_date_dup);
2516  
2517 failmsg = "not enough memory to store revocation date in hash ref";
2518 goto fail;
2519 }
2520  
2521 /***** Extract CRL extensions for this revocation entry *****/
2522  
2523 AV* exts_av = newAV();
2524 if (! hv_store(hash, revexts_label, strlen(revexts_label),
2525 newRV_noinc((SV*)exts_av), 0)) {
2526 failmsg = "not enough memory to store revocation extension arrayref in hash ref";
2527 goto fail;
2528 }
2529  
2530 extnum = X509_REVOKED_get_ext_count(rev_entry);
2531 for(j = 0; j < extnum; j++) {
2532 const X509_EXTENSION* revext = X509_REVOKED_get_ext(rev_entry, j);
2533 if (! revext) {
2534 failmsg = "cannot get revocation extension (X509_REVOKED_get_ext)";
2535 goto fail_in_revext;
2536 }
2537  
2538 X509_EXTENSION* revext_dup = X509_EXTENSION_dup(
2539 (X509_EXTENSION *)revext); // const-ness SNAFU here it seems?
2540 if (! revext_dup) {
2541 failmsg = "cannot X509_EXTENSION_dup";
2542 goto fail_in_revext;
2543 }
2544  
2545 SV* revext_sv = sv_setref_pv(newSV(0), "Crypt::OpenSSL::CA::X509V3_EXT",
2546 revext_dup);
2547 if (! revext_sv) {
2548 failmsg = "not enough memory to allocate revext_sv";
2549 X509_EXTENSION_free(revext_dup);
2550 goto fail_in_revext;
2551 }
2552 SvREADONLY_on(SvRV(revext_sv));
2553  
2554 av_push(exts_av, revext_sv); // See note near the other av_push(), above
2555 } // End of loop over revexts
2556 } // End of loop over X509_REVOKED's
2557 return newRV_noinc((SV*)ret);
2558  
2559 // In case of failure, let the Perl GC deal with all the garbage
2560 // we may be leaving behind!
2561 fail:
2562 sslcroak("CRL entry %d of %d: %s", i + 1, revnum, failmsg);
2563 fail_in_revext:
2564 sslcroak("CRL entry %d of %d, extension %d of %d: %s", i + 1, revnum, j + 1, extnum, failmsg);
2565 return NULL; // Not reached
2566 }
2567 ENTRIES
2568  
2569 =head2 is_crlv2 ()
2570  
2571 Returns true iff this CRL object was set to CRLv2 at L</new> time.
2572  
2573 =cut
2574  
2575 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"IS_CRLV2";
Subroutine BEGIN: called CC=1 SCAR=0.0
2576 static
2577 int is_crlv2(SV* sv_self) {
2578 return X509_CRL_get_version
2579 1 (perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self));
2580 }
2581  
2582 IS_CRLV2
2583  
2584 =head2 get_issuer_DN ()
2585  
2586 =head2 set_issuer_DN ($dn_object)
2587  
2588 Gets / sets the CRL's issuer name as / from an
2589 L</Crypt::OpenSSL::CA::X509_NAME> object.
2590  
2591 =cut
2592  
2593 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_ISSUER_DN";
Subroutine BEGIN: called CC=1 SCAR=0.0
2594  
2595 static
2596 SV* get_issuer_DN(SV* sv_self) {
2597 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2598  
2599 X509_NAME *issuer = X509_CRL_get_issuer(self);
2600 if (! issuer) {
2601 sslcroak("X509_CRL_get_issuer failed");
2602 }
2603  
2604 issuer = X509_NAME_dup(issuer);
2605 if (! issuer) { croak("Not enough memory for get_issuer_DN"); }
2606  
2607 return perl_wrap("Crypt::OpenSSL::CA::X509_NAME", issuer);
2608 }
2609 GET_ISSUER_DN
2610  
2611 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"SET_ISSUER_DN";
Subroutine BEGIN: called CC=1 SCAR=0.0
2612  
2613 static
2614 void set_issuer_DN(SV* sv_self, SV* sv_dn) {
2615 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2616 X509_NAME* dn = perl_unwrap("Crypt::OpenSSL::CA::X509_NAME",
2617 X509_NAME *, sv_dn);
2618 if (! X509_CRL_set_issuer_name(self, dn)) {
2619 sslcroak("X509_CRL_set_issuer_name failed");
2620 }
2621 }
2622 SET_ISSUER_DN
2623  
2624 =head2 get_lastUpdate ()
2625  
2626 =head2 get_nextUpdate ()
2627  
2628 Gets the validity period of the CRL. Returns an instance of
2629 L</Crypt::OpenSSL::CA::ASN1_TIME>.
2630  
2631 =cut
2632  
2633 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"GET_LASTUPDATE_NEXTUPDATE";
Subroutine BEGIN: called CC=1 SCAR=0.0
2634  
2635 static SV* _ASN1_TIME_perlify(const ASN1_TIME* time) {
2636 ASN1_TIME* time_dup =
2637 ASN1_dup_of(ASN1_TIME, i2d_ASN1_TIME, d2i_ASN1_TIME, time);
2638 if (! time_dup) {
2639 sslcroak("Cannot ASN1_dup_of(time)");
2640 }
2641  
2642 return perl_wrap("Crypt::OpenSSL::CA::ASN1_TIME", time_dup);
2643 }
2644  
2645 static
2646 SV* get_lastUpdate(SV* sv_self) {
2647 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2648  
2649 const ASN1_TIME* lastUpdate = X509_CRL_get0_lastUpdate(self);
2650 if (! lastUpdate) {
2651 sslcroak("X509_CRL_get0_lastUpdate() failed");
2652 }
2653  
2654 return _ASN1_TIME_perlify(lastUpdate);
2655 }
2656  
2657 static
2658 SV* get_nextUpdate(SV* sv_self) {
2659 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2660  
2661 const ASN1_TIME* nextUpdate = X509_CRL_get0_nextUpdate(self);
2662 if (! nextUpdate) {
2663 sslcroak("X509_CRL_get0_nextUpdate() failed");
2664 }
2665  
2666 return _ASN1_TIME_perlify(nextUpdate);
2667 }
2668 GET_LASTUPDATE_NEXTUPDATE
2669  
2670 =head2 set_lastUpdate ($lastUpdate)
2671  
2672 =head2 set_nextUpdate ($nextUpdate)
2673  
2674 Sets the validity period of the CRL. The parameter must be an instance of
2675 L</Crypt::OpenSSL::CA::ASN1_TIME> (or something that can be
2676 C<< ->parse() >>d into one).
2677  
2678 =cut
2679  
2680 20002 ▶sub set_lastUpdate {
Subroutine set_lastUpdate: called CC=1 SCAR=0.0
2681 20002 my ($self, $lastUpdate) = @_;
2682 20002 $self->_set_lastUpdate(Crypt::OpenSSL::CA::ASN1_TIME->parse($lastUpdate));
2683 }
2684  
2685 20002 ▶sub set_nextUpdate {
Subroutine set_nextUpdate: called CC=1 SCAR=0.0
2686 20002 my ($self, $nextUpdate) = @_;
2687 20002 $self->_set_nextUpdate(Crypt::OpenSSL::CA::ASN1_TIME->parse($nextUpdate));
2688 }
2689  
2690 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"SET_UPDATES";
Subroutine BEGIN: called CC=1 SCAR=0.0
2691  
2692 static
2693 void _set_lastUpdate(SV* sv_self, SV* sv_time) {
2694 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2695 ASN1_TIME* time = perl_unwrap("Crypt::OpenSSL::CA::ASN1_TIME", ASN1_TIME *, sv_time);
2696 X509_CRL_set_lastUpdate(self, time);
2697 }
2698  
2699 static
2700 void _set_nextUpdate(SV* sv_self, SV* sv_time) {
2701 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2702 ASN1_TIME* time = perl_unwrap("Crypt::OpenSSL::CA::ASN1_TIME", ASN1_TIME *, sv_time);
2703 X509_CRL_set_nextUpdate(self, time);
2704 }
2705  
2706 SET_UPDATES
2707  
2708 =head2 set_extension ($extname, $value, %options, %more_openssl_config)
2709  
2710 =head2 add_extension ($extname, $value, %options, %more_openssl_config)
2711  
2712 =head2 remove_extension ($extname)
2713  
2714 Manage CRL extensions as per RFC3280 section 5.2. These methods work
2715 like their respective counterparts in L<Crypt::OpenSSL::CA::X509>.
2716 Recognized CRL extensions are:
2717  
2718 =over
2719  
2720 =item I<authorityKeyIdentifier>
2721  
2722 Works the same as in L</Crypt::OpenSSL::CA::X509>. Implements RFC3280
2723 section 5.2.1.
2724  
2725 =item I<crlNumber>
2726  
2727 An extension (described in RFC3280 section 5.2.3, and made mandatory
2728 by section 5.1.2.1) to identify the CRL by a monotonically increasing
2729 sequence number. The value of this extension must be a serial number,
2730 with the same syntax as the first argument to L</set_serial>.
2731  
2732 =item I<freshestCRL>
2733  
2734 An optional RFC3280 extension that indicates support for delta-CRLs,
2735 as described by RFC3280 section 5.2.6. The expected $value and
2736 %more_openssl_config are the same as for C<cRLDistributionPoints> in
2737 an extension for certificates (see L</Crypt::OpenSSL::CA::X509>).
2738  
2739 =item I<deltaCRLIndicator>
2740  
2741 An optional RFC3280 extension that indicates that this CRL is as a
2742 delta-CRL, pursuant to RFC3280 section 5.2.4. For this extension,
2743 $value must be a serial number, with the same syntax as the
2744 first argument to L</set_serial>.
2745  
2746 =back
2747  
2748 Note that CRL extensions are B<not> implemented by OpenSSL as of
2749 version 0.9.8c, but rather by C glue code directly in
2750 I<Crypt::OpenSSL::CA>.
2751  
2752 =cut
2753  
2754 1 ▶use vars qw(%ext2oid %oid2ext);
Subroutine BEGIN: called CC=1 SCAR=0.0
2755 # RFC3280 §§ 4.2.1 and 5.2; http://www.alvestrand.no/objectid/2.5.29.html
2756 1 %ext2oid = (crlNumber => "2.5.29.20",
2757 deltaCRLIndicator => "2.5.29.27",
2758 authorityKeyIdentifier => "2.5.29.35",
2759 freshestCRL => "2.5.29.46",
2760 );
2761 1 %oid2ext = reverse %ext2oid;
2762  
2763 60005 ▶sub set_extension {
Subroutine set_extension: called CC=2 SCAR=6.9
2764 60005 my ($self, $extname, @stuff) = @_;
2765 60005 my $real_extname = $extname;
2766 60005 ▶ $real_extname = "authorityKeyIdentifier" if
Branch: 1 branch
BranchTrueFalseTotal
if $extname =~ /^authorityKeyIdentifier/i 20003 40002 60005
2767 ($extname =~ m/^authorityKeyIdentifier/i); # OBSOLETE support
2768 # for authorityKeyIdentifier_keyid as was present in 0.04
2769 60005 $self->remove_extension($real_extname);
2770 60005 $self->add_extension($extname, @stuff);
2771 }
2772  
2773 60005 ▶sub add_extension {
Subroutine add_extension: called CC=17 SCAR=30.7
2774 60005 ▶ die("incorrect number of arguments to add_extension()")
Branch: 1 branch
BranchTrueFalseTotal
unless @_ % 2 0 60005 60005
2775 unless (@_ % 2);
2776 60005 my ($self, $extname, $value, %options) = @_;
2777 60005 ▶ croak("add_extension: name is mandatory") unless
Branch: 1 branch
BranchTrueFalseTotal
unless $extname and length $extname 0 60005 60005
Condition33%1/3
$extname and length $extname
!ll&&!rl&&r
0060005
MC/DC0%0/2
$extname and length $extname
$extname length $extname
Truth table33%1/3
A and B
A= $extnameB= length $extname
ABresult
0X0
100
111
2778 ($extname && length($extname));
2779 60005 ▶ croak("add_extension: value is mandatory") unless
Branch: 1 branch
BranchTrueFalseTotal
unless $value and length $value 0 60005 60005
Condition33%1/3
$value and length $value
!ll&&!rl&&r
0060005
MC/DC0%0/2
$value and length $value
$value length $value
Truth table33%1/3
A and B
A= $valueB= length $value
ABresult
0X0
100
111
2780 ($value && length($value));
2781  
2782 60005 my $critical = "";
2783 60005 ▶ $critical = "critical," if ($value =~ s/^critical(,|$)//i);
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ s/^critical(,|$)//i 0 60005 60005
2784  
2785 60005 foreach my $k (keys %options) {
2786 40002 ▶ next unless $k =~ m/^-/;
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /^-/ 0 40002 40002
2787 40002 my $v = delete $options{$k};
2788  
2789 40002 ▶ if ($k eq "-critical") {
Branch: 1 branch
BranchTrueFalseTotal
if ($k eq "-critical") 40002 0 40002
2790 40002 ▶ if ($v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v) { } 20001 20001 40002
2791 20001 $critical = "critical,";
2792 } else {
2793 20001 ▶ croak("add_extension: -critical => 0 conflicts" .
Branch: 1 branch
BranchTrueFalseTotal
if $critical 0 20001 20001
2794 " with ``$_[2]''") if ($critical);
2795 }
2796 }
2797 # Other named options may be added later.
2798 }
2799  
2800 # OBSOLETE, for compatibility only:
2801 60005 ▶ if ($extname eq "authorityKeyIdentifier_keyid") {
Branch: 1 branch
BranchTrueFalseTotal
if ($extname eq "authorityKeyIdentifier_keyid") 1 60004 60005
2802 1 $extname = "authorityKeyIdentifier";
2803 1 $value = { keyid => $value };
2804 }
2805  
2806 60005 my $ext;
2807 60005 ▶ if ($extname eq "authorityKeyIdentifier") {
Branch: 3 branches
BranchTrueFalseTotal
if ($extname eq 'authorityKeyIdentifier') { } 20003 40002 60005
elsif ($extname eq 'freshestCRL') { } 20001 20001 40002
elsif (grep {$extname eq $_;} 'crlNumber', 'deltaCRLIndicator') { } 20001 0 20001
2808 20003 $ext = Crypt::OpenSSL::CA::X509V3_EXT->
2809 new_authorityKeyIdentifier(critical => $critical, %$value);
2810 } elsif ($extname eq "freshestCRL") {
2811 20001 $ext = Crypt::OpenSSL::CA::X509V3_EXT->
2812 new_freshestCRL("$critical$value",
2813 Crypt::OpenSSL::CA::CONF->new(\%options));
2814 40002 } elsif (grep { $extname eq $_ } (qw(crlNumber deltaCRLIndicator))) {
2815 $ext = Crypt::OpenSSL::CA::X509V3_EXT->
2816 new_CRL_serial(($critical ? 1 : 0),
2817 20001 ▶ $ext2oid{$extname}, $value);
Branch: 1 branch
BranchTrueFalseTotal
$critical ? : 20001 0 20001
2818 } else {
2819 0 croak("Unknown CRL extension $extname");
2820 }
2821 60005 $self->_do_add_extension($ext);
2822 }
2823  
2824 60005 ▶sub remove_extension {
Subroutine remove_extension: called CC=3 SCAR=11.3
2825 60005 my ($self, $extname) = @_;
2826 60005 my $extoid = $extname;
2827 60005 ▶ $extoid = $ext2oid{$extoid} if exists $ext2oid{$extoid};
Branch: 1 branch
BranchTrueFalseTotal
if exists $Crypt::OpenSSL::CA::X509_CRL::ext2oid{$extoid} 60005 0 60005
2828 croak("Unknown CRL extension: $extname") unless
2829 60005 ▶ (exists $oid2ext{$extoid});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $Crypt::OpenSSL::CA::X509_CRL::oid2ext{$extoid} 0 60005 60005
2830 60005 $self->_remove_extension_by_oid($extoid);
2831 }
2832  
2833 =head2 add_entry ($serial, $revocation_date, %named_options)
2834  
2835 Adds an entry to the CRL. $serial is an instance of
2836 L</Crypt::OpenSSL::CA::ASN1_INTEGER> (or something that can be
2837 C<< ->parse() >>d into one). $revocation_date is an instance of
2838 L</Crypt::OpenSSL::CA::ASN1_TIME> (or something that can be
2839 C<< ->parse() >>d into one).
2840  
2841 The following named options provide access to CRLv2 extensions as
2842 defined in RFC3280 section 5.3:
2843  
2844 =over
2845  
2846 =item I<< -reason => $reason >>
2847  
2848 Sets the revocation reason to $reason, a plain string. Available
2849 reasons are C<unspecified> (which is B<not> the same thing as not
2850 setting a revocation reason at all), C<keyCompromise>,
2851 C<CACompromise>, C<affiliationChanged>, C<superseded>,
2852 C<cessationOfOperation>, C<certificateHold> and C<removeFromCRL>.
2853  
2854 =item I<< -compromise_time => $time >>
2855  
2856 The time at which the compromise is suspected to have taken place,
2857 which may be earlier than the $revocation_date. The syntax for $time
2858 is the same as that for $revocation_date. Note that this CRL extension
2859 only makes sense if I<< -reason >> is either I<keyCompromise> or
2860 I<CACompromise>.
2861  
2862 =item I<< -hold_instruction => $oid >>
2863  
2864 =item I<< -hold_instruction => $string >>
2865  
2866 Sets the hold instruction token to $oid (which is a string containing
2867 a dot-separated sequence of decimal integers), or $string (one of the
2868 predefined string constants C<none>, C<callIssuer>, C<reject> and
2869 C<pickupToken>, case-insensitive). This option only makes sense if
2870 the revocation reason is C<certificateHold>. See also
2871 L</Crypt::OpenSSL::CA::X509_CRL::holdInstructionNone>,
2872 L</Crypt::OpenSSL::CA::X509_CRL::holdInstructionCallIssuer>,
2873 L</Crypt::OpenSSL::CA::X509_CRL::holdInstructionReject> and
2874 L</Crypt::OpenSSL::CA::X509_CRL::holdInstructionPickupToken>.
2875  
2876 =back
2877  
2878 All the above options should be specified at most once. If they are
2879 specified several times, only the last occurence in the parameter list
2880 will be taken into account.
2881  
2882 The criticality is set according to the recommendations of RFC3280
2883 section 5.3; practically speaking, all certificate entry extensions
2884 are noncritical, given that 5.3.4-style C<certificateIssuer> is
2885 B<UNIMPLEMENTED>. Support for critical certificate entry extensions
2886 may be added in a future release of I<Crypt::OpenSSL::CA>.
2887  
2888 =cut
2889  
2890 8006 ▶sub add_entry {
Subroutine add_entry: called CC=9 SCAR=24.4
2891 8006 ▶ croak("Wrong number of arguments to add_entry") unless @_ % 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ % 2 0 8006 8006
2892 8006 my ($self, $serial, $revocationdate, %named_options) = @_;
2893  
2894 8006 my $reason = do {
2895 # RFC3280 section 5.3.1:
2896 8006 my @rfc3280_revocation_reasons =
2897 qw(unspecified keyCompromise cACompromise
2898 affiliationChanged superseded cessationOfOperation
2899 certificateHold __UNUSED__ removeFromCRL privilegeWithdrawn
2900 aACompromise);
2901 8006 my %reason = map { ( $rfc3280_revocation_reasons[$_] => $_ ) }
2902 (0..$#rfc3280_revocation_reasons);
2903 8006 ▶ $reason{$named_options{-reason} || ""};
Condition100%2/2
$named_options{'-reason'} || ''
l!l
40034003
MC/DC100%1/1
$named_options{'-reason'} || ''
$named_options{'-reason'}
Truth table100%2/2
A
A= $named_options{'-reason'}
Aresult
11
00
2904 };
2905 8006 my $holdinstr = do {
2906 8006 local $_ = $named_options{-hold_instruction};
2907 8006 ▶ if (defined($_)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_) 2001 6005 8006
2908 0 ▶ if (m/none/i) { $_ = holdInstructionNone(); }
Branch: 5 branches
BranchTrueFalseTotal
if (/none/i) { } 0 2001 2001
elsif (/callissuer/i) { } 0 2001 2001
elsif (/reject/i) { } 0 2001 2001
elsif (/pickuptoken/i) { } 2001 0 2001
elsif (/^\d+(\.\d+)*$/) { } 0 0 0
2909 0 elsif (m/callissuer/i) { $_ = holdInstructionCallIssuer(); }
2910 0 elsif (m/reject/i) { $_ = holdInstructionReject(); }
2911 2001 elsif (m/pickuptoken/i) { $_ = holdInstructionPickupToken(); }
2912 elsif (m/^\d+(\.\d+)*$/) { } # No transformation
2913 0 else { croak("Unknown hold instruction $_"); }
2914 }
2915 8006 $_;
2916 };
2917  
2918 8006 my $comptime = $named_options{-compromise_time};
2919  
2920 8006 return $self->_do_add_entry
2921 (Crypt::OpenSSL::CA::ASN1_INTEGER->parse($serial),
2922 Crypt::OpenSSL::CA::ASN1_TIME->parse($revocationdate),
2923 $reason, $holdinstr, $comptime);
2924 }
2925  
2926 =head2 sign ($privkey, $digestname)
2927  
2928 Signs the CRL. C<$privkey> is an instance of
2929 L</Crypt::OpenSSL::CA::PrivateKey>; C<$digestname> is the name of one
2930 of cryptographic digests supported by OpenSSL, e.g. "sha1" or "sha256"
2931 (notice that using "md5" is B<strongly discouraged> due to security
2932 considerations; see
2933 L<http://www.win.tue.nl/~bdeweger/CollidingCertificates/>). Returns
2934 the PEM-encoded CRL as a string.
2935  
2936 =cut
2937  
2938 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"SIGN";
Subroutine BEGIN: called CC=1 SCAR=0.0
2939 static
2940 SV* sign(SV* sv_self, SV* sv_key, char* digestname) {
2941 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2942 EVP_PKEY* key = perl_unwrap("Crypt::OpenSSL::CA::PrivateKey",
2943 EVP_PKEY *, sv_key);
2944 const EVP_MD* digest;
2945 BIO* mem;
2946  
2947 if (! (digest = EVP_get_digestbyname(digestname))) {
2948 sslcroak("Unknown digest name: %s", digestname);
2949 }
2950  
2951 if (! X509_CRL_sort(self)) { sslcroak("X509_CRL_sort failed"); }
2952  
2953 if (! X509_CRL_sign(self, key, digest)) {
2954 sslcroak("X509_CRL_sign failed");
2955 }
2956  
2957 if (! (mem = BIO_new(BIO_s_mem()))) {
2958 croak("Cannot allocate BIO");
2959 }
2960 if (! (PEM_write_bio_X509_CRL(mem, self) &&
2961 (BIO_write(mem, "\\0", 1) > 0)) ) {
2962 BIO_free(mem);
2963 croak("Serializing certificate failed");
2964 }
2965 return BIO_mem_to_SV(mem);
2966 }
2967 SIGN
2968  
2969 =head2 supported_digests()
2970  
2971 This is a class method (invoking it as an instance method also works
2972 though). Returns the list of all supported digest names for the
2973 second argument of L</sign>. The contents of this list depends on the
2974 OpenSSL version and the details of how it was compiled.
2975  
2976 =cut
2977  
2978 0 ▶sub supported_digests { Crypt::OpenSSL::CA::X509->supported_digests }
Subroutine supported_digests: not called CC=1 SCAR=6.9
2979  
2980 =head2 dump ()
2981  
2982 Returns a textual representation of all the fields inside the
2983 (unfinished) CRL. This is done using OpenSSL's
2984 C<X509_CRL_print()>.
2985  
2986 =cut
2987  
2988 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"DUMP";
Subroutine BEGIN: called CC=1 SCAR=0.0
2989 static
2990 SV* dump(SV* sv_self) {
2991 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
2992 BIO* mem = BIO_new(BIO_s_mem());
2993  
2994 if (! mem) {
2995 croak("Cannot allocate BIO");
2996 }
2997  
2998 if (! (X509_CRL_print(mem, self) &&
2999 (BIO_write(mem, "\\0", 1) > 0)) ) {
3000 sslcroak("X509_CRL_print failed");
3001 }
3002  
3003 return BIO_mem_to_SV(mem);
3004 }
3005 DUMP
3006  
3007 =head2 Crypt::OpenSSL::CA::X509_CRL::holdInstructionNone
3008  
3009 =head2 Crypt::OpenSSL::CA::X509_CRL::holdInstructionCallIssuer
3010  
3011 =head2 Crypt::OpenSSL::CA::X509_CRL::holdInstructionReject
3012  
3013 =head2 Crypt::OpenSSL::CA::X509_CRL::holdInstructionPickupToken
3014  
3015 OID constants for the respective hold instructions (see the
3016 I<-hold_instruction> named option in L</add_entry>). All these
3017 functions return a string containing a dot-separated sequence of
3018 decimal integers.
3019  
3020 =cut
3021  
3022 0 ▶sub holdInstructionNone { "1.2.840.10040.2.1" }
Subroutine holdInstructionNone: not called CC=1 SCAR=6.9
3023 0 ▶sub holdInstructionCallIssuer { "1.2.840.10040.2.2" }
Subroutine holdInstructionCallIssuer: not called CC=1 SCAR=6.9
3024 0 ▶sub holdInstructionReject { "1.2.840.10040.2.3" }
Subroutine holdInstructionReject: not called CC=1 SCAR=6.9
3025 2001 ▶sub holdInstructionPickupToken { "1.2.840.10040.2.4" }
Subroutine holdInstructionPickupToken: called CC=1 SCAR=0.0
3026  
3027 =begin internals
3028  
3029 =head2 _new ($x509_crl_version)
3030  
3031 Does the actual job of L</new>. $x509_crl_version must be an integer,
3032 0 for CRLv1 and 1 for CRLv2.
3033  
3034 =cut
3035  
3036 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"_NEW";
Subroutine BEGIN: called CC=1 SCAR=0.0
3037 static
3038 SV* _new(char *class, int x509_crl_version) {
3039 X509_CRL* retval = X509_CRL_new();
3040  
3041 if (! retval) {
3042 croak("X509_CRL_new failed");
3043 }
3044 if (! X509_CRL_set_version(retval, x509_crl_version)) {
3045 X509_CRL_free(retval);
3046 sslcroak("X509_CRL_set_version failed");
3047 }
3048  
3049 1 return perl_wrap("${\__PACKAGE__}", retval);
3050 }
3051 _NEW
3052  
3053 =head2 _do_add_extension ($extension)
3054  
3055 Does the actual job of L</add_extension>, sans all the syntactic
3056 sugar. $extension is an instance of
3057 L</Crypt::OpenSSL::CA::X509V3_EXT>.
3058  
3059 =cut
3060  
3061 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"_DO_ADD_EXTENSION";
Subroutine BEGIN: called CC=1 SCAR=0.0
3062 static
3063 void _do_add_extension(SV* sv_self, SV* sv_extension) {
3064 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
3065 if (! X509_CRL_get_version(self)) {
3066 croak("Cannot add extensions to a CRLv1");
3067 }
3068 X509_EXTENSION *ex = perl_unwrap("Crypt::OpenSSL::CA::X509V3_EXT",
3069 X509_EXTENSION *, sv_extension);
3070  
3071 if (! X509_CRL_add_ext(self, ex, -1)) {
3072 sslcroak("X509_CRL_add_ext failed");
3073 }
3074 }
3075 _DO_ADD_EXTENSION
3076  
3077 =head2 _remove_extension_by_oid ($oid_text)
3078  
3079 Like L</remove_extension>, except that the parameter is an ASN.1
3080 Object Identifier in dotted-decimal form (e.g. "2.5.29.20" instead of
3081 C<cRLNumber>).
3082  
3083 =cut
3084  
3085 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"_REMOVE_EXTENSION_BY_OID";
Subroutine BEGIN: called CC=1 SCAR=0.0
3086 static
3087 void _remove_extension_by_oid(SV* sv_self, char* oidtxt) {
3088 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
3089 X509_EXTENSION* deleted;
3090 ASN1_OBJECT* obj;
3091 int i;
3092  
3093 if (! (obj = OBJ_txt2obj(oidtxt, 1))) {
3094 sslcroak("OBJ_txt2obj failed on %s", oidtxt);
3095 }
3096  
3097 while( (i = X509_CRL_get_ext_by_OBJ(self, obj, -1)) >= 0) {
3098 if (! (deleted = X509_CRL_delete_ext(self, i)) ) {
3099 ASN1_OBJECT_free(obj);
3100 sslcroak("X509_delete_ext failed");
3101 }
3102 X509_EXTENSION_free(deleted);
3103 }
3104 ASN1_OBJECT_free(obj);
3105 }
3106 _REMOVE_EXTENSION_BY_OID
3107  
3108 =head2 _do_add_entry ($serial, $date, $reason_code, $hold_instr,
3109 $compromise_time)
3110  
3111 Does the actual job of L</add_entry>, sans all the syntactic sugar.
3112 All arguments are strings, except $reason_code which is an integer
3113 according to the enumeration set forth in RFC3280 section 5.3.1.
3114 $reason_code, $hold_instr and $compromise_time can be omitted (that
3115 is, passed as undef).
3116  
3117 This already ugly API will of course have to "evolve" as we implement
3118 more CRL entry extensions.
3119  
3120 =end internals
3121  
3122 =cut
3123  
3124 1 ▶use Crypt::OpenSSL::CA::Inline::C <<"_DO_ADD_ENTRY";
Subroutine BEGIN: called CC=1 SCAR=0.0
3125 static
3126 void _do_add_entry(SV* sv_self, SV* sv_serial, SV* sv_date,
3127 SV* sv_reason, SV* sv_holdinstr,
3128 SV* sv_compromisetime) {
3129 1 X509_CRL* self = perl_unwrap("${\__PACKAGE__}", X509_CRL *, sv_self);
3130 ASN1_INTEGER* serial = perl_unwrap("Crypt::OpenSSL::CA::ASN1_INTEGER",
3131 ASN1_INTEGER *, sv_serial);
3132 ASN1_TIME* revocationtime = perl_unwrap("Crypt::OpenSSL::CA::ASN1_TIME", ASN1_TIME *, sv_date);
3133 ASN1_GENERALIZEDTIME* compromisetime;
3134 ASN1_OBJECT* holdinstr;
3135 ASN1_ENUMERATED* reason;
3136 X509_REVOKED* entry;
3137 int status;
3138 char* plainerr = NULL; char* sslerr = NULL;
3139  
3140 if (! (entry = X509_REVOKED_new())) {
3141 croak("X509_REVOKED_new failed");
3142 }
3143  
3144 status = X509_REVOKED_set_revocationDate(entry, revocationtime);
3145 if (! status) {
3146 sslerr = "X509_REVOKED_set_revocationDate failed";
3147 goto error;
3148 }
3149  
3150 status = X509_REVOKED_set_serialNumber(entry, serial);
3151 if (! status) {
3152 sslerr = "X509_REVOKED_set_serialNumber failed";
3153 goto error;
3154 }
3155  
3156 /* CRLv2 entry extensions */
3157 if ( (! is_crlv2(sv_self)) &&
3158 (SvOK(sv_reason) || SvOK(sv_holdinstr) ||
3159 SvOK(sv_compromisetime))) {
3160 plainerr = "Cannot add entry extensions to CRLv1 CRL";
3161 goto error;
3162 }
3163 if (SvOK(sv_reason)) {
3164 if (! (reason = ASN1_ENUMERATED_new())) {
3165 plainerr = "Not enough memory for ASN1_ENUMERATED_new";
3166 goto error;
3167 }
3168 if (! ASN1_ENUMERATED_set(reason, SvIV(sv_reason))) {
3169 ASN1_ENUMERATED_free(reason);
3170 sslerr = "ASN1_ENUMERATED_set failed";
3171 goto error;
3172 }
3173 status = X509_REVOKED_add1_ext_i2d
3174 (entry, NID_crl_reason, reason, 0, 0);
3175 ASN1_ENUMERATED_free(reason);
3176 if (! status) {
3177 sslerr = "X509_REVOKED_add1_ext_i2d failed";
3178 goto error;
3179 }
3180 }
3181 if (SvOK(sv_holdinstr)) {
3182 if (! (holdinstr = OBJ_txt2obj(char0_value(sv_holdinstr), 1))) {
3183 sslerr = "OBJ_txt2obj failed";
3184 goto error;
3185 }
3186 status = X509_REVOKED_add1_ext_i2d
3187 (entry, NID_hold_instruction_code, holdinstr, 0, 0);
3188 ASN1_OBJECT_free(holdinstr);
3189 if (! status) {
3190 sslerr = "X509_REVOKED_add1_ext_i2d failed";
3191 goto error;
3192 }
3193 }
3194 if (SvOK(sv_compromisetime)) {
3195 if (! (compromisetime = ASN1_GENERALIZEDTIME_new())) {
3196 plainerr = "Not enough memory for ASN1_GENERALIZEDTIME_new";
3197 goto error;
3198 }
3199 if (! (ASN1_GENERALIZEDTIME_set_string
3200 (compromisetime, char0_value(sv_compromisetime)))) {
3201 ASN1_GENERALIZEDTIME_free(compromisetime);
3202 sslerr = "ASN1_GENERALIZEDTIME_set_string failed";
3203 goto error;
3204 }
3205 status = X509_REVOKED_add1_ext_i2d
3206 (entry, NID_invalidity_date, compromisetime, 0, 0);
3207 ASN1_GENERALIZEDTIME_free(compromisetime);
3208 if (! status) {
3209 sslerr = "X509_REVOKED_add1_ext_i2d failed";
3210 goto error;
3211 }
3212 }
3213  
3214 /* All set */
3215  
3216 if (! X509_CRL_add0_revoked(self, entry)) {
3217 sslcroak("X509_CRL_add0_revoked failed");
3218 }
3219 return;
3220  
3221 error:
3222 X509_REVOKED_free(entry);
3223 if (plainerr) { croak("%s", plainerr); }
3224 if (sslerr) { sslcroak("%s", sslerr); }
3225 sslcroak("Unknown error in _do_add_entry");
3226 }
3227 _DO_ADD_ENTRY
3228  
3229 =head1 TODO
3230  
3231 Add centralized key generation.
3232  
3233 Add some comfort features such as the ability to transfer
3234 certification information automatically from the CA certificate to the
3235 issued certificates and CRLs, RFC3280 compliance checks (especially as
3236 regards the criticality of X509v3 certificate extensions) and so on.
3237  
3238 OpenSSL engines are only a few hours of work away, but aren't done
3239 yet.
3240  
3241 Key formats other than RSA are not (fully) supported, and at any rate,
3242 not unit-tested.
3243  
3244 Only the subset of the CRL extensions required to support delta-CRLs
3245 is working, as documented in L<Crypt::OpenSSL::CA::X509_CRL>; RFC3280
3246 sections 5.2.2 (C<issuerAltName>), 5.2.5 (C<issuingDistributionPoint>)
3247 and 5.3.4 (C<certificateIssuer> entry extension) are B<UNIMPLEMENTED>.
3248 I am quite unlikely to implement these arcane parts of the
3249 specification myself; L</PATCHES WELCOME>.
3250  
3251 =head1 SEE ALSO
3252  
3253 L<Crypt::OpenSSL::CA::Resources>, L<Crypt::OpenSSL::CA::Inline::C>.
3254  
3255 =head1 AUTHOR
3256  
3257 Dominique QUATRAVAUX, C<< <domq at cpan.org> >>
3258  
3259 =head1 PATCHES WELCOME
3260  
3261 If you feel that a key feature is missing in I<Crypt::OpenSSL::CA>,
3262 please feel free to send me patches; I'll gladly apply them and
3263 re-release the whole module within a short time. The only thing I
3264 require is that the patch cover all three of documentation, unit tests
3265 and code; and that tests pass successfully afterwards, of course, at
3266 least on your own machine. In particular, this means that patches
3267 that only add code will be declined, no matter how desirable the new
3268 features are.
3269  
3270 =head1 BUGS
3271  
3272 Please report any bugs or feature requests to C<bug-crypt-openssl-ca at
3273 rt.cpan.org>, or through the web interface at
3274 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Crypt-OpenSSL-CA>. I
3275 will be notified, and then you'll automatically be notified of
3276 progress on your bug as I make changes.
3277  
3278 =head1 SUPPORT
3279  
3280 You can find documentation for this module with the perldoc command.
3281  
3282 perldoc Crypt::OpenSSL::CA
3283  
3284 You can also look for information at:
3285  
3286 =over
3287  
3288 =item * AnnoCPAN: Annotated CPAN documentation
3289  
3290 L<http://annocpan.org/dist/Crypt-OpenSSL-CA>
3291  
3292 =item * CPAN Ratings
3293  
3294 L<http://cpanratings.perl.org/d/Crypt-OpenSSL-CA>
3295  
3296 =item * RT: CPAN's request tracker
3297  
3298 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Crypt-OpenSSL-CA>
3299  
3300 =item * Search CPAN
3301  
3302 L<http://search.cpan.org/dist/Crypt-OpenSSL-CA>
3303  
3304 =back
3305  
3306 =head1 ACKNOWLEDGEMENTS
3307  
3308 IDEALX (L<http://www.idealx.com/>) is the company that put food on my
3309 family's table for 5 years while I was busy coding IDX-PKI. I owe
3310 them pretty much everything I know about PKIX, and a great deal of my
3311 todays' Perl-fu. However, the implementation of this module is
3312 original and does not re-use any code in IDX-PKI.
3313  
3314 =head1 COPYRIGHT & LICENSE
3315  
3316  
3317 Copyright (C) 2007 Siemens Business Services France SAS, all rights
3318 reserved.
3319  
3320 This program is free software; you can redistribute it and/or modify it
3321 under the same terms as Perl itself.
3322  
3323 =cut
3324  
3325 1 ▶use Crypt::OpenSSL::CA::Inline::C "__END__";
Subroutine BEGIN: called CC=1 SCAR=0.0
3326  
3327 1 ▶require My::Tests::Below unless caller();
Branch: 1 branch
BranchTrueFalseTotal
unless caller() 1 0 1
3328 1;
3329  
3330 __END__
« blib/lib/Crypt/OpenSSL/CA.pm ↑ Summary lib/Crypt/OpenSSL/CA/Inline/C.pm »