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

mendersoftware / mender / 1571619214

22 Nov 2024 10:07AM UTC coverage: 76.396% (+0.03%) from 76.364%
1571619214

push

gitlab-ci

web-flow
Merge pull request #1696 from vpodzime/master-priv_key_perms

Fix: Private key file permissions

35 of 40 new or added lines in 4 files covered. (87.5%)

2 existing lines in 1 file now uncovered.

7363 of 9638 relevant lines covered (76.4%)

11226.92 hits per line

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

63.95
/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) {
26✔
81
        if (ctx) {
26✔
82
                EVP_PKEY_CTX_free(ctx);
26✔
83
        }
84
};
26✔
85
auto pkey_free_func = [](EVP_PKEY *key) {
53✔
86
        if (key) {
53✔
87
                EVP_PKEY_free(key);
53✔
88
        }
89
};
53✔
90
auto bio_free_func = [](BIO *bio) {
50✔
91
        if (bio) {
50✔
92
                BIO_free(bio);
50✔
93
        }
94
};
50✔
95
auto bio_free_all_func = [](BIO *bio) {
16✔
96
        if (bio) {
16✔
97
                BIO_free_all(bio);
16✔
98
        }
99
};
16✔
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() {
17✔
133
        const auto sysErrorCode = errno;
17✔
134
        auto sslErrorCode = ERR_get_error();
17✔
135

136
        std::string errorDescription {};
137
        while (sslErrorCode != 0) {
56✔
138
                if (!errorDescription.empty()) {
39✔
139
                        errorDescription += '\n';
140
                }
141
                errorDescription += ERR_error_string(sslErrorCode, nullptr);
39✔
142
                sslErrorCode = ERR_get_error();
39✔
143
        }
144
        if (sysErrorCode != 0) {
17✔
145
                if (!errorDescription.empty()) {
15✔
146
                        errorDescription += '\n';
147
                }
148
                errorDescription += "System error, code=" + std::to_string(sysErrorCode);
30✔
149
                errorDescription += ", ";
15✔
150
                errorDescription += strerror(sysErrorCode);
15✔
151
        }
152
        return errorDescription;
17✔
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 PrivateKey(std::move(private_key), std::move(handle));
×
193
}
194

195
#ifdef MENDER_CRYPTO_OPENSSL_LEGACY
196
ExpectedPrivateKey LoadFrom(const Args &args) {
37✔
197
        log::Trace("Loading private key from file: " + args.private_key_path);
74✔
198
        auto private_bio_key = unique_ptr<BIO, void (*)(BIO *)>(
199
                BIO_new_file(args.private_key_path.c_str(), "r"), bio_free_func);
74✔
200
        if (private_bio_key == nullptr) {
37✔
201
                return expected::unexpected(MakeError(
6✔
202
                        SetupError,
203
                        "Failed to load the private key file " + args.private_key_path + ": "
12✔
204
                                + GetOpenSSLErrorMessage()));
30✔
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);
62✔
212
        if (private_key == nullptr) {
31✔
213
                return expected::unexpected(MakeError(
4✔
214
                        SetupError,
215
                        "Failed to load the private key: " + args.private_key_path + " "
8✔
216
                                + GetOpenSSLErrorMessage()));
20✔
217
        }
218

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

223
#ifndef MENDER_CRYPTO_OPENSSL_LEGACY
224
ExpectedPrivateKey LoadFrom(const Args &args) {
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);
237

238
        if (ctx == nullptr) {
239
                return expected::unexpected(MakeError(
240
                        SetupError,
241
                        "Failed to load the private key from: " + args.private_key_path
242
                                + " error: " + GetOpenSSLErrorMessage()));
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())) {
247
                auto info = unique_ptr<OSSL_STORE_INFO, void (*)(OSSL_STORE_INFO *)>(
248
                        OSSL_STORE_load(ctx.get()), OSSL_STORE_INFO_free);
249

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

257
                const int type_info {OSSL_STORE_INFO_get_type(info.get())};
258
                switch (type_info) {
259
                case OSSL_STORE_INFO_PKEY: {
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);
264
                        if (private_key == nullptr) {
265
                                return expected::unexpected(MakeError(
266
                                        SetupError,
267
                                        "Failed to load the private key: " + args.private_key_path
268
                                                + " error: " + GetOpenSSLErrorMessage()));
269
                        }
270

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

402
        return buffer;
15✔
403
}
404

405

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

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

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

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

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

440

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

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

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

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

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

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

479
        vector<uint8_t> key_vector(pending);
8✔
480

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

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

490
        return string(key_vector.begin(), key_vector.end());
16✔
491
}
492

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

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

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

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

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

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

528
        return sig;
2✔
529
}
530

531
expected::ExpectedBytes SignGeneric(PrivateKey &private_key, const vector<uint8_t> &digest) {
8✔
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);
16✔
534

535
        if (EVP_PKEY_sign_init(pkey_signer_ctx.get()) <= 0) {
8✔
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) {
8✔
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)
8✔
550
                <= 0) {
551
                return expected::unexpected(MakeError(
×
552
                        SetupError, "Failed to get the signature buffer length: " + GetOpenSSLErrorMessage()));
×
553
        }
554
        signature.resize(siglength);
8✔
555

556
        if (EVP_PKEY_sign(
8✔
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);
8✔
566

567
        return signature;
8✔
568
}
569

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

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

578
        auto key_type = EVP_PKEY_base_id(exp_private_key.value().Get());
10✔
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) {
10✔
583
                return SignED25519(exp_private_key.value().Get(), raw_data);
2✔
584
        }
585

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

593
        return SignGeneric(exp_private_key.value(), digest);
16✔
594
}
595

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

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

606
const size_t mender_decode_buf_size = 256;
607
const size_t ecdsa256keySize = 32;
608

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

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

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

668
        /* Allocate some array guaranteed to hold the DER-encoded structure */
669
        vector<uint8_t> der_encoded_byte_array(mender_decode_buf_size);
2✔
670
        unsigned char *arr_p = &der_encoded_byte_array[0];
2✔
671
        int len = i2d_ECDSA_SIG(ecSig.get(), &arr_p);
2✔
672
        if (len < 0) {
2✔
673
                return expected::unexpected(MakeError(
×
674
                        SetupError,
675
                        "Failed to set the signature parts in the ECDSA structure: "
676
                                + GetOpenSSLErrorMessage()));
×
677
        }
678
        /* Resize to the actual size of the DER-encoded signature */
679
        der_encoded_byte_array.resize(len);
2✔
680

681
        return der_encoded_byte_array;
2✔
682
}
683

684

685
expected::ExpectedBool VerifySignData(
686
        const string &public_key_path,
687
        const mender::sha::SHA &shasum,
688
        const vector<uint8_t> &signature);
689

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

708
        vector<uint8_t> der_encoded_signature = exp_der_encoded_signature.value();
2✔
709

710
        return VerifySignData(public_key_path, shasum, der_encoded_signature);
2✔
711
}
712

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

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

736
        auto pkey = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(
737
                PEM_read_bio_PUBKEY(bio_key.get(), nullptr, nullptr, nullptr), pkey_free_func);
26✔
738
        if (pkey == nullptr) {
13✔
739
                return expected::unexpected(MakeError(
2✔
740
                        SetupError,
741
                        "Failed to load the public key from(" + public_key_path
4✔
742
                                + "): " + GetOpenSSLErrorMessage()));
10✔
743
        }
744

745
        auto pkey_signer_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
746
                EVP_PKEY_CTX_new(pkey.get(), nullptr), pkey_ctx_free_func);
22✔
747

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

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

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

785
        return VerifySignData(public_key_path, shasum, decoded_signature);
14✔
786
}
787

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

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

821
        return error::NoError;
6✔
822
}
823

824
} // namespace crypto
825
} // namespace common
826
} // 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