Skip to content

Commit a238b27

Browse files
committed
gui: Simplify isCertificateValid()
1 parent 7cced74 commit a238b27

1 file changed

Lines changed: 9 additions & 20 deletions

File tree

src/gui/src/SslCertificate.cpp

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
#include "SslCertificate.h"
1919
#include "common/DataDirectories.h"
20+
#include "base/finally.h"
21+
#include "io/fstream.h"
2022
#include "net/FingerprintDatabase.h"
2123
#include "net/SecureUtils.h"
2224

@@ -98,54 +100,41 @@ std::string SslCertificate::getCertificateDirectory()
98100
bool SslCertificate::isCertificateValid(const std::string& path)
99101
{
100102
OpenSSL_add_all_algorithms();
101-
ERR_load_BIO_strings();
102103
ERR_load_crypto_strings();
103104

104-
BIO* bio = BIO_new(BIO_s_file());
105-
106-
auto ret = BIO_read_filename(bio, path.c_str());
107-
if (!ret) {
105+
auto fp = barrier::fopen_utf8_path(path, "r");
106+
if (!fp) {
108107
emit info(tr("Could not read from default certificate file."));
109-
BIO_free_all(bio);
110108
return false;
111109
}
110+
auto file_close = barrier::finally([fp]() { std::fclose(fp); });
112111

113-
X509* cert = PEM_read_bio_X509(bio, NULL, 0, NULL);
112+
auto* cert = PEM_read_X509(fp, nullptr, nullptr, nullptr);
114113
if (!cert) {
115114
emit info(tr("Error loading default certificate file to memory."));
116-
BIO_free_all(bio);
117115
return false;
118116
}
117+
auto cert_free = barrier::finally([cert]() { X509_free(cert); });
119118

120-
EVP_PKEY* pubkey = X509_get_pubkey(cert);
119+
auto* pubkey = X509_get_pubkey(cert);
121120
if (!pubkey) {
122121
emit info(tr("Default certificate key file does not contain valid public key"));
123-
X509_free(cert);
124-
BIO_free_all(bio);
125122
return false;
126123
}
124+
auto pubkey_free = barrier::finally([pubkey]() { EVP_PKEY_free(pubkey); });
127125

128126
auto type = EVP_PKEY_type(EVP_PKEY_id(pubkey));
129127
if (type != EVP_PKEY_RSA && type != EVP_PKEY_DSA) {
130128
emit info(tr("Public key in default certificate key file is not RSA or DSA"));
131-
EVP_PKEY_free(pubkey);
132-
X509_free(cert);
133-
BIO_free_all(bio);
134129
return false;
135130
}
136131

137132
auto bits = EVP_PKEY_bits(pubkey);
138133
if (bits < 2048) {
139134
// We could have small keys in old barrier installations
140135
emit info(tr("Public key in default certificate key file is too small."));
141-
EVP_PKEY_free(pubkey);
142-
X509_free(cert);
143-
BIO_free_all(bio);
144136
return false;
145137
}
146138

147-
EVP_PKEY_free(pubkey);
148-
X509_free(cert);
149-
BIO_free_all(bio);
150139
return true;
151140
}

0 commit comments

Comments
 (0)