• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / mender / 1476750812

01 Oct 2024 09:40AM UTC coverage: 76.356% (+0.03%) from 76.326%
1476750812

push

gitlab-ci

danielskinstad
feat: change generated key from RSA to ED25519

Ticket: MEN-7534
Changelog: Title

Signed-off-by: Daniel Skinstad Drabitzius <daniel.drabitzius@northern.tech>

5 of 5 new or added lines in 3 files covered. (100.0%)

2 existing lines in 1 file now uncovered.

7360 of 9639 relevant lines covered (76.36%)

11337.18 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

63.91
/src/common/crypto/platform/openssl/crypto.cpp
1
// Copyright 2023 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14

15
#include <common/crypto.hpp>
16

17
#include <common/crypto/platform/openssl/openssl_config.h>
18

19
#include <cstdint>
20
#include <string>
21
#include <vector>
22
#include <memory>
23

24
#include <openssl/bn.h>
25
#include <openssl/ecdsa.h>
26
#include <openssl/err.h>
27
#include <openssl/engine.h>
28
#include <openssl/ui.h>
29
#ifndef MENDER_CRYPTO_OPENSSL_LEGACY
30
#include <openssl/provider.h>
31
#include <openssl/store.h>
32
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
33

34
#include <openssl/evp.h>
35
#include <openssl/conf.h>
36
#include <openssl/pem.h>
37
#include <openssl/rsa.h>
38

39
#include <common/io.hpp>
40
#include <common/error.hpp>
41
#include <common/expected.hpp>
42
#include <common/common.hpp>
43

44
#include <artifact/sha/sha.hpp>
45

46

47
namespace mender {
48
namespace common {
49
namespace crypto {
50

51
const size_t MENDER_DIGEST_SHA256_LENGTH = 32;
52

53
const size_t OPENSSL_SUCCESS = 1;
54

55
using namespace std;
56

57
namespace error = mender::common::error;
58
namespace io = mender::common::io;
59

60
using EnginePtr = unique_ptr<ENGINE, void (*)(ENGINE *)>;
61
#ifndef MENDER_CRYPTO_OPENSSL_LEGACY
62
using ProviderPtr = unique_ptr<OSSL_PROVIDER, int (*)(OSSL_PROVIDER *)>;
63
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
64

65
class OpenSSLResourceHandle {
×
66
public:
67
        EnginePtr engine;
68
};
69

70
auto resource_handle_free_func = [](OpenSSLResourceHandle *h) {
×
71
        if (h) {
×
72
                delete h;
×
73
        }
74
};
×
75

76
auto pkey_ctx_free_func = [](EVP_PKEY_CTX *ctx) {
26✔
77
        if (ctx) {
26✔
78
                EVP_PKEY_CTX_free(ctx);
26✔
79
        }
80
};
26✔
81
auto pkey_free_func = [](EVP_PKEY *key) {
53✔
82
        if (key) {
53✔
83
                EVP_PKEY_free(key);
53✔
84
        }
85
};
53✔
86
auto bio_free_func = [](BIO *bio) {
49✔
87
        if (bio) {
49✔
88
                BIO_free(bio);
49✔
89
        }
90
};
49✔
91
auto bio_free_all_func = [](BIO *bio) {
16✔
92
        if (bio) {
16✔
93
                BIO_free_all(bio);
16✔
94
        }
95
};
16✔
96
auto bn_free = [](BIGNUM *bn) {
×
97
        if (bn) {
×
98
                BN_free(bn);
×
99
        }
100
};
×
101
auto engine_free_func = [](ENGINE *e) {
×
102
        if (e) {
×
103
                ENGINE_free(e);
×
104
        }
105
};
×
106

107
auto password_callback = [](char *buf, int size, int rwflag, void *u) {
3✔
108
        // We'll only use this callback for reading passphrases, not for
109
        // writing them.
110
        assert(rwflag == 0);
111

112
        if (u == nullptr) {
3✔
113
                return 0;
114
        }
115

116
        // NB: buf is not expected to be null terminated.
117
        char *const pass = static_cast<char *>(u);
118
        strncpy(buf, pass, size);
3✔
119

120
        return static_cast<int>(strnlen(pass, size));
3✔
121
};
122

123

124
// NOTE: GetOpenSSLErrorMessage should be called upon all OpenSSL errors, as
125
// the errors are queued, and if not harvested, the FIFO structure of the
126
// queue will mean that if you just get one, you might actually get the wrong
127
// one.
128
string GetOpenSSLErrorMessage() {
40✔
129
        const auto sysErrorCode = errno;
40✔
130
        auto sslErrorCode = ERR_get_error();
40✔
131

132
        std::string errorDescription {};
133
        while (sslErrorCode != 0) {
169✔
134
                if (!errorDescription.empty()) {
129✔
135
                        errorDescription += '\n';
136
                }
137
                errorDescription += ERR_error_string(sslErrorCode, nullptr);
129✔
138
                sslErrorCode = ERR_get_error();
129✔
139
        }
140
        if (sysErrorCode != 0) {
40✔
141
                if (!errorDescription.empty()) {
38✔
142
                        errorDescription += '\n';
143
                }
144
                errorDescription += "System error, code=" + std::to_string(sysErrorCode);
76✔
145
                errorDescription += ", ";
38✔
146
                errorDescription += strerror(sysErrorCode);
38✔
147
        }
148
        return errorDescription;
40✔
149
}
150

151
ExpectedPrivateKey LoadFromHSMEngine(const Args &args) {
×
152
        log::Trace("Loading the private key from HSM");
×
153

154
        ENGINE_load_builtin_engines();
×
155
        auto engine = EnginePtr(ENGINE_by_id(args.ssl_engine.c_str()), engine_free_func);
×
156

157
        if (engine == nullptr) {
×
158
                return expected::unexpected(MakeError(
×
159
                        SetupError,
160
                        "Failed to get the " + args.ssl_engine
×
161
                                + " engine. No engine with the ID found: " + GetOpenSSLErrorMessage()));
×
162
        }
163
        log::Debug("Loaded the HSM engine successfully!");
×
164

165
        int res = ENGINE_init(engine.get());
×
166
        if (not res) {
×
167
                return expected::unexpected(MakeError(
×
168
                        SetupError,
169
                        "Failed to initialise the hardware security module (HSM): "
170
                                + GetOpenSSLErrorMessage()));
×
171
        }
172
        log::Debug("Successfully initialised the HSM engine");
×
173

174
        auto private_key = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(
175
                ENGINE_load_private_key(
176
                        engine.get(),
177
                        args.private_key_path.c_str(),
178
                        (UI_METHOD *) nullptr,
179
                        nullptr /*callback_data */),
180
                pkey_free_func);
×
181
        if (private_key == nullptr) {
×
182
                return expected::unexpected(MakeError(
×
183
                        SetupError,
184
                        "Failed to load the private key from the hardware security module: "
185
                                + GetOpenSSLErrorMessage()));
×
186
        }
187
        log::Debug("Successfully loaded the private key from the HSM Engine: " + args.ssl_engine);
×
188

189
        auto handle = unique_ptr<OpenSSLResourceHandle, void (*)(OpenSSLResourceHandle *)>(
190
                new OpenSSLResourceHandle {std::move(engine)}, resource_handle_free_func);
×
191
        return PrivateKey(std::move(private_key), std::move(handle));
×
192
}
193

194
#ifdef MENDER_CRYPTO_OPENSSL_LEGACY
195
ExpectedPrivateKey LoadFrom(const Args &args) {
37✔
196
        log::Trace("Loading private key from file: " + args.private_key_path);
74✔
197
        auto private_bio_key = unique_ptr<BIO, void (*)(BIO *)>(
198
                BIO_new_file(args.private_key_path.c_str(), "r"), bio_free_func);
74✔
199
        if (private_bio_key == nullptr) {
37✔
200
                return expected::unexpected(MakeError(
6✔
201
                        SetupError,
202
                        "Failed to load the private key file " + args.private_key_path + ": "
12✔
203
                                + GetOpenSSLErrorMessage()));
30✔
204
        }
205

206
        char *passphrase = const_cast<char *>(args.private_key_passphrase.c_str());
207

208
        auto private_key = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(
209
                PEM_read_bio_PrivateKey(private_bio_key.get(), nullptr, password_callback, passphrase),
210
                pkey_free_func);
62✔
211
        if (private_key == nullptr) {
31✔
212
                return expected::unexpected(MakeError(
4✔
213
                        SetupError,
214
                        "Failed to load the private key: " + args.private_key_path + " "
8✔
215
                                + GetOpenSSLErrorMessage()));
20✔
216
        }
217

218
        return PrivateKey(std::move(private_key));
27✔
219
}
220
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
221

222
#ifndef MENDER_CRYPTO_OPENSSL_LEGACY
223
ExpectedPrivateKey LoadFrom(const Args &args) {
224
        char *passphrase = const_cast<char *>(args.private_key_passphrase.c_str());
225

226
        auto ui_method = unique_ptr<UI_METHOD, void (*)(UI_METHOD *)>(
227
                UI_UTIL_wrap_read_pem_callback(password_callback, 0 /* rw_flag */), UI_destroy_method);
228
        auto ctx = unique_ptr<OSSL_STORE_CTX, int (*)(OSSL_STORE_CTX *)>(
229
                OSSL_STORE_open(
230
                        args.private_key_path.c_str(),
231
                        ui_method.get(),
232
                        passphrase,
233
                        nullptr, /* OSSL_PARAM params[] */
234
                        nullptr),
235
                OSSL_STORE_close);
236

237
        if (ctx == nullptr) {
238
                return expected::unexpected(MakeError(
239
                        SetupError,
240
                        "Failed to load the private key from: " + args.private_key_path
241
                                + " error: " + GetOpenSSLErrorMessage()));
242
        }
243

244
        // Go through all objects in the context till we find the first private key
245
        while (not OSSL_STORE_eof(ctx.get())) {
246
                auto info = unique_ptr<OSSL_STORE_INFO, void (*)(OSSL_STORE_INFO *)>(
247
                        OSSL_STORE_load(ctx.get()), OSSL_STORE_INFO_free);
248

249
                if (info == nullptr) {
250
                        log::Error(
251
                                "Failed to load the the private key: " + args.private_key_path
252
                                + " trying the next object in the context: " + GetOpenSSLErrorMessage());
253
                        continue;
254
                }
255

256
                const int type_info {OSSL_STORE_INFO_get_type(info.get())};
257
                switch (type_info) {
258
                case OSSL_STORE_INFO_PKEY: {
259
                        // NOTE: get1 creates a duplicate of the pkey from the info, which can be
260
                        // used after the info ctx is destroyed
261
                        auto private_key = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(
262
                                OSSL_STORE_INFO_get1_PKEY(info.get()), pkey_free_func);
263
                        if (private_key == nullptr) {
264
                                return expected::unexpected(MakeError(
265
                                        SetupError,
266
                                        "Failed to load the private key: " + args.private_key_path
267
                                                + " error: " + GetOpenSSLErrorMessage()));
268
                        }
269

270
                        return PrivateKey(std::move(private_key));
271
                }
272
                default:
273
                        const string info_type_string = OSSL_STORE_INFO_type_string(type_info);
274
                        log::Debug("Unhandled OpenSSL type: expected PrivateKey, got: " + info_type_string);
275
                        continue;
276
                }
277
        }
278

279
        return expected::unexpected(
280
                MakeError(SetupError, "Failed to load the private key: " + GetOpenSSLErrorMessage()));
281
}
282
#endif // ndef MENDER_CRYPTO_OPENSSL_LEGACY
283

284
ExpectedPrivateKey PrivateKey::Load(const Args &args) {
37✔
285
        // Load OpenSSL config
286
        if ((CONF_modules_load_file(nullptr, nullptr, 0) != OPENSSL_SUCCESS)) {
37✔
287
                log::Warning("Failed to load OpenSSL configuration file: " + GetOpenSSLErrorMessage());
44✔
288
        }
289

290
        log::Trace("Loading private key");
74✔
291
        if (args.ssl_engine != "") {
37✔
292
                return LoadFromHSMEngine(args);
×
293
        }
294
        return LoadFrom(args);
37✔
295
}
296

297
ExpectedPrivateKey PrivateKey::Generate() {
7✔
298
        auto pkey_gen_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
299
                EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, nullptr), pkey_ctx_free_func);
14✔
300

301
        int ret = EVP_PKEY_keygen_init(pkey_gen_ctx.get());
7✔
302
        if (ret != OPENSSL_SUCCESS) {
7✔
303
                return expected::unexpected(MakeError(
×
304
                        SetupError,
305
                        "Failed to generate a private key. Initialization failed: "
306
                                + GetOpenSSLErrorMessage()));
×
307
        }
308
        EVP_PKEY *pkey = nullptr;
7✔
309
#ifdef MENDER_CRYPTO_OPENSSL_LEGACY
310
        // https://docs.openssl.org/master/man3/EVP_PKEY_keygen
311
        ret = EVP_PKEY_keygen(pkey_gen_ctx.get(), &pkey);
7✔
312
#else
313
        ret = EVP_PKEY_generate(pkey_gen_ctx.get(), &pkey);
314
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
315
        if (ret != OPENSSL_SUCCESS) {
7✔
UNCOV
316
                return expected::unexpected(MakeError(
×
317
                        SetupError,
UNCOV
318
                        "Failed to generate a private key. Generation failed: " + GetOpenSSLErrorMessage()));
×
319
        }
320

321
        auto private_key = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(pkey, pkey_free_func);
7✔
322
        return PrivateKey(std::move(private_key));
7✔
323
}
324

325
expected::ExpectedString EncodeBase64(vector<uint8_t> to_encode) {
14✔
326
        // Predict the len of the decoded for later verification. From man page:
327
        // For every 3 bytes of input provided 4 bytes of output
328
        // data will be produced. If n is not divisible by 3 (...)
329
        // the output is padded such that it is always divisible by 4.
330
        const uint64_t predicted_len {4 * ((to_encode.size() + 2) / 3)};
14✔
331

332
        // Add space for a NUL terminator. From man page:
333
        // Additionally a NUL terminator character will be added
334
        auto buffer {vector<unsigned char>(predicted_len + 1)};
14✔
335

336
        const int64_t output_len {
337
                EVP_EncodeBlock(buffer.data(), to_encode.data(), static_cast<int>(to_encode.size()))};
14✔
338
        assert(output_len >= 0);
339

340
        if (predicted_len != static_cast<uint64_t>(output_len)) {
14✔
341
                return expected::unexpected(
×
342
                        MakeError(Base64Error, "The predicted and the actual length differ"));
×
343
        }
344

345
        return string(buffer.begin(), buffer.end() - 1); // Remove the last zero byte
28✔
346
}
347

348
expected::ExpectedBytes DecodeBase64(string to_decode) {
15✔
349
        // Predict the len of the decoded for later verification. From man page:
350
        // For every 4 input bytes exactly 3 output bytes will be
351
        // produced. The output will be padded with 0 bits if necessary
352
        // to ensure that the output is always 3 bytes.
353
        const uint64_t predicted_len {3 * ((to_decode.size() + 3) / 4)};
15✔
354

355
        auto buffer {vector<unsigned char>(predicted_len)};
15✔
356

357
        const int64_t output_len {EVP_DecodeBlock(
15✔
358
                buffer.data(),
359
                common::ByteVectorFromString(to_decode).data(),
15✔
360
                static_cast<int>(to_decode.size()))};
15✔
361
        assert(output_len >= 0);
362

363
        if (predicted_len != static_cast<uint64_t>(output_len)) {
15✔
364
                return expected::unexpected(MakeError(
×
365
                        Base64Error,
366
                        "The predicted (" + std::to_string(predicted_len) + ") and the actual ("
×
367
                                + std::to_string(output_len) + ") length differ"));
×
368
        }
369

370
        // Subtract padding bytes. Inspired by internal OpenSSL code from:
371
        // https://github.com/openssl/openssl/blob/ff88545e02ab48a52952350c52013cf765455dd3/crypto/ct/ct_b64.c#L46
372
        for (auto it = to_decode.crbegin(); *it == '='; it++) {
24✔
373
                buffer.pop_back();
374
        }
375

376
        return buffer;
15✔
377
}
378

379

380
expected::ExpectedString ExtractPublicKey(const Args &args) {
9✔
381
        auto exp_private_key = PrivateKey::Load(args);
9✔
382
        if (!exp_private_key) {
9✔
383
                return expected::unexpected(exp_private_key.error());
2✔
384
        }
385

386
        auto bio_public_key = unique_ptr<BIO, void (*)(BIO *)>(BIO_new(BIO_s_mem()), bio_free_all_func);
16✔
387

388
        if (!bio_public_key.get()) {
8✔
389
                return expected::unexpected(MakeError(
×
390
                        SetupError,
391
                        "Failed to extract the public key from the private key " + args.private_key_path
×
392
                                + "):" + GetOpenSSLErrorMessage()));
×
393
        }
394

395
        int ret = PEM_write_bio_PUBKEY(bio_public_key.get(), exp_private_key.value().Get());
8✔
396
        if (ret != OPENSSL_SUCCESS) {
8✔
397
                return expected::unexpected(MakeError(
×
398
                        SetupError,
399
                        "Failed to extract the public key from the private key (" + args.private_key_path
×
400
                                + "): OpenSSL BIO write failed: " + GetOpenSSLErrorMessage()));
×
401
        }
402

403
        // NOTE: At this point we already have a public key available for extraction.
404
        // However, when using some providers in OpenSSL3 the external provider might
405
        // write the key in the old PKCS#1 format. The format is not deprecated, but
406
        // our older backends only understand the format if it is in the PKCS#8
407
        // (SubjectPublicKey) format:
408
        //
409
        // For us who don't speak OpenSSL:
410
        //
411
        // -- BEGIN RSA PUBLIC KEY -- <- PKCS#1 (old format)
412
        // -- BEGIN PUBLIC KEY -- <- PKCS#8 (new format - can hold different key types)
413

414

415
        auto evp_public_key = PkeyPtr(
416
                PEM_read_bio_PUBKEY(bio_public_key.get(), nullptr, nullptr, nullptr), pkey_free_func);
16✔
417

418
        if (evp_public_key == nullptr) {
8✔
419
                return expected::unexpected(MakeError(
×
420
                        SetupError,
421
                        "Failed to extract the public key from the private key " + args.private_key_path
×
422
                                + "):" + GetOpenSSLErrorMessage()));
×
423
        }
424

425
        auto bio_public_key_new =
426
                unique_ptr<BIO, void (*)(BIO *)>(BIO_new(BIO_s_mem()), bio_free_all_func);
16✔
427

428
        if (bio_public_key_new == nullptr) {
8✔
429
                return expected::unexpected(MakeError(
×
430
                        SetupError,
431
                        "Failed to extract the public key from the public key " + args.private_key_path
×
432
                                + "):" + GetOpenSSLErrorMessage()));
×
433
        }
434

435
        ret = PEM_write_bio_PUBKEY(bio_public_key_new.get(), evp_public_key.get());
8✔
436
        if (ret != OPENSSL_SUCCESS) {
8✔
437
                return expected::unexpected(MakeError(
×
438
                        SetupError,
439
                        "Failed to extract the public key from the private key: (" + args.private_key_path
×
440
                                + "): OpenSSL BIO write failed: " + GetOpenSSLErrorMessage()));
×
441
        }
442

443
        int pending = BIO_ctrl_pending(bio_public_key_new.get());
8✔
444
        if (pending <= 0) {
8✔
445
                return expected::unexpected(MakeError(
×
446
                        SetupError,
447
                        "Failed to extract the public key from bio ctrl: (" + args.private_key_path
×
448
                                + "): Zero byte key unexpected: " + GetOpenSSLErrorMessage()));
×
449
        }
450

451
        vector<uint8_t> key_vector(pending);
8✔
452

453
        size_t read = BIO_read(bio_public_key_new.get(), key_vector.data(), pending);
8✔
454

455
        if (read == 0) {
8✔
456
                MakeError(
×
457
                        SetupError,
458
                        "Failed to extract the public key from (" + args.private_key_path
×
459
                                + "): Zero bytes read from BIO: " + GetOpenSSLErrorMessage());
×
460
        }
461

462
        return string(key_vector.begin(), key_vector.end());
16✔
463
}
464

465
static expected::ExpectedBytes SignED25519(EVP_PKEY *pkey, const vector<uint8_t> &raw_data) {
2✔
466
        size_t sig_len;
467

468
        auto md_ctx = unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX *)>(EVP_MD_CTX_new(), EVP_MD_CTX_free);
4✔
469
        if (md_ctx == nullptr) {
2✔
470
                return expected::unexpected(MakeError(
×
471
                        SetupError, "Failed to initialize the OpenSSL md_ctx: " + GetOpenSSLErrorMessage()));
×
472
        }
473

474
        int ret {EVP_DigestSignInit(md_ctx.get(), nullptr, nullptr, nullptr, pkey)};
2✔
475
        if (ret != OPENSSL_SUCCESS) {
2✔
476
                return expected::unexpected(MakeError(
×
477
                        SetupError, "Failed to initialize the OpenSSL signature: " + GetOpenSSLErrorMessage()));
×
478
        }
479

480
        /* Calculate the required size for the signature by passing a nullptr buffer */
481
        ret = EVP_DigestSign(md_ctx.get(), nullptr, &sig_len, raw_data.data(), raw_data.size());
2✔
482
        if (ret != OPENSSL_SUCCESS) {
2✔
483
                return expected::unexpected(MakeError(
×
484
                        SetupError,
485
                        "Failed to find the required size of the signature buffer: "
486
                                + GetOpenSSLErrorMessage()));
×
487
        }
488

489
        vector<uint8_t> sig(sig_len);
2✔
490
        ret = EVP_DigestSign(md_ctx.get(), sig.data(), &sig_len, raw_data.data(), raw_data.size());
2✔
491
        if (ret != OPENSSL_SUCCESS) {
2✔
492
                return expected::unexpected(
×
493
                        MakeError(SetupError, "Failed to sign the message: " + GetOpenSSLErrorMessage()));
×
494
        }
495

496
        // The signature may in some cases be shorter than the previously allocated
497
        // length (which is the max)
498
        sig.resize(sig_len);
2✔
499

500
        return sig;
2✔
501
}
502

503
expected::ExpectedBytes SignGeneric(PrivateKey &private_key, const vector<uint8_t> &digest) {
8✔
504
        auto pkey_signer_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
505
                EVP_PKEY_CTX_new(private_key.Get(), nullptr), pkey_ctx_free_func);
16✔
506

507
        if (EVP_PKEY_sign_init(pkey_signer_ctx.get()) <= 0) {
8✔
508
                return expected::unexpected(MakeError(
×
509
                        SetupError, "Failed to initialize the OpenSSL signer: " + GetOpenSSLErrorMessage()));
×
510
        }
511
        if (EVP_PKEY_CTX_set_signature_md(pkey_signer_ctx.get(), EVP_sha256()) <= 0) {
8✔
512
                return expected::unexpected(MakeError(
×
513
                        SetupError,
514
                        "Failed to set the OpenSSL signature to sha256: " + GetOpenSSLErrorMessage()));
×
515
        }
516

517
        vector<uint8_t> signature {};
518

519
        // Set the needed signature buffer length
520
        size_t digestlength = MENDER_DIGEST_SHA256_LENGTH, siglength;
521
        if (EVP_PKEY_sign(pkey_signer_ctx.get(), nullptr, &siglength, digest.data(), digestlength)
8✔
522
                <= 0) {
523
                return expected::unexpected(MakeError(
×
524
                        SetupError, "Failed to get the signature buffer length: " + GetOpenSSLErrorMessage()));
×
525
        }
526
        signature.resize(siglength);
8✔
527

528
        if (EVP_PKEY_sign(
8✔
529
                        pkey_signer_ctx.get(), signature.data(), &siglength, digest.data(), digestlength)
530
                <= 0) {
531
                return expected::unexpected(
×
532
                        MakeError(SetupError, "Failed to sign the digest: " + GetOpenSSLErrorMessage()));
×
533
        }
534

535
        // The signature may in some cases be shorter than the previously allocated
536
        // length (which is the max)
537
        signature.resize(siglength);
8✔
538

539
        return signature;
8✔
540
}
541

542
expected::ExpectedBytes SignData(const Args &args, const vector<uint8_t> &raw_data) {
11✔
543
        auto exp_private_key = PrivateKey::Load(args);
11✔
544
        if (!exp_private_key) {
11✔
545
                return expected::unexpected(exp_private_key.error());
2✔
546
        }
547

548
        log::Info("Signing with: " + args.private_key_path);
10✔
549

550
        auto key_type = EVP_PKEY_base_id(exp_private_key.value().Get());
10✔
551

552
        // ED25519 signatures need to be handled independently, because of how the
553
        // signature scheme is designed.
554
        if (key_type == EVP_PKEY_ED25519) {
10✔
555
                return SignED25519(exp_private_key.value().Get(), raw_data);
2✔
556
        }
557

558
        auto exp_shasum = mender::sha::Shasum(raw_data);
8✔
559
        if (!exp_shasum) {
8✔
560
                return expected::unexpected(exp_shasum.error());
×
561
        }
562
        auto digest = exp_shasum.value(); /* The shasummed data = digest in crypto world */
8✔
563
        log::Debug("Shasum is: " + digest.String());
16✔
564

565
        return SignGeneric(exp_private_key.value(), digest);
16✔
566
}
567

568
expected::ExpectedString Sign(const Args &args, const vector<uint8_t> &raw_data) {
11✔
569
        auto exp_signed_data = SignData(args, raw_data);
11✔
570
        if (!exp_signed_data) {
11✔
571
                return expected::unexpected(exp_signed_data.error());
2✔
572
        }
573
        vector<uint8_t> signature = exp_signed_data.value();
10✔
574

575
        return EncodeBase64(signature);
20✔
576
}
577

578
const size_t mender_decode_buf_size = 256;
579
const size_t ecdsa256keySize = 32;
580

581
// Try and decode the keys from pure binary, assuming that the points on the
582
// curve (r,s), have been concatenated together (r || s), and simply dumped to
583
// binary. Which is what we did in the `mender-artifact` tool.
584
// (See MEN-1740) for some insight into previous issues, and the chosen fix.
585
static expected::ExpectedBytes TryASN1EncodeMenderCustomBinaryECFormat(
2✔
586
        const vector<uint8_t> &signature,
587
        const mender::sha::SHA &shasum,
588
        std::function<BIGNUM *(const unsigned char *signature, int length, BIGNUM *_unused)>
589
                BinaryDecoderFn) {
590
        // Verify that the marshalled keys match our expectation
591
        const size_t assumed_signature_size {2 * ecdsa256keySize};
592
        if (signature.size() > assumed_signature_size) {
2✔
593
                return expected::unexpected(MakeError(
×
594
                        SetupError,
595
                        "Unexpected size of the signature for ECDSA. Expected 2*" + to_string(ecdsa256keySize)
×
596
                                + " bytes. Got: " + to_string(signature.size())));
×
597
        }
598
        auto ecSig = unique_ptr<ECDSA_SIG, void (*)(ECDSA_SIG *)>(ECDSA_SIG_new(), ECDSA_SIG_free);
4✔
599
        if (ecSig == nullptr) {
2✔
600
                return expected::unexpected(MakeError(
×
601
                        SetupError,
602
                        "Failed to allocate the structure for the ECDSA signature: "
603
                                + GetOpenSSLErrorMessage()));
×
604
        }
605

606
        auto r = unique_ptr<BIGNUM, void (*)(BIGNUM *)>(
607
                BinaryDecoderFn(signature.data(), ecdsa256keySize, nullptr /* allocate new memory for r */),
608
                bn_free);
4✔
609
        if (r == nullptr) {
2✔
610
                return expected::unexpected(MakeError(
×
611
                        SetupError,
612
                        "Failed to extract the r(andom) part from the ECDSA signature in the binary representation: "
613
                                + GetOpenSSLErrorMessage()));
×
614
        }
615
        auto s = unique_ptr<BIGNUM, void (*)(BIGNUM *)>(
616
                BinaryDecoderFn(
617
                        signature.data() + ecdsa256keySize,
618
                        ecdsa256keySize,
619
                        nullptr /* allocate new memory for s */),
620
                bn_free);
4✔
621
        if (s == nullptr) {
2✔
622
                return expected::unexpected(MakeError(
×
623
                        SetupError,
624
                        "Failed to extract the s(ignature) part from the ECDSA signature in the binary representation: "
625
                                + GetOpenSSLErrorMessage()));
×
626
        }
627

628
        // Set the r&s values in the SIG struct
629
        // r & s now owned by ecSig
630
        int ret {ECDSA_SIG_set0(ecSig.get(), r.get(), s.get())};
2✔
631
        if (ret != OPENSSL_SUCCESS) {
2✔
632
                return expected::unexpected(MakeError(
×
633
                        SetupError,
634
                        "Failed to set the signature parts in the ECDSA structure: "
635
                                + GetOpenSSLErrorMessage()));
×
636
        }
637
        r.release();
638
        s.release();
639

640
        /* Allocate some array guaranteed to hold the DER-encoded structure */
641
        vector<uint8_t> der_encoded_byte_array(mender_decode_buf_size);
2✔
642
        unsigned char *arr_p = &der_encoded_byte_array[0];
2✔
643
        int len = i2d_ECDSA_SIG(ecSig.get(), &arr_p);
2✔
644
        if (len < 0) {
2✔
645
                return expected::unexpected(MakeError(
×
646
                        SetupError,
647
                        "Failed to set the signature parts in the ECDSA structure: "
648
                                + GetOpenSSLErrorMessage()));
×
649
        }
650
        /* Resize to the actual size of the DER-encoded signature */
651
        der_encoded_byte_array.resize(len);
2✔
652

653
        return der_encoded_byte_array;
2✔
654
}
655

656

657
expected::ExpectedBool VerifySignData(
658
        const string &public_key_path,
659
        const mender::sha::SHA &shasum,
660
        const vector<uint8_t> &signature);
661

662
static expected::ExpectedBool VerifyECDSASignData(
2✔
663
        const string &public_key_path,
664
        const mender::sha::SHA &shasum,
665
        const vector<uint8_t> &signature) {
666
        expected::ExpectedBytes exp_der_encoded_signature =
667
                TryASN1EncodeMenderCustomBinaryECFormat(signature, shasum, BN_bin2bn)
4✔
668
                        .or_else([&signature, &shasum](error::Error big_endian_error) {
×
669
                                log::Debug(
×
670
                                        "Failed to decode the signature binary blob from our custom binary format assuming the big-endian encoding, error: "
671
                                        + big_endian_error.String()
×
672
                                        + " falling back and trying anew assuming it is little-endian encoded: ");
×
673
                                return TryASN1EncodeMenderCustomBinaryECFormat(signature, shasum, BN_lebin2bn);
×
674
                        });
2✔
675
        if (!exp_der_encoded_signature) {
2✔
676
                return expected::unexpected(
×
677
                        MakeError(VerificationError, exp_der_encoded_signature.error().message));
×
678
        }
679

680
        vector<uint8_t> der_encoded_signature = exp_der_encoded_signature.value();
2✔
681

682
        return VerifySignData(public_key_path, shasum, der_encoded_signature);
2✔
683
}
684

685
static bool OpenSSLSignatureVerificationError(int a) {
686
        /*
687
         * The signature check errored. This is different from the signature being
688
         * wrong. We simply were not able to perform the check in this instance.
689
         * Therefore, we fall back to trying the custom marshalled binary ECDSA
690
         * signature, which we have been using in Mender.
691
         */
692
        return a < 0;
693
}
694

695
expected::ExpectedBool VerifySignData(
16✔
696
        const string &public_key_path,
697
        const mender::sha::SHA &shasum,
698
        const vector<uint8_t> &signature) {
699
        auto bio_key =
700
                unique_ptr<BIO, void (*)(BIO *)>(BIO_new_file(public_key_path.c_str(), "r"), bio_free_func);
32✔
701
        if (bio_key == nullptr) {
16✔
702
                return expected::unexpected(MakeError(
3✔
703
                        SetupError,
704
                        "Failed to open the public key file from (" + public_key_path
6✔
705
                                + "):" + GetOpenSSLErrorMessage()));
15✔
706
        }
707

708
        auto pkey = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(
709
                PEM_read_bio_PUBKEY(bio_key.get(), nullptr, nullptr, nullptr), pkey_free_func);
26✔
710
        if (pkey == nullptr) {
13✔
711
                return expected::unexpected(MakeError(
2✔
712
                        SetupError,
713
                        "Failed to load the public key from(" + public_key_path
4✔
714
                                + "): " + GetOpenSSLErrorMessage()));
10✔
715
        }
716

717
        auto pkey_signer_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
718
                EVP_PKEY_CTX_new(pkey.get(), nullptr), pkey_ctx_free_func);
22✔
719

720
        auto ret = EVP_PKEY_verify_init(pkey_signer_ctx.get());
11✔
721
        if (ret <= 0) {
11✔
722
                return expected::unexpected(MakeError(
×
723
                        SetupError, "Failed to initialize the OpenSSL signer: " + GetOpenSSLErrorMessage()));
×
724
        }
725
        ret = EVP_PKEY_CTX_set_signature_md(pkey_signer_ctx.get(), EVP_sha256());
11✔
726
        if (ret <= 0) {
11✔
727
                return expected::unexpected(MakeError(
×
728
                        SetupError,
729
                        "Failed to set the OpenSSL signature to sha256: " + GetOpenSSLErrorMessage()));
×
730
        }
731

732
        // verify signature
733
        ret = EVP_PKEY_verify(
11✔
734
                pkey_signer_ctx.get(), signature.data(), signature.size(), shasum.data(), shasum.size());
735
        if (OpenSSLSignatureVerificationError(ret)) {
11✔
736
                log::Debug(
2✔
737
                        "Failed to verify the signature with the supported OpenSSL binary formats. Falling back to the custom Mender encoded binary format for ECDSA signatures: "
738
                        + GetOpenSSLErrorMessage());
4✔
739
                return VerifyECDSASignData(public_key_path, shasum, signature);
2✔
740
        }
741
        if (ret == OPENSSL_SUCCESS) {
9✔
742
                return true;
743
        }
744
        /* This is the case where ret == 0. The signature is simply wrong */
745
        return false;
746
}
747

748
expected::ExpectedBool VerifySign(
14✔
749
        const string &public_key_path, const mender::sha::SHA &shasum, const string &signature) {
750
        // signature: decode base64
751
        auto exp_decoded_signature = DecodeBase64(signature);
28✔
752
        if (!exp_decoded_signature) {
14✔
753
                return expected::unexpected(exp_decoded_signature.error());
×
754
        }
755
        auto decoded_signature = exp_decoded_signature.value();
14✔
756

757
        return VerifySignData(public_key_path, shasum, decoded_signature);
14✔
758
}
759

760
error::Error PrivateKey::SaveToPEM(const string &private_key_path) {
6✔
761
        auto bio_key = unique_ptr<BIO, void (*)(BIO *)>(
762
                BIO_new_file(private_key_path.c_str(), "w"), bio_free_func);
12✔
763
        if (bio_key == nullptr) {
6✔
764
                return MakeError(
765
                        SetupError,
766
                        "Failed to open the private key file (" + private_key_path
2✔
767
                                + "): " + GetOpenSSLErrorMessage());
4✔
768
        }
769

770
        auto ret =
771
                PEM_write_bio_PrivateKey(bio_key.get(), key.get(), nullptr, nullptr, 0, nullptr, nullptr);
5✔
772
        if (ret != OPENSSL_SUCCESS) {
5✔
773
                return MakeError(
774
                        SetupError,
775
                        "Failed to save the private key to file (" + private_key_path
×
776
                                + "): " + GetOpenSSLErrorMessage());
×
777
        }
778

779
        return error::NoError;
5✔
780
}
781

782
} // namespace crypto
783
} // namespace common
784
} // namespace mender
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc