Add config tests for including provider config files
[openssl.git] / test / recipes / 80-test_ca.t
1 #! /usr/bin/env perl
2 # Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved.
3 #
4 # Licensed under the Apache License 2.0 (the "License").  You may not use
5 # this file except in compliance with the License.  You can obtain a copy
6 # in the file LICENSE in the source distribution or at
7 # https://www.openssl.org/source/license.html
8
9
10 use strict;
11 use warnings;
12
13 use POSIX;
14 use File::Path 2.00 qw/rmtree/;
15 use OpenSSL::Test qw/:DEFAULT cmdstr data_file srctop_file/;
16 use OpenSSL::Test::Utils;
17 use Time::Local qw/timegm/;
18
19 setup("test_ca");
20
21 $ENV{OPENSSL} = cmdstr(app(["openssl"]), display => 1);
22
23 my $cnf = srctop_file("test","ca-and-certs.cnf");
24 my $std_openssl_cnf = '"'
25     . srctop_file("apps", $^O eq "VMS" ? "openssl-vms.cnf" : "openssl.cnf")
26     . '"';
27
28 sub src_file {
29     return srctop_file("test", "certs", shift);
30 }
31
32 rmtree("demoCA", { safe => 0 });
33
34 plan tests => 20;
35
36 require_ok(srctop_file("test", "recipes", "tconversion.pl"));
37
38  SKIP: {
39      my $cakey = src_file("ca-key.pem");
40      $ENV{OPENSSL_CONFIG} = qq(-config "$cnf");
41      skip "failed creating CA structure", 4
42          if !ok(run(perlapp(["CA.pl","-newca",
43                              "-extra-req", "-key $cakey"], stdin => undef)),
44                 'creating CA structure');
45
46      my $eekey = src_file("ee-key.pem");
47      $ENV{OPENSSL_CONFIG} = qq(-config "$cnf");
48      skip "failed creating new certificate request", 3
49          if !ok(run(perlapp(["CA.pl","-newreq",
50                              '-extra-req', "-outform DER -section userreq -key $eekey"])),
51                 'creating certificate request');
52      $ENV{OPENSSL_CONFIG} = qq(-rand_serial -inform DER -config "$std_openssl_cnf");
53      skip "failed to sign certificate request", 2
54          if !is(yes(cmdstr(perlapp(["CA.pl", "-sign"]))), 0,
55                 'signing certificate request');
56
57      ok(run(perlapp(["CA.pl", "-verify", "newcert.pem"])),
58         'verifying new certificate');
59
60      skip "CT not configured, can't use -precert", 1
61          if disabled("ct");
62
63      my $eekey2 = src_file("ee-key-3072.pem");
64      $ENV{OPENSSL_CONFIG} = qq(-config "$cnf");
65      ok(run(perlapp(["CA.pl", "-precert", '-extra-req', "-section userreq -key $eekey2"], stderr => undef)),
66         'creating new pre-certificate');
67 }
68
69 SKIP: {
70     skip "SM2 is not supported by this OpenSSL build", 1
71         if disabled("sm2");
72
73     is(yes(cmdstr(app(["openssl", "ca", "-config",
74                        $cnf,
75                        "-in", src_file("sm2-csr.pem"),
76                        "-out", "sm2-test.crt",
77                        "-sigopt", "distid:1234567812345678",
78                        "-vfyopt", "distid:1234567812345678",
79                        "-md", "sm3",
80                        "-cert", src_file("sm2-root.crt"),
81                        "-keyfile", src_file("sm2-root.key")]))),
82        0,
83        "Signing SM2 certificate request");
84 }
85
86 my $v3_cert = "v3-test.crt";
87 ok(run(app(["openssl", "ca", "-batch", "-config", $cnf, "-extensions", "empty",
88             "-in", src_file("x509-check.csr"), "-out", $v3_cert])));
89 # although no explicit extensions given:
90 has_version($v3_cert, 3);
91 has_SKID($v3_cert, 1);
92 has_AKID($v3_cert, 1);
93
94 test_revoke('notimes', {
95     should_succeed => 1,
96 });
97 test_revoke('lastupdate_invalid', {
98     lastupdate     => '1234567890',
99     should_succeed => 0,
100 });
101 test_revoke('lastupdate_utctime', {
102     lastupdate     => '200901123456Z',
103     should_succeed => 1,
104 });
105 test_revoke('lastupdate_generalizedtime', {
106     lastupdate     => '20990901123456Z',
107     should_succeed => 1,
108 });
109 test_revoke('nextupdate_invalid', {
110     nextupdate     => '1234567890',
111     should_succeed => 0,
112 });
113 test_revoke('nextupdate_utctime', {
114     nextupdate     => '200901123456Z',
115     should_succeed => 1,
116 });
117 test_revoke('nextupdate_generalizedtime', {
118     nextupdate     => '20990901123456Z',
119     should_succeed => 1,
120 });
121 test_revoke('both_utctime', {
122     lastupdate     => '200901123456Z',
123     nextupdate     => '200908123456Z',
124     should_succeed => 1,
125 });
126 test_revoke('both_generalizedtime', {
127     lastupdate     => '20990901123456Z',
128     nextupdate     => '20990908123456Z',
129     should_succeed => 1,
130 });
131
132 sub test_revoke {
133     my ($filename, $opts) = @_;
134
135     subtest "Revoke certificate and generate CRL: $filename" => sub {
136         # Before Perl 5.12.0, the range of times Perl could represent was
137         # limited by the size of time_t, so Time::Local was hamstrung by the
138         # Y2038 problem
139         # Perl 5.12.0 onwards use an internal time implementation with a
140         # guaranteed >32-bit time range on all architectures, so the tests
141         # involving post-2038 times won't fail provided we're running under
142         # that version or newer
143         plan skip_all =>
144             'Perl >= 5.12.0 required to run certificate revocation tests'
145             if $] < 5.012000;
146
147         $ENV{CN2} = $filename;
148         ok(
149             run(app(['openssl',
150                      'req',
151                      '-config',  $cnf,
152                      '-new',
153                      '-key',     data_file('revoked.key'),
154                      '-out',     "$filename-req.pem",
155                      '-section', 'userreq',
156             ])),
157             'Generate CSR'
158         );
159         delete $ENV{CN2};
160
161         ok(
162             run(app(['openssl',
163                      'ca',
164                      '-batch',
165                      '-config',  $cnf,
166                      '-in',      "$filename-req.pem",
167                      '-out',     "$filename-cert.pem",
168             ])),
169             'Sign CSR'
170         );
171
172         ok(
173             run(app(['openssl',
174                      'ca',
175                      '-config', $cnf,
176                      '-revoke', "$filename-cert.pem",
177             ])),
178             'Revoke certificate'
179         );
180
181         my @gencrl_opts;
182
183         if (exists $opts->{lastupdate}) {
184             push @gencrl_opts, '-crl_lastupdate', $opts->{lastupdate};
185         }
186
187         if (exists $opts->{nextupdate}) {
188             push @gencrl_opts, '-crl_nextupdate', $opts->{nextupdate};
189         }
190
191         is(
192             run(app(['openssl',
193                      'ca',
194                      '-config', $cnf,
195                      '-gencrl',
196                      '-out',    "$filename-crl.pem",
197                      '-crlsec', '60',
198                      @gencrl_opts,
199             ])),
200             $opts->{should_succeed},
201             'Generate CRL'
202         );
203         my $crl_gentime = time;
204
205         # The following tests only need to run if the CRL was supposed to be
206         # generated:
207         return unless $opts->{should_succeed};
208
209         my $crl_lastupdate = crl_field("$filename-crl.pem", 'lastUpdate');
210         if (exists $opts->{lastupdate}) {
211             is(
212                 $crl_lastupdate,
213                 rfc5280_time($opts->{lastupdate}),
214                 'CRL lastUpdate field has expected value'
215             );
216         } else {
217             diag("CRL lastUpdate:   $crl_lastupdate");
218             diag("openssl run time: $crl_gentime");
219             ok(
220                 # Is the CRL's lastUpdate time within a second of the time that
221                 # `openssl ca -gencrl` was executed?
222                 $crl_gentime - 1 <= $crl_lastupdate && $crl_lastupdate <= $crl_gentime + 1,
223                 'CRL lastUpdate field has (roughly) expected value'
224             );
225         }
226
227         my $crl_nextupdate = crl_field("$filename-crl.pem", 'nextUpdate');
228         if (exists $opts->{nextupdate}) {
229             is(
230                 $crl_nextupdate,
231                 rfc5280_time($opts->{nextupdate}),
232                 'CRL nextUpdate field has expected value'
233             );
234         } else {
235             diag("CRL nextUpdate:   $crl_nextupdate");
236             diag("openssl run time: $crl_gentime");
237             ok(
238                 # Is the CRL's lastUpdate time within a second of the time that
239                 # `openssl ca -gencrl` was executed, taking into account the use
240                 # of '-crlsec 60'?
241                 $crl_gentime + 59 <= $crl_nextupdate && $crl_nextupdate <= $crl_gentime + 61,
242                 'CRL nextUpdate field has (roughly) expected value'
243             );
244         }
245     };
246 }
247
248 sub yes {
249     my $cntr = 10;
250     open(PIPE, "|-", join(" ",@_));
251     local $SIG{PIPE} = "IGNORE";
252     1 while $cntr-- > 0 && print PIPE "y\n";
253     close PIPE;
254     return 0;
255 }
256
257 # Get the value of the lastUpdate or nextUpdate field from a CRL
258 sub crl_field {
259     my ($crl_path, $field_name) = @_;
260
261     my @out = run(
262         app(['openssl',
263              'crl',
264              '-in', $crl_path,
265              '-noout',
266              '-' . lc($field_name),
267         ]),
268         capture => 1,
269         statusvar => \my $exit,
270     );
271     ok($exit, "CRL $field_name field retrieved");
272     diag("CRL $field_name: $out[0]");
273
274     $out[0] =~ s/^\Q$field_name\E=//;
275     $out[0] =~ s/\n?//;
276     my $time = human_time($out[0]);
277
278     return $time;
279 }
280
281 # Converts human-readable ASN1_TIME_print() output to Unix time
282 sub human_time {
283     my ($human) = @_;
284
285     my ($mo, $d, $h, $m, $s, $y) = $human =~ /^([A-Za-z]{3})\s+(\d+) (\d{2}):(\d{2}):(\d{2}) (\d{4})/;
286
287     my %months = (
288         Jan => 0, Feb => 1, Mar => 2, Apr => 3, May => 4,  Jun => 5,
289         Jul => 6, Aug => 7, Sep => 8, Oct => 9, Nov => 10, Dec => 11,
290     );
291
292     return timegm($s, $m, $h, $d, $months{$mo}, $y);
293 }
294
295 # Converts an RFC 5280 timestamp to Unix time
296 sub rfc5280_time {
297     my ($asn1) = @_;
298
299     my ($y, $mo, $d, $h, $m, $s) = $asn1 =~ /^(\d{2,4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/;
300
301     return timegm($s, $m, $h, $d, $mo - 1, $y);
302 }