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).',
61 description
=> 'Certificate\'s notAfter timestamp (UNIX epoch).',
66 description
=> 'List of Certificate\'s SubjectAlternativeName entries.',
74 description
=> 'Certificate in PEM format',
75 format
=> 'pem-certificate',
82 my $b64_char_re = qr![0-9A-Za-z\+/]!;
85 return qr!-----BEGIN\ $label-----(?:\s|\n)*!;
89 return qr!-----END\ $label-----(?:\s|\n)*!;
94 my $header = $header_re->($label);
95 my $footer = $footer_re->($label);
99 (?
:(?
:$b64_char_re)+\s
*\n)*
100 (?
:$b64_char_re)*(?
:=\s
*\n=|={0,2})?\s
*\n
105 sub strip_leading_text
{
108 my $header = $header_re->(qr/.*?/);
109 $content =~ s/^.*?(?=$header)//s;
114 my ($content, %opts) = @_;
115 my $label = $opts{label
} // 'CERTIFICATE';
117 my $header = $header_re->($label);
118 return split(/(?=$header)/,$content);
122 my ($content, %opts) = @_;
124 my $label = $opts{label
} // 'CERTIFICATE';
125 my $multiple = $opts{multiple
};
126 my $noerr = $opts{noerr
};
128 $content = strip_leading_text
($content);
130 my $re = $pem_re->($label);
132 $re = qr/($re\n+)*$re/ if $multiple;
134 if ($content =~ /^$re$/) {
137 return undef if $noerr;
138 die "not a valid PEM-formatted string.\n";
145 my $header = $header_re->(qr/.*?/);
146 my $footer = $footer_re->(qr/.*?/);
148 $content = strip_leading_text
($content);
150 # only take first PEM entry
151 $content =~ s/^$header$//mg;
152 $content =~ s/$footer.*//sg;
154 $content = decode_base64
($content);
160 my ($content, %opts) = @_;
162 my $label = $opts{label
} // 'CERTIFICATE';
164 my $b64 = encode_base64
($content, '');
165 $b64 = join("\n", ($b64 =~ /.{1,64}/sg));
166 return "-----BEGIN $label-----\n$b64\n-----END $label-----\n";
171 Net
::SSLeay
::die_now
($msg);
176 Net
::SSLeay
::print_errs
();
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' - $!\n");
188 my $cert = Net
::SSLeay
::PEM_read_bio_X509
($bio);
190 Net
::SSLeay
::BIO_free
($bio);
191 die "unable to read certificate from '$cert_path'\n";
197 sub convert_asn1_to_epoch
{
198 my ($asn1_time) = @_;
200 $ssl_die->("invalid ASN1 time object\n") if !$asn1_time;
201 my $iso_time = Net
::SSLeay
::P_ASN1_TIME_get_isotime
($asn1_time);
202 $ssl_die->("unable to parse ASN1 time\n") if $iso_time eq '';
203 return Date
::Parse
::str2time
($iso_time);
206 sub get_certificate_info
{
207 my ($cert_path) = @_;
209 my $cert = $read_certificate->($cert_path);
211 my $parse_san = sub {
213 while (my ($type, $value) = splice(@_, 0, 2)) {
214 if ($type != 2 && $type != 7) {
215 warn "unexpected SAN type encountered: $type\n";
220 my $hex = unpack("H*", $value);
221 if (length($hex) == 8) {
223 $value = join(".", unpack("C4C4C4C4", $value));
224 } elsif (length($hex) == 32) {
226 $value = join(":", unpack("H4H4H4H4H4H4H4H4", $value));
228 warn "cannot parse SAN IP entry '0x${hex}'\n";
240 $info->{fingerprint
} = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
242 my $subject = Net
::SSLeay
::X509_get_subject_name
($cert);
244 $info->{subject
} = Net
::SSLeay
::X509_NAME_oneline
($subject);
247 my $issuer = Net
::SSLeay
::X509_get_issuer_name
($cert);
249 $info->{issuer
} = Net
::SSLeay
::X509_NAME_oneline
($issuer);
252 eval { $info->{notbefore
} = convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notBefore
($cert)) };
254 eval { $info->{notafter
} = convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notAfter
($cert)) };
257 $info->{san
} = $parse_san->(Net
::SSLeay
::X509_get_subjectAltNames
($cert));
258 $info->{pem
} = Net
::SSLeay
::PEM_get_string_X509
($cert);
260 Net
::SSLeay
::X509_free
($cert);
262 $cert_path =~ s!^.*/!!g;
263 $info->{filename
} = $cert_path;
268 # Checks whether certificate expires before $timestamp (UNIX epoch)
270 my ($cert_path, $timestamp) = @_;
272 $timestamp //= time();
274 my $cert = $read_certificate->($cert_path);
275 my $not_after = eval { convert_asn1_to_epoch
(Net
::SSLeay
::X509_get_notAfter
($cert)) };
278 Net
::SSLeay
::X509_free
($cert);
282 return ($not_after < $timestamp) ?
1 : 0;
285 # Create a CSR and certificate key for a given order
286 # returns path to CSR file or path to CSR and key files
291 my $bits = delete($attr{bits
}) // 4096;
292 my $dig_alg = delete($attr{digest
}) // 'sha256';
293 my $pem_key = delete($attr{private_key
});
296 my $identifiers = delete($attr{identifiers
});
298 die "Identifiers are required to generate a CSR.\n"
299 if !defined($identifiers);
301 my $san = [ map { $_->{value
} } grep { $_->{type
} eq 'dns' } @$identifiers ];
302 die "DNS identifiers are required to generate a CSR.\n" if !scalar @$san;
304 my $md = eval { Net
::SSLeay
::EVP_get_digestbyname
($dig_alg) };
305 die "Invalid digest algorithm '$dig_alg'\n" if !$md;
307 my ($bio, $pk, $req);
310 my ($warn, $die_msg) = @_;
311 $ssl_warn->() if $warn;
313 Net
::SSLeay
::X509_REQ_free
($req) if $req;
314 Net
::SSLeay
::EVP_PKEY_free
($pk) if $pk;
315 Net
::SSLeay
::BIO_free
($bio) if $bio;
317 die $die_msg if $die_msg;
320 # this unfortunately causes a small memory leak, since there is no
321 # X509_NAME_free() (yet)
322 my $name = Net
::SSLeay
::X509_NAME_new
();
323 $ssl_die->("Failed to allocate X509_NAME object\n") if !$name;
324 my $add_name_entry = sub {
326 if (!Net
::SSLeay
::X509_NAME_add_entry_by_txt
($name,
328 &Net
::SSLeay
::MBSTRING_UTF8
,
329 encode
('utf-8', $v))) {
330 $cleanup->(1, "Failed to add '$k'='$v' to DN\n");
334 $add_name_entry->('CN', @$san[0]);
335 for (qw(C ST L O OU)) {
336 if (defined(my $v = $attr{$_})) {
337 $add_name_entry->($_, $v);
341 if (defined($pem_key)) {
342 my $bio_s_mem = Net
::SSLeay
::BIO_s_mem
();
343 $cleanup->(1, "Failed to allocate BIO_s_mem for private key\n")
346 $bio = Net
::SSLeay
::BIO_new
($bio_s_mem);
347 $cleanup->(1, "Failed to allocate BIO for private key\n") if !$bio;
349 $cleanup->(1, "Failed to write PEM-encoded key to BIO\n")
350 if Net
::SSLeay
::BIO_write
($bio, $pem_key) <= 0;
352 $pk = Net
::SSLeay
::PEM_read_bio_PrivateKey
($bio);
353 $cleanup->(1, "Failed to read private key into EVP_PKEY\n") if !$pk;
355 $pk = Net
::SSLeay
::EVP_PKEY_new
();
356 $cleanup->(1, "Failed to allocate EVP_PKEY for private key\n") if !$pk;
358 my $rsa = Net
::SSLeay
::RSA_generate_key
($bits, 65537);
359 $cleanup->(1, "Failed to generate RSA key pair\n") if !$rsa;
361 $cleanup->(1, "Failed to assign RSA key to EVP_PKEY\n")
362 if !Net
::SSLeay
::EVP_PKEY_assign_RSA
($pk, $rsa);
365 $req = Net
::SSLeay
::X509_REQ_new
();
366 $cleanup->(1, "Failed to allocate X509_REQ\n") if !$req;
368 $cleanup->(1, "Failed to set subject name\n")
369 if (!Net
::SSLeay
::X509_REQ_set_subject_name
($req, $name));
371 $cleanup->(1, "Failed to add extensions to CSR\n")
372 if !Net
::SSLeay
::P_X509_REQ_add_extensions
($req,
373 &Net
::SSLeay
::NID_key_usage
=> 'digitalSignature,keyEncipherment',
374 &Net
::SSLeay
::NID_basic_constraints
=> 'CA:FALSE',
375 &Net
::SSLeay
::NID_ext_key_usage
=> 'serverAuth,clientAuth',
376 &Net
::SSLeay
::NID_subject_alt_name
=> join(',', map { "DNS:$_" } @$san),
379 $cleanup->(1, "Failed to set public key\n")
380 if !Net
::SSLeay
::X509_REQ_set_pubkey
($req, $pk);
382 $cleanup->(1, "Failed to set CSR version\n")
383 if !Net
::SSLeay
::X509_REQ_set_version
($req, 2);
385 $cleanup->(1, "Failed to sign CSR\n")
386 if !Net
::SSLeay
::X509_REQ_sign
($req, $pk, $md);
388 my $pk_pem = Net
::SSLeay
::PEM_get_string_PrivateKey
($pk);
389 my $req_pem = Net
::SSLeay
::PEM_get_string_X509_REQ
($req);
393 return wantarray ?
($req_pem, $pk_pem) : $req_pem;