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',
96 return qr!-----BEGIN\ $label-----(?:\s|\n)*!;
100 return qr!-----END\ $label-----(?:\s|\n)*!;
105 my $b64_char_re = qr![0-9A-Za-z\+/]!; # see RFC 7468
106 my $header = $header_re->($label);
107 my $footer = $footer_re->($label);
111 (?
:(?
:$b64_char_re)+\s
*\n)*
112 (?
:$b64_char_re)*(?
:=\s
*\n=|={0,2})?\s
*\n
117 sub strip_leading_text
{
120 my $header = $header_re->(qr/.*?/);
121 $content =~ s/^.*?(?=$header)//s;
126 my ($content, %opts) = @_;
127 my $label = $opts{label
} // 'CERTIFICATE';
129 my $header = $header_re->($label);
130 return split(/(?=$header)/,$content);
134 my ($content, %opts) = @_;
136 $content = strip_leading_text
($content);
138 my $re = $pem_re->($opts{label
} // 'CERTIFICATE');
139 $re = qr/($re\n+)*$re/ if $opts{multiple
};
141 return $content if $content =~ /^$re$/; # OK
143 return undef if $opts{noerr
};
144 die "not a valid PEM-formatted string.\n";
150 my $header = $header_re->(qr/.*?/);
151 my $footer = $footer_re->(qr/.*?/);
153 $content = strip_leading_text
($content);
155 # only take first PEM entry
156 $content =~ s/^$header$//mg;
157 $content =~ s/$footer.*//sg;
159 $content = decode_base64
($content);
165 my ($content, %opts) = @_;
167 my $label = $opts{label
} // 'CERTIFICATE';
169 my $b64 = encode_base64
($content, '');
170 $b64 = join("\n", ($b64 =~ /.{1,64}/sg));
171 return "-----BEGIN $label-----\n$b64\n-----END $label-----\n";
176 warn Net
::SSLeay
::print_errs
();
177 Net
::SSLeay
::die_now
("$msg\n");
180 my $read_certificate = sub {
181 my ($cert_path) = @_;
183 die "'$cert_path' does not exist!\n" if ! -e
$cert_path;
185 my $bio = Net
::SSLeay
::BIO_new_file
($cert_path, 'r')
186 or ssl_die
("unable to read '$cert_path' - $!");
188 my $cert = Net
::SSLeay
::PEM_read_bio_X509
($bio);
189 Net
::SSLeay
::BIO_free
($bio);
190 die "unable to read certificate from '$cert_path'\n" if !$cert;
195 sub convert_asn1_to_epoch
{
196 my ($asn1_time) = @_;
198 ssl_die
("invalid ASN1 time object") if !$asn1_time;
199 my $iso_time = Net
::SSLeay
::P_ASN1_TIME_get_isotime
($asn1_time);
200 ssl_die
("unable to parse ASN1 time") if $iso_time eq '';
201 return Date
::Parse
::str2time
($iso_time);
204 sub get_certificate_fingerprint
{
205 my ($cert_path) = @_;
207 my $cert = $read_certificate->($cert_path);
209 my $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
210 Net
::SSLeay
::X509_free
($cert);
212 die "unable to get fingerprint for '$cert_path' - got empty value\n"
213 if !defined($fp) || $fp eq '';
218 sub assert_certificate_matches_key
{
219 my ($cert_path, $key_path) = @_;
221 die "No certificate path given!\n" if !$cert_path;
222 die "No certificate key path given!\n" if !$key_path;
224 die "Certificate at '$cert_path' does not exist!\n" if ! -e
$cert_path;
225 die "Certificate key '$key_path' does not exist!\n" if ! -e
$key_path;
227 my $ctx = Net
::SSLeay
::CTX_new
()
228 or ssl_die
("Failed to create SSL context in order to verify private key");
231 my $filetype = &Net
::SSLeay
::FILETYPE_PEM
;
233 Net
::SSLeay
::CTX_use_PrivateKey_file
($ctx, $key_path, $filetype)
234 or ssl_die
("Failed to load private key from '$key_path' into SSL context");
236 Net
::SSLeay
::CTX_use_certificate_file
($ctx, $cert_path, $filetype)
237 or ssl_die
("Failed to load certificate from '$cert_path' into SSL context");
239 Net
::SSLeay
::CTX_check_private_key
($ctx)
240 or ssl_die
("Failed to validate private key and certificate");
244 Net
::SSLeay
::CTX_free
($ctx);
251 sub get_certificate_info
{
252 my ($cert_path) = @_;
254 my $cert = $read_certificate->($cert_path);
256 my $parse_san = sub {
258 while (my ($type, $value) = splice(@_, 0, 2)) {
259 if ($type != 2 && $type != 7) {
260 warn "unexpected SAN type encountered: $type\n";
265 my $hex = unpack("H*", $value);
266 if (length($hex) == 8) {
268 $value = join(".", unpack("C4C4C4C4", $value));
269 } elsif (length($hex) == 32) {
271 $value = join(":", unpack("H4H4H4H4H4H4H4H4", $value));
273 warn "cannot parse SAN IP entry '0x${hex}'\n";
285 $info->{fingerprint
} = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
287 if (my $subject = Net
::SSLeay
::X509_get_subject_name
($cert)) {
288 $info->{subject
} = Net
::SSLeay
::X509_NAME_oneline
($subject);
291 if (my $issuer = Net
::SSLeay
::X509_get_issuer_name
($cert)) {
292 $info->{issuer
} = Net
::SSLeay
::X509_NAME_oneline
($issuer);
295 eval { $info->{notbefore
} = convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notBefore
($cert)) };
297 eval { $info->{notafter
} = convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notAfter
($cert)) };
300 $info->{san
} = $parse_san->(Net
::SSLeay
::X509_get_subjectAltNames
($cert));
301 $info->{pem
} = Net
::SSLeay
::PEM_get_string_X509
($cert);
303 my $pub_key = eval { Net
::SSLeay
::X509_get_pubkey
($cert) };
306 $info->{'public-key-type'} = Net
::SSLeay
::OBJ_nid2sn
(Net
::SSLeay
::EVP_PKEY_id
($pub_key));
307 $info->{'public-key-bits'} = Net
::SSLeay
::EVP_PKEY_bits
($pub_key);
308 Net
::SSLeay
::EVP_PKEY_free
($pub_key);
311 Net
::SSLeay
::X509_free
($cert);
313 $cert_path =~ s!^.*/!!g;
314 $info->{filename
} = $cert_path;
319 # Checks whether certificate expires before $timestamp (UNIX epoch)
321 my ($cert_path, $timestamp) = @_;
323 $timestamp //= time();
325 my $cert = $read_certificate->($cert_path);
326 my $not_after = eval { convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notAfter
($cert)) };
329 Net
::SSLeay
::X509_free
($cert);
333 return ($not_after < $timestamp) ?
1 : 0;
336 # Create a CSR and certificate key for a given order
337 # returns path to CSR file or path to CSR and key files
342 my $bits = delete($attr{bits
}) // 4096;
343 my $dig_alg = delete($attr{digest
}) // 'sha256';
344 my $pem_key = delete($attr{private_key
});
347 my $identifiers = delete($attr{identifiers
});
349 die "Identifiers are required to generate a CSR.\n"
350 if !defined($identifiers);
352 my $san = [ map { $_->{value
} } grep { $_->{type
} eq 'dns' } @$identifiers ];
353 die "DNS identifiers are required to generate a CSR.\n" if !scalar @$san;
356 my $common_name = delete($attr{common_name
}) // $san->[0];
358 my $md = eval { Net
::SSLeay
::EVP_get_digestbyname
($dig_alg) };
359 die "Invalid digest algorithm '$dig_alg'\n" if !$md;
361 my ($bio, $pk, $req);
364 my ($die_msg, $no_warn) = @_;
365 Net
::SSLeay
::print_errs
() if !$no_warn;
367 Net
::SSLeay
::X509_REQ_free
($req) if $req;
368 Net
::SSLeay
::EVP_PKEY_free
($pk) if $pk;
369 Net
::SSLeay
::BIO_free
($bio) if $bio;
371 die $die_msg if $die_msg;
374 # this unfortunately causes a small memory leak, since there is no
375 # X509_NAME_free() (yet)
376 my $name = Net
::SSLeay
::X509_NAME_new
();
377 ssl_die
("Failed to allocate X509_NAME object") if !$name;
378 my $add_name_entry = sub {
381 my $res = Net
::SSLeay
::X509_NAME_add_entry_by_txt
(
382 $name, $k, &Net
::SSLeay
::MBSTRING_UTF8
, encode
('utf-8', $v));
384 $cleanup->("Failed to add '$k'='$v' to DN\n") if !$res;
387 $add_name_entry->('CN', $common_name);
388 for (qw(C ST L O OU)) {
389 if (defined(my $v = $attr{$_})) {
390 $add_name_entry->($_, $v);
394 if (defined($pem_key)) {
395 my $bio_s_mem = Net
::SSLeay
::BIO_s_mem
();
396 $cleanup->("Failed to allocate BIO_s_mem for private key\n") if !$bio_s_mem;
398 $bio = Net
::SSLeay
::BIO_new
($bio_s_mem);
399 $cleanup->("Failed to allocate BIO for private key\n") if !$bio;
401 $cleanup->("Failed to write PEM-encoded key to BIO\n")
402 if Net
::SSLeay
::BIO_write
($bio, $pem_key) <= 0;
404 $pk = Net
::SSLeay
::PEM_read_bio_PrivateKey
($bio);
405 $cleanup->("Failed to read private key into EVP_PKEY\n") if !$pk;
407 $pk = Net
::SSLeay
::EVP_PKEY_new
();
408 $cleanup->("Failed to allocate EVP_PKEY for private key\n") if !$pk;
410 my $rsa = Net
::SSLeay
::RSA_generate_key
($bits, 65537);
411 $cleanup->("Failed to generate RSA key pair\n") if !$rsa;
413 $cleanup->("Failed to assign RSA key to EVP_PKEY\n")
414 if !Net
::SSLeay
::EVP_PKEY_assign_RSA
($pk, $rsa);
417 $req = Net
::SSLeay
::X509_REQ_new
();
418 $cleanup->("Failed to allocate X509_REQ\n") if !$req;
420 $cleanup->("Failed to set subject name\n")
421 if (!Net
::SSLeay
::X509_REQ_set_subject_name
($req, $name));
423 Net
::SSLeay
::P_X509_REQ_add_extensions
(
425 &Net
::SSLeay
::NID_key_usage
=> 'digitalSignature,keyEncipherment',
426 &Net
::SSLeay
::NID_basic_constraints
=> 'CA:FALSE',
427 &Net
::SSLeay
::NID_ext_key_usage
=> 'serverAuth,clientAuth',
428 &Net
::SSLeay
::NID_subject_alt_name
=> join(',', map { "DNS:$_" } @$san),
429 ) or $cleanup->("Failed to add extensions to CSR\n");
431 $cleanup->("Failed to set public key\n") if !Net
::SSLeay
::X509_REQ_set_pubkey
($req, $pk);
433 $cleanup->("Failed to set CSR version\n") if !Net
::SSLeay
::X509_REQ_set_version
($req, 0);
435 $cleanup->("Failed to sign CSR\n") if !Net
::SSLeay
::X509_REQ_sign
($req, $pk, $md);
437 my $pk_pem = Net
::SSLeay
::PEM_get_string_PrivateKey
($pk);
438 my $req_pem = Net
::SSLeay
::PEM_get_string_X509_REQ
($req);
440 $cleanup->(undef, 1);
442 return wantarray ?
($req_pem, $pk_pem) : $req_pem;