1 package PVE
::Certificate
;
7 use Encode
qw(decode encode);
8 use MIME
::Base64
qw(decode_base64 encode_base64);
11 use PVE
::JSONSchema
qw(get_standard_option);
13 Net
::SSLeay
::load_error_strings
();
14 Net
::SSLeay
::randomize
();
16 PVE
::JSONSchema
::register_format
('pem-certificate', sub {
17 my ($content, $noerr) = @_;
19 return check_pem
($content, noerr
=> $noerr);
22 PVE
::JSONSchema
::register_format
('pem-certificate-chain', sub {
23 my ($content, $noerr) = @_;
25 return check_pem
($content, noerr
=> $noerr, multiple
=> 1);
28 PVE
::JSONSchema
::register_format
('pem-string', sub {
29 my ($content, $noerr) = @_;
31 return check_pem
($content, noerr
=> $noerr, label
=> qr/.*?/);
34 PVE
::JSONSchema
::register_standard_option
('pve-certificate-info', {
41 fingerprint
=> get_standard_option
('fingerprint-sha256', {
46 description
=> 'Certificate subject name.',
51 description
=> 'Certificate issuer name.',
56 description
=> 'Certificate\'s notBefore timestamp (UNIX epoch).',
57 renderer
=> 'timestamp',
62 description
=> 'Certificate\'s notAfter timestamp (UNIX epoch).',
63 renderer
=> 'timestamp',
68 description
=> 'List of Certificate\'s SubjectAlternativeName entries.',
77 description
=> 'Certificate in PEM format',
78 format
=> 'pem-certificate',
81 'public-key-type' => {
83 description
=> 'Certificate\'s public key algorithm',
86 'public-key-bits' => {
88 description
=> 'Certificate\'s public key size',
95 my $b64_char_re = qr![0-9A-Za-z\+/]!;
98 return qr!-----BEGIN\ $label-----(?:\s|\n)*!;
100 my $footer_re = sub {
102 return qr!-----END\ $label-----(?:\s|\n)*!;
107 my $header = $header_re->($label);
108 my $footer = $footer_re->($label);
112 (?
:(?
:$b64_char_re)+\s
*\n)*
113 (?
:$b64_char_re)*(?
:=\s
*\n=|={0,2})?\s
*\n
118 sub strip_leading_text
{
121 my $header = $header_re->(qr/.*?/);
122 $content =~ s/^.*?(?=$header)//s;
127 my ($content, %opts) = @_;
128 my $label = $opts{label
} // 'CERTIFICATE';
130 my $header = $header_re->($label);
131 return split(/(?=$header)/,$content);
135 my ($content, %opts) = @_;
137 my $label = $opts{label
} // 'CERTIFICATE';
138 my $multiple = $opts{multiple
};
139 my $noerr = $opts{noerr
};
141 $content = strip_leading_text
($content);
143 my $re = $pem_re->($label);
145 $re = qr/($re\n+)*$re/ if $multiple;
147 if ($content =~ /^$re$/) {
150 return undef if $noerr;
151 die "not a valid PEM-formatted string.\n";
158 my $header = $header_re->(qr/.*?/);
159 my $footer = $footer_re->(qr/.*?/);
161 $content = strip_leading_text
($content);
163 # only take first PEM entry
164 $content =~ s/^$header$//mg;
165 $content =~ s/$footer.*//sg;
167 $content = decode_base64
($content);
173 my ($content, %opts) = @_;
175 my $label = $opts{label
} // 'CERTIFICATE';
177 my $b64 = encode_base64
($content, '');
178 $b64 = join("\n", ($b64 =~ /.{1,64}/sg));
179 return "-----BEGIN $label-----\n$b64\n-----END $label-----\n";
184 Net
::SSLeay
::die_now
("$msg\n");
187 my $read_certificate = sub {
188 my ($cert_path) = @_;
190 die "'$cert_path' does not exist!\n" if ! -e
$cert_path;
192 my $bio = Net
::SSLeay
::BIO_new_file
($cert_path, 'r')
193 or ssl_die
("unable to read '$cert_path' - $!");
195 my $cert = Net
::SSLeay
::PEM_read_bio_X509
($bio);
196 Net
::SSLeay
::BIO_free
($bio);
197 die "unable to read certificate from '$cert_path'\n" if !$cert;
202 sub convert_asn1_to_epoch
{
203 my ($asn1_time) = @_;
205 ssl_die
("invalid ASN1 time object") if !$asn1_time;
206 my $iso_time = Net
::SSLeay
::P_ASN1_TIME_get_isotime
($asn1_time);
207 ssl_die
("unable to parse ASN1 time") if $iso_time eq '';
208 return Date
::Parse
::str2time
($iso_time);
211 sub get_certificate_fingerprint
{
212 my ($cert_path) = @_;
214 my $cert = $read_certificate->($cert_path);
216 my $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
217 Net
::SSLeay
::X509_free
($cert);
219 die "unable to get fingerprint for '$cert_path' - got empty value\n"
220 if !defined($fp) || $fp eq '';
225 sub assert_certificate_matches_key
{
226 my ($cert_path, $key_path) = @_;
228 die "No certificate path given!\n" if !$cert_path;
229 die "No certificate key path given!\n" if !$key_path;
231 die "Certificate at '$cert_path' does not exist!\n" if ! -e
$cert_path;
232 die "Certificate key '$key_path' does not exist!\n" if ! -e
$key_path;
234 my $ctx = Net
::SSLeay
::CTX_new
()
235 or ssl_die
("Failed to create SSL context in order to verify private key");
238 my $filetype = &Net
::SSLeay
::FILETYPE_PEM
;
240 Net
::SSLeay
::CTX_use_PrivateKey_file
($ctx, $key_path, $filetype)
241 or ssl_die
("Failed to load private key from '$key_path' into SSL context");
243 Net
::SSLeay
::CTX_use_certificate_file
($ctx, $cert_path, $filetype)
244 or ssl_die
("Failed to load certificate from '$cert_path' into SSL context");
246 Net
::SSLeay
::CTX_check_private_key
($ctx)
247 or ssl_die
("Failed to validate private key and certificate");
251 Net
::SSLeay
::CTX_free
($ctx);
258 sub get_certificate_info
{
259 my ($cert_path) = @_;
261 my $cert = $read_certificate->($cert_path);
263 my $parse_san = sub {
265 while (my ($type, $value) = splice(@_, 0, 2)) {
266 if ($type != 2 && $type != 7) {
267 warn "unexpected SAN type encountered: $type\n";
272 my $hex = unpack("H*", $value);
273 if (length($hex) == 8) {
275 $value = join(".", unpack("C4C4C4C4", $value));
276 } elsif (length($hex) == 32) {
278 $value = join(":", unpack("H4H4H4H4H4H4H4H4", $value));
280 warn "cannot parse SAN IP entry '0x${hex}'\n";
292 $info->{fingerprint
} = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
294 if (my $subject = Net
::SSLeay
::X509_get_subject_name
($cert)) {
295 $info->{subject
} = Net
::SSLeay
::X509_NAME_oneline
($subject);
298 if (my $issuer = Net
::SSLeay
::X509_get_issuer_name
($cert)) {
299 $info->{issuer
} = Net
::SSLeay
::X509_NAME_oneline
($issuer);
302 eval { $info->{notbefore
} = convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notBefore
($cert)) };
304 eval { $info->{notafter
} = convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notAfter
($cert)) };
307 $info->{san
} = $parse_san->(Net
::SSLeay
::X509_get_subjectAltNames
($cert));
308 $info->{pem
} = Net
::SSLeay
::PEM_get_string_X509
($cert);
310 my $pub_key = eval { Net
::SSLeay
::X509_get_pubkey
($cert) };
313 $info->{'public-key-type'} = Net
::SSLeay
::OBJ_nid2sn
(Net
::SSLeay
::EVP_PKEY_id
($pub_key));
314 $info->{'public-key-bits'} = Net
::SSLeay
::EVP_PKEY_bits
($pub_key);
315 Net
::SSLeay
::EVP_PKEY_free
($pub_key);
318 Net
::SSLeay
::X509_free
($cert);
320 $cert_path =~ s!^.*/!!g;
321 $info->{filename
} = $cert_path;
326 # Checks whether certificate expires before $timestamp (UNIX epoch)
328 my ($cert_path, $timestamp) = @_;
330 $timestamp //= time();
332 my $cert = $read_certificate->($cert_path);
333 my $not_after = eval { convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notAfter
($cert)) };
336 Net
::SSLeay
::X509_free
($cert);
340 return ($not_after < $timestamp) ?
1 : 0;
343 # Create a CSR and certificate key for a given order
344 # returns path to CSR file or path to CSR and key files
349 my $bits = delete($attr{bits
}) // 4096;
350 my $dig_alg = delete($attr{digest
}) // 'sha256';
351 my $pem_key = delete($attr{private_key
});
354 my $identifiers = delete($attr{identifiers
});
356 die "Identifiers are required to generate a CSR.\n"
357 if !defined($identifiers);
359 my $san = [ map { $_->{value
} } grep { $_->{type
} eq 'dns' } @$identifiers ];
360 die "DNS identifiers are required to generate a CSR.\n" if !scalar @$san;
363 my $common_name = delete($attr{common_name
}) // $san->[0];
365 my $md = eval { Net
::SSLeay
::EVP_get_digestbyname
($dig_alg) };
366 die "Invalid digest algorithm '$dig_alg'\n" if !$md;
368 my ($bio, $pk, $req);
371 my ($die_msg, $no_warn) = @_;
372 Net
::SSLeay
::print_errs
() if !$no_warn;
374 Net
::SSLeay
::X509_REQ_free
($req) if $req;
375 Net
::SSLeay
::EVP_PKEY_free
($pk) if $pk;
376 Net
::SSLeay
::BIO_free
($bio) if $bio;
378 die $die_msg if $die_msg;
381 # this unfortunately causes a small memory leak, since there is no
382 # X509_NAME_free() (yet)
383 my $name = Net
::SSLeay
::X509_NAME_new
();
384 ssl_die
("Failed to allocate X509_NAME object") if !$name;
385 my $add_name_entry = sub {
388 my $res = Net
::SSLeay
::X509_NAME_add_entry_by_txt
(
389 $name, $k, &Net
::SSLeay
::MBSTRING_UTF8
, encode
('utf-8', $v));
391 $cleanup->("Failed to add '$k'='$v' to DN\n") if !$res;
394 $add_name_entry->('CN', $common_name);
395 for (qw(C ST L O OU)) {
396 if (defined(my $v = $attr{$_})) {
397 $add_name_entry->($_, $v);
401 if (defined($pem_key)) {
402 my $bio_s_mem = Net
::SSLeay
::BIO_s_mem
();
403 $cleanup->("Failed to allocate BIO_s_mem for private key\n") if !$bio_s_mem;
405 $bio = Net
::SSLeay
::BIO_new
($bio_s_mem);
406 $cleanup->("Failed to allocate BIO for private key\n") if !$bio;
408 $cleanup->("Failed to write PEM-encoded key to BIO\n")
409 if Net
::SSLeay
::BIO_write
($bio, $pem_key) <= 0;
411 $pk = Net
::SSLeay
::PEM_read_bio_PrivateKey
($bio);
412 $cleanup->("Failed to read private key into EVP_PKEY\n") if !$pk;
414 $pk = Net
::SSLeay
::EVP_PKEY_new
();
415 $cleanup->("Failed to allocate EVP_PKEY for private key\n") if !$pk;
417 my $rsa = Net
::SSLeay
::RSA_generate_key
($bits, 65537);
418 $cleanup->("Failed to generate RSA key pair\n") if !$rsa;
420 $cleanup->("Failed to assign RSA key to EVP_PKEY\n")
421 if !Net
::SSLeay
::EVP_PKEY_assign_RSA
($pk, $rsa);
424 $req = Net
::SSLeay
::X509_REQ_new
();
425 $cleanup->("Failed to allocate X509_REQ\n") if !$req;
427 $cleanup->("Failed to set subject name\n")
428 if (!Net
::SSLeay
::X509_REQ_set_subject_name
($req, $name));
430 Net
::SSLeay
::P_X509_REQ_add_extensions
(
432 &Net
::SSLeay
::NID_key_usage
=> 'digitalSignature,keyEncipherment',
433 &Net
::SSLeay
::NID_basic_constraints
=> 'CA:FALSE',
434 &Net
::SSLeay
::NID_ext_key_usage
=> 'serverAuth,clientAuth',
435 &Net
::SSLeay
::NID_subject_alt_name
=> join(',', map { "DNS:$_" } @$san),
436 ) or $cleanup->("Failed to add extensions to CSR\n");
438 $cleanup->("Failed to set public key\n") if !Net
::SSLeay
::X509_REQ_set_pubkey
($req, $pk);
440 $cleanup->("Failed to set CSR version\n") if !Net
::SSLeay
::X509_REQ_set_version
($req, 2);
442 $cleanup->("Failed to sign CSR\n") if !Net
::SSLeay
::X509_REQ_sign
($req, $pk, $md);
444 my $pk_pem = Net
::SSLeay
::PEM_get_string_PrivateKey
($pk);
445 my $req_pem = Net
::SSLeay
::PEM_get_string_X509_REQ
($req);
447 $cleanup->(undef, 1);
449 return wantarray ?
($req_pem, $pk_pem) : $req_pem;