]> git.proxmox.com Git - pve-common.git/commitdiff
certificate: add subroutine that checks if cert and key match
authorMax Carrara <m.carrara@proxmox.com>
Fri, 3 Mar 2023 17:57:02 +0000 (18:57 +0100)
committerFabian Grünbichler <f.gruenbichler@proxmox.com>
Tue, 7 Mar 2023 09:14:42 +0000 (10:14 +0100)
This is done here in order to allow other packages to make use of
this subroutine.

Signed-off-by: Max Carrara <m.carrara@proxmox.com>
src/PVE/Certificate.pm

index 31a77223f83c556e393be3a3165ea168eda5ae1d..22de7621715c98284b6739eb17ee4d95db57c7c8 100644 (file)
@@ -228,6 +228,47 @@ sub get_certificate_fingerprint {
     return $fp;
 }
 
+sub certificate_matches_key {
+    my ($cert_path, $key_path) = @_;
+
+    die "No certificate path given!\n" if !$cert_path;
+    die "No certificate key path given!\n" if !$key_path;
+
+    die "Certificate at '$cert_path' does not exist!\n" if ! -e $cert_path;
+    die "Certificate key '$key_path' does not exist!\n" if ! -e $key_path;
+
+    my $ctx = Net::SSLeay::CTX_new()
+       or $ssl_die->(
+           "Failed to create SSL context in order to verify private key"
+       );
+
+    eval {
+       my $filetype = &Net::SSLeay::FILETYPE_PEM;
+
+       Net::SSLeay::CTX_use_PrivateKey_file($ctx, $key_path, $filetype)
+           or $ssl_die->(
+               "Failed to load private key from '$key_path' into SSL context"
+           );
+
+       Net::SSLeay::CTX_use_certificate_file($ctx, $cert_path, $filetype)
+           or $ssl_die->(
+               "Failed to load certificate from '$cert_path' into SSL context"
+           );
+
+       Net::SSLeay::CTX_check_private_key($ctx)
+           or $ssl_die->(
+               "Failed to validate private key and certificate"
+           );
+    };
+    my $err = $@;
+
+    Net::SSLeay::CTX_free($ctx);
+
+    die $err if $err;
+
+    return 1;
+}
+
 sub get_certificate_info {
     my ($cert_path) = @_;