3 #include <boost/algorithm/hex.hpp>
4 #include <boost/scoped_array.hpp>
9 #include "logging/logging.h"
10 #include "openssl_compat.h"
11 #include "utilities/utils.h"
13 PublicKey::PublicKey(
const boost::filesystem::path &path) : value_(
Utils::readFile(path)) {
14 type_ = Crypto::IdentifyRSAKeyType(value_);
17 PublicKey::PublicKey(Json::Value uptane_json) {
18 if (!uptane_json[
"keytype"].isString()) {
19 type_ = KeyType::kUnknown;
22 if (!uptane_json[
"keyval"].isObject()) {
23 type_ = KeyType::kUnknown;
27 if (!uptane_json[
"keyval"][
"public"].isString()) {
28 type_ = KeyType::kUnknown;
32 std::string keytype = uptane_json[
"keytype"].asString();
33 std::string keyvalue = uptane_json[
"keyval"][
"public"].asString();
35 std::transform(keytype.begin(), keytype.end(), keytype.begin(), ::tolower);
38 if (keytype ==
"ed25519") {
39 type = KeyType::kED25519;
40 }
else if (keytype ==
"rsa") {
41 type = Crypto::IdentifyRSAKeyType(keyvalue);
42 if (type == KeyType::kUnknown) {
43 LOG_WARNING <<
"Couldn't identify length of RSA key";
46 type = KeyType::kUnknown;
52 PublicKey::PublicKey(std::string value, KeyType type) : value_(std::move(value)), type_(type) {
53 if (Crypto::IsRsaKeyType(type)) {
54 if (type != Crypto::IdentifyRSAKeyType(value)) {
55 std::logic_error(
"RSA key length is incorrect");
62 case KeyType::kED25519:
63 return Crypto::ED25519Verify(boost::algorithm::unhex(value_), Utils::fromBase64(signature), message);
64 case KeyType::kRSA2048:
65 case KeyType::kRSA3072:
66 case KeyType::kRSA4096:
67 return Crypto::RSAPSSVerify(value_, Utils::fromBase64(signature), message);
73 bool PublicKey::operator==(
const PublicKey &rhs)
const {
return value_ == rhs.value_ && type_ == rhs.type_; }
77 case KeyType::kRSA2048:
78 case KeyType::kRSA3072:
79 case KeyType::kRSA4096:
80 res[
"keytype"] =
"RSA";
82 case KeyType::kED25519:
83 res[
"keytype"] =
"ED25519";
85 case KeyType::kUnknown:
86 res[
"keytype"] =
"unknown";
89 throw std::range_error(
"Unknown key type in PublicKey::ToUptane");
91 res[
"keyval"][
"public"] = value_;
95 std::string PublicKey::KeyId()
const {
96 std::string key_content = value_;
97 boost::algorithm::trim_right_if(key_content, boost::algorithm::is_any_of(
"\n"));
98 std::string keyid = boost::algorithm::hex(Crypto::sha256digest(Utils::jsonToCanonicalStr(Json::Value(key_content))));
99 std::transform(keyid.begin(), keyid.end(), keyid.begin(), ::tolower);
103 std::string Crypto::sha256digest(
const std::string &text) {
104 unsigned char sha256_hash[crypto_hash_sha256_BYTES];
105 crypto_hash_sha256(sha256_hash, reinterpret_cast<const unsigned char *>(text.c_str()), text.size());
106 return std::string(reinterpret_cast<char *>(sha256_hash), crypto_hash_sha256_BYTES);
109 std::string Crypto::sha512digest(
const std::string &text) {
110 unsigned char sha512_hash[crypto_hash_sha512_BYTES];
111 crypto_hash_sha512(sha512_hash, reinterpret_cast<const unsigned char *>(text.c_str()), text.size());
112 return std::string(reinterpret_cast<char *>(sha512_hash), crypto_hash_sha512_BYTES);
115 std::string Crypto::RSAPSSSign(ENGINE *engine,
const std::string &private_key,
const std::string &message) {
116 StructGuard<EVP_PKEY> key(
nullptr, EVP_PKEY_free);
117 StructGuard<RSA> rsa(
nullptr, RSA_free);
118 if (engine !=
nullptr) {
120 key.reset(ENGINE_load_private_key(engine, private_key.c_str(),
nullptr,
nullptr));
122 if (key ==
nullptr) {
123 LOG_ERROR <<
"ENGINE_load_private_key failed with error " << ERR_error_string(ERR_get_error(),
nullptr);
124 return std::string();
127 rsa.reset(EVP_PKEY_get1_RSA(key.get()));
128 if (rsa ==
nullptr) {
129 LOG_ERROR <<
"EVP_PKEY_get1_RSA failed with error " << ERR_error_string(ERR_get_error(),
nullptr);
130 return std::string();
133 StructGuard<BIO> bio(BIO_new_mem_buf(const_cast<char *>(private_key.c_str()), static_cast<int>(private_key.size())),
135 key.reset(PEM_read_bio_PrivateKey(bio.get(),
nullptr,
nullptr,
nullptr));
136 if (key !=
nullptr) {
137 rsa.reset(EVP_PKEY_get1_RSA(key.get()));
140 if (rsa ==
nullptr) {
141 LOG_ERROR <<
"PEM_read_bio_PrivateKey failed with error " << ERR_error_string(ERR_get_error(),
nullptr);
142 return std::string();
145 #if AKTUALIZR_OPENSSL_PRE_11
146 RSA_set_method(rsa.get(), RSA_PKCS1_SSLeay());
148 RSA_set_method(rsa.get(), RSA_PKCS1_OpenSSL());
152 const auto sign_size = static_cast<unsigned int>(RSA_size(rsa.get()));
153 boost::scoped_array<unsigned char> EM(
new unsigned char[sign_size]);
154 boost::scoped_array<unsigned char> pSignature(
new unsigned char[sign_size]);
156 std::string digest = Crypto::sha256digest(message);
157 int status = RSA_padding_add_PKCS1_PSS(rsa.get(), EM.get(), reinterpret_cast<const unsigned char *>(digest.c_str()),
160 LOG_ERROR <<
"RSA_padding_add_PKCS1_PSS failed with error " << ERR_error_string(ERR_get_error(),
nullptr);
161 return std::string();
165 status = RSA_private_encrypt(RSA_size(rsa.get()), EM.get(), pSignature.get(), rsa.get(), RSA_NO_PADDING);
167 LOG_ERROR <<
"RSA_private_encrypt failed with error " << ERR_error_string(ERR_get_error(),
nullptr);
168 return std::string();
170 std::string retval = std::string(reinterpret_cast<char *>(pSignature.get()), sign_size);
174 std::string Crypto::Sign(KeyType key_type, ENGINE *engine,
const std::string &private_key,
const std::string &message) {
175 if (key_type == KeyType::kED25519) {
176 return Crypto::ED25519Sign(boost::algorithm::unhex(private_key), message);
178 return Crypto::RSAPSSSign(engine, private_key, message);
181 std::string Crypto::ED25519Sign(
const std::string &private_key,
const std::string &message) {
182 unsigned char sig[crypto_sign_BYTES];
183 crypto_sign_detached(sig,
nullptr, reinterpret_cast<const unsigned char *>(message.c_str()), message.size(),
184 reinterpret_cast<const unsigned char *>(private_key.c_str()));
185 return std::string(reinterpret_cast<char *>(sig), crypto_sign_BYTES);
188 bool Crypto::RSAPSSVerify(
const std::string &public_key,
const std::string &signature,
const std::string &message) {
189 StructGuard<RSA> rsa(
nullptr, RSA_free);
190 StructGuard<BIO> bio(BIO_new_mem_buf(const_cast<char *>(public_key.c_str()), static_cast<int>(public_key.size())),
194 if (PEM_read_bio_RSA_PUBKEY(bio.get(), &r,
nullptr,
nullptr) ==
nullptr) {
195 LOG_ERROR <<
"PEM_read_bio_RSA_PUBKEY failed with error " << ERR_error_string(ERR_get_error(),
nullptr);
201 #if AKTUALIZR_OPENSSL_PRE_11
202 RSA_set_method(rsa.get(), RSA_PKCS1_SSLeay());
204 RSA_set_method(rsa.get(), RSA_PKCS1_OpenSSL());
207 const auto size = static_cast<unsigned int>(RSA_size(rsa.get()));
208 boost::scoped_array<unsigned char> pDecrypted(
new unsigned char[size]);
213 RSA_public_decrypt(static_cast<int>(signature.size()), reinterpret_cast<const unsigned char *>(signature.c_str()),
214 pDecrypted.get(), rsa.get(), RSA_NO_PADDING);
216 LOG_ERROR <<
"RSA_public_decrypt failed with error " << ERR_error_string(ERR_get_error(),
nullptr);
220 std::string digest = Crypto::sha256digest(message);
223 status = RSA_verify_PKCS1_PSS(rsa.get(), reinterpret_cast<const unsigned char *>(digest.c_str()), EVP_sha256(),
224 pDecrypted.get(), -2 );
228 bool Crypto::ED25519Verify(
const std::string &public_key,
const std::string &signature,
const std::string &message) {
229 if (public_key.size() < crypto_sign_PUBLICKEYBYTES || signature.size() < crypto_sign_BYTES) {
232 return crypto_sign_verify_detached(reinterpret_cast<const unsigned char *>(signature.c_str()),
233 reinterpret_cast<const unsigned char *>(message.c_str()), message.size(),
234 reinterpret_cast<const unsigned char *>(public_key.c_str())) == 0;
237 bool Crypto::parseP12(BIO *p12_bio,
const std::string &p12_password, std::string *out_pkey, std::string *out_cert,
238 std::string *out_ca) {
239 #if AKTUALIZR_OPENSSL_PRE_11
240 SSLeay_add_all_algorithms();
242 StructGuard<PKCS12> p12(d2i_PKCS12_bio(p12_bio,
nullptr), PKCS12_free);
243 if (p12 ==
nullptr) {
244 LOG_ERROR <<
"Could not read from " << p12_bio <<
" file pointer";
249 auto stackx509_free = [](STACK_OF(X509) * stack) {
250 sk_X509_pop_free(stack, X509_free);
253 StructGuard<EVP_PKEY> pkey(
nullptr, EVP_PKEY_free);
254 StructGuard<X509> x509_cert(
nullptr, X509_free);
255 StructGuard<STACK_OF(X509)> ca_certs(
nullptr, stackx509_free);
258 X509 *x509c =
nullptr;
259 STACK_OF(X509) *cacs =
nullptr;
260 if (PKCS12_parse(p12.get(), p12_password.c_str(), &pk, &x509c, &cacs) == 0) {
261 LOG_ERROR <<
"Could not parse file from " << p12_bio <<
" source pointer";
265 x509_cert.reset(x509c);
266 ca_certs.reset(cacs);
269 StructGuard<BIO> pkey_pem_sink(BIO_new(BIO_s_mem()), BIO_vfree);
270 if (pkey_pem_sink ==
nullptr) {
271 LOG_ERROR <<
"Could not open pkey buffer for writing";
274 PEM_write_bio_PrivateKey(pkey_pem_sink.get(), pkey.get(),
nullptr,
nullptr, 0,
nullptr,
nullptr);
277 auto pkey_len = BIO_get_mem_data(pkey_pem_sink.get(), &pkey_buf);
278 *out_pkey = std::string(pkey_buf, static_cast<size_t>(pkey_len));
282 StructGuard<BIO> cert_sink(BIO_new(BIO_s_mem()), BIO_vfree);
283 if (cert_sink ==
nullptr) {
284 LOG_ERROR <<
"Could not open certificate buffer for writing";
287 PEM_write_bio_X509(cert_sink.get(), x509_cert.get());
291 StructGuard<BIO> ca_sink(BIO_new(BIO_s_mem()), BIO_vfree);
292 if (ca_sink ==
nullptr) {
293 LOG_ERROR <<
"Could not open ca buffer for writing";
296 X509 *ca_cert =
nullptr;
297 for (
int i = 0; i < sk_X509_num(ca_certs.get()); i++) {
298 ca_cert = sk_X509_value(ca_certs.get(), i);
299 PEM_write_bio_X509(ca_sink.get(), ca_cert);
300 PEM_write_bio_X509(cert_sink.get(), ca_cert);
302 ca_len = static_cast<size_t>(BIO_get_mem_data(ca_sink.get(), &ca_buf));
303 *out_ca = std::string(ca_buf, ca_len);
305 cert_len = static_cast<size_t>(BIO_get_mem_data(cert_sink.get(), &cert_buf));
306 *out_cert = std::string(cert_buf, cert_len);
311 bool Crypto::extractSubjectCN(
const std::string &cert, std::string *cn) {
312 StructGuard<BIO> bio(BIO_new_mem_buf(const_cast<char *>(cert.c_str()), static_cast<int>(cert.size())), BIO_vfree);
313 StructGuard<X509> x(PEM_read_bio_X509(bio.get(),
nullptr,
nullptr,
nullptr), X509_free);
318 int len = X509_NAME_get_text_by_NID(X509_get_subject_name(x.get()), NID_commonName,
nullptr, 0);
322 boost::scoped_array<char> buf(
new char[len + 1]);
323 X509_NAME_get_text_by_NID(X509_get_subject_name(x.get()), NID_commonName, buf.get(), len + 1);
324 *cn = std::string(buf.get());
328 StructGuard<EVP_PKEY> Crypto::generateRSAKeyPairEVP(KeyType key_type) {
331 case KeyType::kRSA2048:
334 case KeyType::kRSA3072:
337 case KeyType::kRSA4096:
341 return {
nullptr, EVP_PKEY_free};
344 #if AKTUALIZR_OPENSSL_PRE_11
345 StructGuard<RSA> rsa(RSA_generate_key(bits,
352 StructGuard<BIGNUM> bne(BN_new(), BN_free);
353 ret = BN_set_word(bne.get(), RSA_F4);
355 return {
nullptr, EVP_PKEY_free};
357 StructGuard<RSA> rsa(RSA_new(), RSA_free);
358 ret = RSA_generate_key_ex(rsa.get(), bits,
362 return {
nullptr, EVP_PKEY_free};
366 StructGuard<EVP_PKEY> pkey(EVP_PKEY_new(), EVP_PKEY_free);
368 EVP_PKEY_assign_RSA(pkey.get(), rsa.release());
382 StructGuard<EVP_PKEY> pkey = generateRSAKeyPairEVP(key_type);
383 if (pkey ==
nullptr) {
388 StructGuard<BIO> pubkey_sink(BIO_new(BIO_s_mem()), BIO_vfree);
389 if (pubkey_sink ==
nullptr) {
392 ret = PEM_write_bio_PUBKEY(pubkey_sink.get(), pkey.get());
396 auto pubkey_len = BIO_get_mem_data(pubkey_sink.get(), &pubkey_buf);
397 *public_key = std::string(pubkey_buf, static_cast<size_t>(pubkey_len));
400 StructGuard<BIO> privkey_sink(BIO_new(BIO_s_mem()), BIO_vfree);
401 if (privkey_sink ==
nullptr) {
405 ret = PEM_write_bio_RSAPrivateKey(privkey_sink.get(), static_cast<RSA *>(EVP_PKEY_get0(pkey.get())),
nullptr,
nullptr,
406 0,
nullptr,
nullptr);
410 auto privkey_len = BIO_get_mem_data(privkey_sink.get(), &privkey_buf);
411 *private_key = std::string(privkey_buf, static_cast<size_t>(privkey_len));
415 bool Crypto::generateEDKeyPair(std::string *public_key, std::string *private_key) {
416 unsigned char pk[crypto_sign_PUBLICKEYBYTES];
417 unsigned char sk[crypto_sign_SECRETKEYBYTES];
418 crypto_sign_keypair(pk, sk);
419 *public_key = boost::algorithm::hex(std::string(reinterpret_cast<char *>(pk), crypto_sign_PUBLICKEYBYTES));
421 *private_key = boost::algorithm::hex(std::string(reinterpret_cast<char *>(sk), crypto_sign_SECRETKEYBYTES));
426 bool Crypto::generateKeyPair(KeyType key_type, std::string *public_key, std::string *private_key) {
427 if (key_type == KeyType::kED25519) {
428 return Crypto::generateEDKeyPair(public_key, private_key);
433 bool Crypto::IsRsaKeyType(KeyType type) {
435 case KeyType::kRSA2048:
436 case KeyType::kRSA3072:
437 case KeyType::kRSA4096:
443 KeyType Crypto::IdentifyRSAKeyType(
const std::string &public_key_pem) {
444 StructGuard<BIO> bufio(BIO_new_mem_buf(reinterpret_cast<const void *>(public_key_pem.c_str()),
445 static_cast<int>(public_key_pem.length())),
447 if (bufio.get() ==
nullptr) {
448 throw std::runtime_error(
"BIO_new_mem_buf failed");
450 StructGuard<::RSA> rsa(PEM_read_bio_RSA_PUBKEY(bufio.get(),
nullptr,
nullptr,
nullptr), RSA_free);
452 if (rsa.get() ==
nullptr) {
453 return KeyType::kUnknown;
456 int key_length = RSA_size(rsa.get()) * 8;
461 switch (key_length) {
463 return KeyType::kRSA2048;
465 return KeyType::kRSA3072;
467 return KeyType::kRSA4096;
469 LOG_WARNING <<
"Weird key length:" << key_length;
470 return KeyType::kUnknown;