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

mendersoftware / mender / 2271300743

19 Jan 2026 11:42AM UTC coverage: 81.376% (+1.7%) from 79.701%
2271300743

push

gitlab-ci

web-flow
Merge pull request #1879 from lluiscampos/MEN-8687-ci-debian-updates

MEN-8687: Update Debian base images for CI jobs

8791 of 10803 relevant lines covered (81.38%)

20310.08 hits per line

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

64.74
/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 <cerrno>
20
#include <cstdint>
21
#include <string>
22
#include <vector>
23
#include <memory>
24

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

36
#include <openssl/evp.h>
37
#include <openssl/conf.h>
38
#include <openssl/pem.h>
39
#include <openssl/rsa.h>
40

41
#include <common/io.hpp>
42
#include <common/error.hpp>
43
#include <common/expected.hpp>
44
#include <common/common.hpp>
45
#include <common/path.hpp>
46

47
#include <artifact/sha/sha.hpp>
48

49

50
namespace mender {
51
namespace common {
52
namespace crypto {
53

54
const size_t MENDER_DIGEST_SHA256_LENGTH = 32;
55

56
const size_t OPENSSL_SUCCESS = 1;
57

58
using namespace std;
59

60
namespace error = mender::common::error;
61
namespace io = mender::common::io;
62
namespace path = mender::common::path;
63

64
using EnginePtr = unique_ptr<ENGINE, void (*)(ENGINE *)>;
65
#ifndef MENDER_CRYPTO_OPENSSL_LEGACY
66
using ProviderPtr = unique_ptr<OSSL_PROVIDER, int (*)(OSSL_PROVIDER *)>;
67
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
68

69
class OpenSSLResourceHandle {
×
70
public:
71
        EnginePtr engine;
72
};
73

74
auto resource_handle_free_func = [](OpenSSLResourceHandle *h) {
×
75
        if (h) {
×
76
                delete h;
×
77
        }
78
};
×
79

80
auto pkey_ctx_free_func = [](EVP_PKEY_CTX *ctx) {
29✔
81
        if (ctx) {
29✔
82
                EVP_PKEY_CTX_free(ctx);
29✔
83
        }
84
};
29✔
85
auto pkey_free_func = [](EVP_PKEY *key) {
62✔
86
        if (key) {
62✔
87
                EVP_PKEY_free(key);
62✔
88
        }
89
};
62✔
90
auto bio_free_func = [](BIO *bio) {
19✔
91
        if (bio) {
19✔
92
                BIO_free(bio);
19✔
93
        }
94
};
19✔
95
auto bio_free_all_func = [](BIO *bio) {
22✔
96
        if (bio) {
22✔
97
                BIO_free_all(bio);
22✔
98
        }
99
};
22✔
100
auto bn_free = [](BIGNUM *bn) {
×
101
        if (bn) {
×
102
                BN_free(bn);
×
103
        }
104
};
×
105
auto engine_free_func = [](ENGINE *e) {
×
106
        if (e) {
×
107
                ENGINE_free(e);
×
108
        }
109
};
×
110

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

116
        if (u == nullptr) {
3✔
117
                return 0;
118
        }
119

120
        // NB: buf is not expected to be null terminated.
121
        char *const pass = static_cast<char *>(u);
122
        strncpy(buf, pass, size);
3✔
123

124
        return static_cast<int>(strnlen(pass, size));
3✔
125
};
126

127

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

136
        std::string errorDescription {};
137
        while (sslErrorCode != 0) {
54✔
138
                if (!errorDescription.empty()) {
30✔
139
                        errorDescription += '\n';
140
                }
141
                errorDescription += ERR_error_string(sslErrorCode, nullptr);
30✔
142
                sslErrorCode = ERR_get_error();
30✔
143
        }
144
        if (sysErrorCode != 0) {
24✔
145
                if (!errorDescription.empty()) {
22✔
146
                        errorDescription += '\n';
147
                }
148
                errorDescription += "System error, code=" + std::to_string(sysErrorCode);
22✔
149
                errorDescription += ", ";
22✔
150
                errorDescription += strerror(sysErrorCode);
22✔
151
        }
152
        return errorDescription;
24✔
153
}
154

155
ExpectedPrivateKey LoadFromHSMEngine(const Args &args) {
×
156
        log::Trace("Loading the private key from HSM");
×
157

158
        ENGINE_load_builtin_engines();
×
159
        auto engine = EnginePtr(ENGINE_by_id(args.ssl_engine.c_str()), engine_free_func);
×
160

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

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

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

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

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

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

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

219
        return std::make_unique<PrivateKey>(std::move(private_key));
220
}
221
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
222

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

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

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

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

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

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

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

284
ExpectedPrivateKey PrivateKey::Load(const Args &args) {
43✔
285
        // Numerous internal OpenSSL functions call OPENSSL_init_ssl().
286
        // Therefore, in order to perform nondefault initialisation,
287
        // OPENSSL_init_ssl() MUST be called by application code prior to any other OpenSSL function
288
        // calls. See: https://docs.openssl.org/3.3/man3/OPENSSL_init_ssl/#description
289
        if (OPENSSL_init_ssl(0, nullptr) != OPENSSL_SUCCESS) {
43✔
290
                log::Warning("Error initializing libssl: " + GetOpenSSLErrorMessage());
×
291
        }
292
        // Load OpenSSL config
293
        if (CONF_modules_load_file(nullptr, nullptr, 0) != OPENSSL_SUCCESS) {
43✔
294
                log::Warning("Failed to load OpenSSL configuration file: " + GetOpenSSLErrorMessage());
×
295
        }
296

297
        log::Trace("Loading private key");
43✔
298
        if (args.ssl_engine != "") {
43✔
299
                return LoadFromHSMEngine(args);
×
300
        }
301
        // Try to make sure the key has the right permissions and warn if there was
302
        // a change (MEN-7752), but try to load it in any case (it may not even be a
303
        // file on the file system).
304
        if (common::StartsWith<string>(args.private_key_path, "/")) {
43✔
305
                auto err = path::Permissions(
8✔
306
                        args.private_key_path,
307
                        {path::Perms::Owner_read, path::Perms::Owner_write},
308
                        path::WarnMode::WarnOnChange);
8✔
309
                if (err != error::NoError) {
8✔
310
                        log::Warning(
3✔
311
                                "Failed to fix permissions of the private key file '" + args.private_key_path
3✔
312
                                + "': " + err.String());
9✔
313
                }
314
        }
315
        return LoadFrom(args);
43✔
316
}
317

318
ExpectedPrivateKey PrivateKey::Generate() {
7✔
319
#ifdef MENDER_CRYPTO_OPENSSL_LEGACY
320
        auto pkey_gen_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
321
                EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, nullptr), pkey_ctx_free_func);
322
#else
323
        auto pkey_gen_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
324
                EVP_PKEY_CTX_new_from_name(nullptr, "ED25519", nullptr), pkey_ctx_free_func);
7✔
325
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
326

327
        int ret = EVP_PKEY_keygen_init(pkey_gen_ctx.get());
7✔
328
        if (ret != OPENSSL_SUCCESS) {
7✔
329
                return expected::unexpected(MakeError(
×
330
                        SetupError,
331
                        "Failed to generate a private key. Initialization failed: "
332
                                + GetOpenSSLErrorMessage()));
×
333
        }
334
        EVP_PKEY *pkey = nullptr;
7✔
335
#ifdef MENDER_CRYPTO_OPENSSL_LEGACY
336
        ret = EVP_PKEY_keygen(pkey_gen_ctx.get(), &pkey);
337
#else
338
        ret = EVP_PKEY_generate(pkey_gen_ctx.get(), &pkey);
7✔
339
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
340
        if (ret != OPENSSL_SUCCESS) {
7✔
341
                return expected::unexpected(MakeError(
×
342
                        SetupError,
343
                        "Failed to generate a private key. Generation failed: " + GetOpenSSLErrorMessage()));
×
344
        }
345

346
        auto private_key = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(pkey, pkey_free_func);
7✔
347
        return std::make_unique<PrivateKey>(std::move(private_key));
7✔
348
}
7✔
349

350
expected::ExpectedString EncodeBase64(vector<uint8_t> to_encode) {
17✔
351
        // Predict the len of the decoded for later verification. From man page:
352
        // For every 3 bytes of input provided 4 bytes of output
353
        // data will be produced. If n is not divisible by 3 (...)
354
        // the output is padded such that it is always divisible by 4.
355
        const size_t predicted_len {4 * ((to_encode.size() + 2) / 3)};
17✔
356

357
        // Add space for a NUL terminator. From man page:
358
        // Additionally a NUL terminator character will be added
359
        auto buffer {vector<unsigned char>(predicted_len + 1)};
17✔
360

361
        const int64_t output_len {
362
                EVP_EncodeBlock(buffer.data(), to_encode.data(), static_cast<int>(to_encode.size()))};
17✔
363
        assert(output_len >= 0);
364

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

370
        return string(buffer.begin(), buffer.end() - 1); // Remove the last zero byte
34✔
371
}
372

373
expected::ExpectedBytes DecodeBase64(string to_decode) {
15✔
374
        // Predict the len of the decoded for later verification. From man page:
375
        // For every 4 input bytes exactly 3 output bytes will be
376
        // produced. The output will be padded with 0 bits if necessary
377
        // to ensure that the output is always 3 bytes.
378
        const size_t predicted_len {3 * ((to_decode.size() + 3) / 4)};
15✔
379

380
        auto buffer {vector<unsigned char>(predicted_len)};
15✔
381

382
        const int64_t output_len {EVP_DecodeBlock(
15✔
383
                buffer.data(),
384
                common::ByteVectorFromString(to_decode).data(),
15✔
385
                static_cast<int>(to_decode.size()))};
15✔
386
        assert(output_len >= 0);
387

388
        if (predicted_len != static_cast<uint64_t>(output_len)) {
15✔
389
                return expected::unexpected(MakeError(
×
390
                        Base64Error,
391
                        "The predicted (" + std::to_string(predicted_len) + ") and the actual ("
×
392
                                + std::to_string(output_len) + ") length differ"));
×
393
        }
394

395
        // Subtract padding bytes. Inspired by internal OpenSSL code from:
396
        // https://github.com/openssl/openssl/blob/ff88545e02ab48a52952350c52013cf765455dd3/crypto/ct/ct_b64.c#L46
397
        for (auto it = to_decode.crbegin(); *it == '='; it++) {
24✔
398
                buffer.pop_back();
399
        }
400

401
        return buffer;
15✔
402
}
403

404

405
expected::ExpectedString ExtractPublicKey(const Args &args) {
12✔
406
        auto exp_private_key = PrivateKey::Load(args);
12✔
407
        if (!exp_private_key) {
12✔
408
                return expected::unexpected(exp_private_key.error());
2✔
409
        }
410

411
        auto bio_public_key = unique_ptr<BIO, void (*)(BIO *)>(BIO_new(BIO_s_mem()), bio_free_all_func);
11✔
412

413
        if (!bio_public_key.get()) {
11✔
414
                return expected::unexpected(MakeError(
×
415
                        SetupError,
416
                        "Failed to extract the public key from the private key " + args.private_key_path
×
417
                                + "):" + GetOpenSSLErrorMessage()));
×
418
        }
419

420
        int ret = PEM_write_bio_PUBKEY(bio_public_key.get(), exp_private_key.value()->Get());
11✔
421
        if (ret != OPENSSL_SUCCESS) {
11✔
422
                return expected::unexpected(MakeError(
×
423
                        SetupError,
424
                        "Failed to extract the public key from the private key (" + args.private_key_path
×
425
                                + "): OpenSSL BIO write failed: " + GetOpenSSLErrorMessage()));
×
426
        }
427

428
        // NOTE: At this point we already have a public key available for extraction.
429
        // However, when using some providers in OpenSSL3 the external provider might
430
        // write the key in the old PKCS#1 format. The format is not deprecated, but
431
        // our older backends only understand the format if it is in the PKCS#8
432
        // (SubjectPublicKey) format:
433
        //
434
        // For us who don't speak OpenSSL:
435
        //
436
        // -- BEGIN RSA PUBLIC KEY -- <- PKCS#1 (old format)
437
        // -- BEGIN PUBLIC KEY -- <- PKCS#8 (new format - can hold different key types)
438

439

440
        auto evp_public_key = PkeyPtr(
441
                PEM_read_bio_PUBKEY(bio_public_key.get(), nullptr, nullptr, nullptr), pkey_free_func);
11✔
442

443
        if (evp_public_key == nullptr) {
11✔
444
                return expected::unexpected(MakeError(
×
445
                        SetupError,
446
                        "Failed to extract the public key from the private key " + args.private_key_path
×
447
                                + "):" + GetOpenSSLErrorMessage()));
×
448
        }
449

450
        auto bio_public_key_new =
451
                unique_ptr<BIO, void (*)(BIO *)>(BIO_new(BIO_s_mem()), bio_free_all_func);
11✔
452

453
        if (bio_public_key_new == nullptr) {
11✔
454
                return expected::unexpected(MakeError(
×
455
                        SetupError,
456
                        "Failed to extract the public key from the public key " + args.private_key_path
×
457
                                + "):" + GetOpenSSLErrorMessage()));
×
458
        }
459

460
        ret = PEM_write_bio_PUBKEY(bio_public_key_new.get(), evp_public_key.get());
11✔
461
        if (ret != OPENSSL_SUCCESS) {
11✔
462
                return expected::unexpected(MakeError(
×
463
                        SetupError,
464
                        "Failed to extract the public key from the private key: (" + args.private_key_path
×
465
                                + "): OpenSSL BIO write failed: " + GetOpenSSLErrorMessage()));
×
466
        }
467

468
        // Inconsistent API, this returns size_t, but the API below uses int. Should not matter for
469
        // key sizes though.
470
        int pending = static_cast<int>(BIO_ctrl_pending(bio_public_key_new.get()));
11✔
471
        if (pending <= 0) {
11✔
472
                return expected::unexpected(MakeError(
×
473
                        SetupError,
474
                        "Failed to extract the public key from bio ctrl: (" + args.private_key_path
×
475
                                + "): Zero byte key unexpected: " + GetOpenSSLErrorMessage()));
×
476
        }
477

478
        vector<uint8_t> key_vector(pending);
11✔
479

480
        size_t read = BIO_read(bio_public_key_new.get(), key_vector.data(), pending);
11✔
481

482
        if (read == 0) {
11✔
483
                MakeError(
×
484
                        SetupError,
485
                        "Failed to extract the public key from (" + args.private_key_path
×
486
                                + "): Zero bytes read from BIO: " + GetOpenSSLErrorMessage());
×
487
        }
488

489
        return string(key_vector.begin(), key_vector.end());
22✔
490
}
11✔
491

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

495
        auto md_ctx = unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX *)>(EVP_MD_CTX_new(), EVP_MD_CTX_free);
2✔
496
        if (md_ctx == nullptr) {
2✔
497
                return expected::unexpected(MakeError(
×
498
                        SetupError, "Failed to initialize the OpenSSL md_ctx: " + GetOpenSSLErrorMessage()));
×
499
        }
500

501
        int ret {EVP_DigestSignInit(md_ctx.get(), nullptr, nullptr, nullptr, pkey)};
2✔
502
        if (ret != OPENSSL_SUCCESS) {
2✔
503
                return expected::unexpected(MakeError(
×
504
                        SetupError, "Failed to initialize the OpenSSL signature: " + GetOpenSSLErrorMessage()));
×
505
        }
506

507
        /* Calculate the required size for the signature by passing a nullptr buffer */
508
        ret = EVP_DigestSign(md_ctx.get(), nullptr, &sig_len, raw_data.data(), raw_data.size());
2✔
509
        if (ret != OPENSSL_SUCCESS) {
2✔
510
                return expected::unexpected(MakeError(
×
511
                        SetupError,
512
                        "Failed to find the required size of the signature buffer: "
513
                                + GetOpenSSLErrorMessage()));
×
514
        }
515

516
        vector<uint8_t> sig(sig_len);
2✔
517
        ret = EVP_DigestSign(md_ctx.get(), sig.data(), &sig_len, raw_data.data(), raw_data.size());
2✔
518
        if (ret != OPENSSL_SUCCESS) {
2✔
519
                return expected::unexpected(
×
520
                        MakeError(SetupError, "Failed to sign the message: " + GetOpenSSLErrorMessage()));
×
521
        }
522

523
        // The signature may in some cases be shorter than the previously allocated
524
        // length (which is the max)
525
        sig.resize(sig_len);
2✔
526

527
        return sig;
2✔
528
}
2✔
529

530
expected::ExpectedBytes SignGeneric(
11✔
531
        std::unique_ptr<PrivateKey> &&private_key, const vector<uint8_t> &digest) {
532
        auto pkey_signer_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
533
                EVP_PKEY_CTX_new(private_key->Get(), nullptr), pkey_ctx_free_func);
11✔
534

535
        if (EVP_PKEY_sign_init(pkey_signer_ctx.get()) <= 0) {
11✔
536
                return expected::unexpected(MakeError(
×
537
                        SetupError, "Failed to initialize the OpenSSL signer: " + GetOpenSSLErrorMessage()));
×
538
        }
539
        if (EVP_PKEY_CTX_set_signature_md(pkey_signer_ctx.get(), EVP_sha256()) <= 0) {
11✔
540
                return expected::unexpected(MakeError(
×
541
                        SetupError,
542
                        "Failed to set the OpenSSL signature to sha256: " + GetOpenSSLErrorMessage()));
×
543
        }
544

545
        vector<uint8_t> signature {};
546

547
        // Set the needed signature buffer length
548
        size_t digestlength = MENDER_DIGEST_SHA256_LENGTH, siglength;
549
        if (EVP_PKEY_sign(pkey_signer_ctx.get(), nullptr, &siglength, digest.data(), digestlength)
11✔
550
                <= 0) {
551
                return expected::unexpected(MakeError(
×
552
                        SetupError, "Failed to get the signature buffer length: " + GetOpenSSLErrorMessage()));
×
553
        }
554
        signature.resize(siglength);
11✔
555

556
        if (EVP_PKEY_sign(
11✔
557
                        pkey_signer_ctx.get(), signature.data(), &siglength, digest.data(), digestlength)
558
                <= 0) {
559
                return expected::unexpected(
×
560
                        MakeError(SetupError, "Failed to sign the digest: " + GetOpenSSLErrorMessage()));
×
561
        }
562

563
        // The signature may in some cases be shorter than the previously allocated
564
        // length (which is the max)
565
        signature.resize(siglength);
11✔
566

567
        return signature;
11✔
568
}
11✔
569

570
expected::ExpectedBytes SignData(const Args &args, const vector<uint8_t> &raw_data) {
14✔
571
        auto exp_private_key = PrivateKey::Load(args);
14✔
572
        if (!exp_private_key) {
14✔
573
                return expected::unexpected(exp_private_key.error());
2✔
574
        }
575

576
        log::Info("Signing with: " + args.private_key_path);
13✔
577

578
        auto key_type = EVP_PKEY_base_id(exp_private_key.value()->Get());
13✔
579

580
        // ED25519 signatures need to be handled independently, because of how the
581
        // signature scheme is designed.
582
        if (key_type == EVP_PKEY_ED25519) {
13✔
583
                return SignED25519(exp_private_key.value()->Get(), raw_data);
2✔
584
        }
585

586
        auto exp_shasum = mender::sha::Shasum(raw_data);
11✔
587
        if (!exp_shasum) {
11✔
588
                return expected::unexpected(exp_shasum.error());
×
589
        }
590
        auto digest = exp_shasum.value(); /* The shasummed data = digest in crypto world */
11✔
591
        log::Debug("Shasum is: " + digest.String());
22✔
592

593
        return SignGeneric(std::move(exp_private_key.value()), digest);
22✔
594
}
595

596
expected::ExpectedString Sign(const Args &args, const vector<uint8_t> &raw_data) {
14✔
597
        auto exp_signed_data = SignData(args, raw_data);
14✔
598
        if (!exp_signed_data) {
14✔
599
                return expected::unexpected(exp_signed_data.error());
2✔
600
        }
601
        vector<uint8_t> signature = exp_signed_data.value();
13✔
602

603
        return EncodeBase64(signature);
26✔
604
}
605

606
const size_t ecdsa256keySize = 32;
607

608
// Try and decode the keys from pure binary, assuming that the points on the
609
// curve (r,s), have been concatenated together (r || s), and simply dumped to
610
// binary. Which is what we did in the `mender-artifact` tool.
611
// (See MEN-1740) for some insight into previous issues, and the chosen fix.
612
static expected::ExpectedBytes TryASN1EncodeMenderCustomBinaryECFormat(
2✔
613
        const vector<uint8_t> &signature,
614
        const mender::sha::SHA &shasum,
615
        std::function<BIGNUM *(const unsigned char *signature, int length, BIGNUM *_unused)>
616
                BinaryDecoderFn) {
617
        // Verify that the marshalled keys match our expectation
618
        const size_t assumed_signature_size {2 * ecdsa256keySize};
619
        if (signature.size() != assumed_signature_size) {
2✔
620
                return expected::unexpected(MakeError(
×
621
                        SetupError,
622
                        "Unexpected size of the signature for ECDSA. Expected 2*" + to_string(ecdsa256keySize)
×
623
                                + " bytes. Got: " + to_string(signature.size())));
×
624
        }
625
        auto ecSig = unique_ptr<ECDSA_SIG, void (*)(ECDSA_SIG *)>(ECDSA_SIG_new(), ECDSA_SIG_free);
2✔
626
        if (ecSig == nullptr) {
2✔
627
                return expected::unexpected(MakeError(
×
628
                        SetupError,
629
                        "Failed to allocate the structure for the ECDSA signature: "
630
                                + GetOpenSSLErrorMessage()));
×
631
        }
632

633
        auto r = unique_ptr<BIGNUM, void (*)(BIGNUM *)>(
634
                BinaryDecoderFn(signature.data(), ecdsa256keySize, nullptr /* allocate new memory for r */),
635
                bn_free);
2✔
636
        if (r == nullptr) {
2✔
637
                return expected::unexpected(MakeError(
×
638
                        SetupError,
639
                        "Failed to extract the r(andom) part from the ECDSA signature in the binary representation: "
640
                                + GetOpenSSLErrorMessage()));
×
641
        }
642
        auto s = unique_ptr<BIGNUM, void (*)(BIGNUM *)>(
643
                BinaryDecoderFn(
644
                        signature.data() + ecdsa256keySize,
645
                        ecdsa256keySize,
646
                        nullptr /* allocate new memory for s */),
647
                bn_free);
2✔
648
        if (s == nullptr) {
2✔
649
                return expected::unexpected(MakeError(
×
650
                        SetupError,
651
                        "Failed to extract the s(ignature) part from the ECDSA signature in the binary representation: "
652
                                + GetOpenSSLErrorMessage()));
×
653
        }
654

655
        // Set the r&s values in the SIG struct
656
        // r & s now owned by ecSig
657
        int ret {ECDSA_SIG_set0(ecSig.get(), r.get(), s.get())};
2✔
658
        if (ret != OPENSSL_SUCCESS) {
2✔
659
                return expected::unexpected(MakeError(
×
660
                        SetupError,
661
                        "Failed to set the signature parts in the ECDSA structure: "
662
                                + GetOpenSSLErrorMessage()));
×
663
        }
664
        r.release();
665
        s.release();
666

667
        /* Get the expected length in bytes of the DER encoded signature */
668
        int len = i2d_ECDSA_SIG(ecSig.get(), NULL);
2✔
669
        if (len < 0) {
2✔
670
                return expected::unexpected(MakeError(
×
671
                        SetupError,
672
                        "Failed to set the signature parts in the ECDSA structure: "
673
                                + GetOpenSSLErrorMessage()));
×
674
        }
675

676
        /* Allocate an array guaranteed to hold the DER-encoded structure */
677
        vector<unsigned char> der_encoded_byte_array(len);
2✔
678
        unsigned char *arr_p = der_encoded_byte_array.data();
2✔
679
        len = i2d_ECDSA_SIG(ecSig.get(), &arr_p);
2✔
680
        if (len < 0) {
2✔
681
                return expected::unexpected(MakeError(
×
682
                        SetupError,
683
                        "Failed to set the signature parts in the ECDSA structure: "
684
                                + GetOpenSSLErrorMessage()));
×
685
        }
686
        return der_encoded_byte_array;
2✔
687
}
2✔
688

689

690
expected::ExpectedBool VerifySignData(
691
        const string &public_key_path,
692
        const mender::sha::SHA &shasum,
693
        const vector<uint8_t> &signature);
694

695
static expected::ExpectedBool VerifyECDSASignData(
2✔
696
        const string &public_key_path,
697
        const mender::sha::SHA &shasum,
698
        const vector<uint8_t> &signature) {
699
        expected::ExpectedBytes exp_der_encoded_signature =
700
                TryASN1EncodeMenderCustomBinaryECFormat(signature, shasum, BN_bin2bn)
4✔
701
                        .or_else([&signature, &shasum](error::Error big_endian_error) {
2✔
702
                                log::Debug(
×
703
                                        "Failed to decode the signature binary blob from our custom binary format assuming the big-endian encoding, error: "
704
                                        + big_endian_error.String()
×
705
                                        + " falling back and trying anew assuming it is little-endian encoded: ");
×
706
                                return TryASN1EncodeMenderCustomBinaryECFormat(signature, shasum, BN_lebin2bn);
×
707
                        });
708
        if (!exp_der_encoded_signature) {
2✔
709
                return expected::unexpected(
×
710
                        MakeError(VerificationError, exp_der_encoded_signature.error().message));
×
711
        }
712

713
        vector<uint8_t> der_encoded_signature = exp_der_encoded_signature.value();
2✔
714

715
        return VerifySignData(public_key_path, shasum, der_encoded_signature);
2✔
716
}
717

718
static bool OpenSSLSignatureVerificationError(int a) {
719
        /*
720
         * The signature check errored. This is different from the signature being
721
         * wrong. We simply were not able to perform the check in this instance.
722
         * Therefore, we fall back to trying the custom marshalled binary ECDSA
723
         * signature, which we have been using in Mender.
724
         */
725
        return a < 0;
726
}
727

728
expected::ExpectedBool VerifySignData(
16✔
729
        const string &public_key_path,
730
        const mender::sha::SHA &shasum,
731
        const vector<uint8_t> &signature) {
732
        auto bio_key =
733
                unique_ptr<BIO, void (*)(BIO *)>(BIO_new_file(public_key_path.c_str(), "r"), bio_free_func);
16✔
734
        if (bio_key == nullptr) {
16✔
735
                return expected::unexpected(MakeError(
3✔
736
                        SetupError,
737
                        "Failed to open the public key file from (" + public_key_path
3✔
738
                                + "):" + GetOpenSSLErrorMessage()));
12✔
739
        }
740

741
        auto pkey = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(
742
                PEM_read_bio_PUBKEY(bio_key.get(), nullptr, nullptr, nullptr), pkey_free_func);
13✔
743
        if (pkey == nullptr) {
13✔
744
                return expected::unexpected(MakeError(
2✔
745
                        SetupError,
746
                        "Failed to load the public key from(" + public_key_path
2✔
747
                                + "): " + GetOpenSSLErrorMessage()));
8✔
748
        }
749

750
        auto pkey_signer_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
751
                EVP_PKEY_CTX_new(pkey.get(), nullptr), pkey_ctx_free_func);
11✔
752

753
        auto ret = EVP_PKEY_verify_init(pkey_signer_ctx.get());
11✔
754
        if (ret <= 0) {
11✔
755
                return expected::unexpected(MakeError(
×
756
                        SetupError, "Failed to initialize the OpenSSL signer: " + GetOpenSSLErrorMessage()));
×
757
        }
758
        ret = EVP_PKEY_CTX_set_signature_md(pkey_signer_ctx.get(), EVP_sha256());
11✔
759
        if (ret <= 0) {
11✔
760
                return expected::unexpected(MakeError(
×
761
                        SetupError,
762
                        "Failed to set the OpenSSL signature to sha256: " + GetOpenSSLErrorMessage()));
×
763
        }
764

765
        // verify signature
766
        ret = EVP_PKEY_verify(
11✔
767
                pkey_signer_ctx.get(), signature.data(), signature.size(), shasum.data(), shasum.size());
768
        if (OpenSSLSignatureVerificationError(ret)) {
11✔
769
                log::Debug(
2✔
770
                        "Failed to verify the signature with the supported OpenSSL binary formats. Falling back to the custom Mender encoded binary format for ECDSA signatures: "
771
                        + GetOpenSSLErrorMessage());
2✔
772
                return VerifyECDSASignData(public_key_path, shasum, signature);
2✔
773
        }
774
        if (ret == OPENSSL_SUCCESS) {
9✔
775
                return true;
776
        }
777
        /* This is the case where ret == 0. The signature is simply wrong */
778
        return false;
779
}
16✔
780

781
expected::ExpectedBool VerifySign(
14✔
782
        const string &public_key_path, const mender::sha::SHA &shasum, const string &signature) {
783
        // signature: decode base64
784
        auto exp_decoded_signature = DecodeBase64(signature);
28✔
785
        if (!exp_decoded_signature) {
14✔
786
                return expected::unexpected(exp_decoded_signature.error());
×
787
        }
788
        auto decoded_signature = exp_decoded_signature.value();
14✔
789

790
        return VerifySignData(public_key_path, shasum, decoded_signature);
14✔
791
}
792

793
error::Error PrivateKey::SaveToPEM(const string &private_key_path) {
7✔
794
        if (path::FileExists(private_key_path)) {
7✔
795
                auto err = path::FileDelete(private_key_path);
3✔
796
                if (err != error::NoError) {
3✔
797
                        log::Debug(
×
798
                                "Failed to delete the private key fie '" + private_key_path + "': " + err.String());
×
799
                }
800
        }
801
        auto ex_fd =
802
                path::FileCreate(private_key_path, {path::Perms::Owner_read, path::Perms::Owner_write});
14✔
803
        if (!ex_fd) {
7✔
804
                auto &err = ex_fd.error();
805
                return err.FollowedBy(MakeError(
1✔
806
                        SetupError, "Failed to create the private key file '" + private_key_path + "'"));
3✔
807
        }
808
        auto bio_key =
809
                unique_ptr<BIO, void (*)(BIO *)>(BIO_new_fd(ex_fd.value(), BIO_CLOSE), bio_free_func);
6✔
810
        if (bio_key == nullptr) {
6✔
811
                return MakeError(
812
                        SetupError,
813
                        "Failed to open the private key file (" + private_key_path
×
814
                                + "): " + GetOpenSSLErrorMessage());
×
815
        }
816

817
        auto ret =
818
                PEM_write_bio_PrivateKey(bio_key.get(), key.get(), nullptr, nullptr, 0, nullptr, nullptr);
6✔
819
        if (ret != OPENSSL_SUCCESS) {
6✔
820
                return MakeError(
821
                        SetupError,
822
                        "Failed to save the private key to file (" + private_key_path
×
823
                                + "): " + GetOpenSSLErrorMessage());
×
824
        }
825

826
        return error::NoError;
6✔
827
}
6✔
828

829
} // namespace crypto
830
} // namespace common
831
} // 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