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

mendersoftware / mender / 1508379960

23 Oct 2024 07:18AM UTC coverage: 76.249% (-0.008%) from 76.257%
1508379960

push

gitlab-ci

kacf
build: Enable some more warnings by default.

Signed-off-by: Kristian Amlie <kristian.amlie@northern.tech>

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

2 existing lines in 2 files now uncovered.

7313 of 9591 relevant lines covered (76.25%)

11279.03 hits per line

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

63.49
/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
#include <openssl/ssl.h>
30
#ifndef MENDER_CRYPTO_OPENSSL_LEGACY
31
#include <openssl/provider.h>
32
#include <openssl/store.h>
33
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
34

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

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

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

47

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

52
const size_t MENDER_DIGEST_SHA256_LENGTH = 32;
53

54
const size_t OPENSSL_SUCCESS = 1;
55

56
using namespace std;
57

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

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

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

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

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

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

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

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

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

124

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

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

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

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

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

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

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

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

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

204
        char *passphrase = const_cast<char *>(args.private_key_passphrase.c_str());
205

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

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

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

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

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

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

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

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

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

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

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

295
        log::Trace("Loading private key");
74✔
296
        if (args.ssl_engine != "") {
37✔
297
                return LoadFromHSMEngine(args);
×
298
        }
299
        return LoadFrom(args);
37✔
300
}
301

302
ExpectedPrivateKey PrivateKey::Generate() {
7✔
303
#ifdef MENDER_CRYPTO_OPENSSL_LEGACY
304
        auto pkey_gen_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
305
                EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, nullptr), pkey_ctx_free_func);
14✔
306
#else
307
        auto pkey_gen_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
308
                EVP_PKEY_CTX_new_from_name(nullptr, "ED25519", nullptr), pkey_ctx_free_func);
309
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
310

311
        int ret = EVP_PKEY_keygen_init(pkey_gen_ctx.get());
7✔
312
        if (ret != OPENSSL_SUCCESS) {
7✔
313
                return expected::unexpected(MakeError(
×
314
                        SetupError,
315
                        "Failed to generate a private key. Initialization failed: "
316
                                + GetOpenSSLErrorMessage()));
×
317
        }
318
        EVP_PKEY *pkey = nullptr;
7✔
319
#ifdef MENDER_CRYPTO_OPENSSL_LEGACY
320
        ret = EVP_PKEY_keygen(pkey_gen_ctx.get(), &pkey);
7✔
321
#else
322
        ret = EVP_PKEY_generate(pkey_gen_ctx.get(), &pkey);
323
#endif // MENDER_CRYPTO_OPENSSL_LEGACY
324
        if (ret != OPENSSL_SUCCESS) {
7✔
325
                return expected::unexpected(MakeError(
×
326
                        SetupError,
327
                        "Failed to generate a private key. Generation failed: " + GetOpenSSLErrorMessage()));
×
328
        }
329

330
        auto private_key = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(pkey, pkey_free_func);
7✔
331
        return PrivateKey(std::move(private_key));
7✔
332
}
333

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

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

345
        const int64_t output_len {
346
                EVP_EncodeBlock(buffer.data(), to_encode.data(), static_cast<int>(to_encode.size()))};
14✔
347
        assert(output_len >= 0);
348

349
        if (predicted_len != static_cast<uint64_t>(output_len)) {
14✔
350
                return expected::unexpected(
×
351
                        MakeError(Base64Error, "The predicted and the actual length differ"));
×
352
        }
353

354
        return string(buffer.begin(), buffer.end() - 1); // Remove the last zero byte
28✔
355
}
356

357
expected::ExpectedBytes DecodeBase64(string to_decode) {
15✔
358
        // Predict the len of the decoded for later verification. From man page:
359
        // For every 4 input bytes exactly 3 output bytes will be
360
        // produced. The output will be padded with 0 bits if necessary
361
        // to ensure that the output is always 3 bytes.
362
        const size_t predicted_len {3 * ((to_decode.size() + 3) / 4)};
15✔
363

364
        auto buffer {vector<unsigned char>(predicted_len)};
15✔
365

366
        const int64_t output_len {EVP_DecodeBlock(
15✔
367
                buffer.data(),
368
                common::ByteVectorFromString(to_decode).data(),
15✔
369
                static_cast<int>(to_decode.size()))};
15✔
370
        assert(output_len >= 0);
371

372
        if (predicted_len != static_cast<uint64_t>(output_len)) {
15✔
373
                return expected::unexpected(MakeError(
×
374
                        Base64Error,
375
                        "The predicted (" + std::to_string(predicted_len) + ") and the actual ("
×
376
                                + std::to_string(output_len) + ") length differ"));
×
377
        }
378

379
        // Subtract padding bytes. Inspired by internal OpenSSL code from:
380
        // https://github.com/openssl/openssl/blob/ff88545e02ab48a52952350c52013cf765455dd3/crypto/ct/ct_b64.c#L46
381
        for (auto it = to_decode.crbegin(); *it == '='; it++) {
23✔
382
                buffer.pop_back();
383
        }
384

385
        return buffer;
15✔
386
}
387

388

389
expected::ExpectedString ExtractPublicKey(const Args &args) {
9✔
390
        auto exp_private_key = PrivateKey::Load(args);
9✔
391
        if (!exp_private_key) {
9✔
392
                return expected::unexpected(exp_private_key.error());
2✔
393
        }
394

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

397
        if (!bio_public_key.get()) {
8✔
398
                return expected::unexpected(MakeError(
×
399
                        SetupError,
400
                        "Failed to extract the public key from the private key " + args.private_key_path
×
401
                                + "):" + GetOpenSSLErrorMessage()));
×
402
        }
403

404
        int ret = PEM_write_bio_PUBKEY(bio_public_key.get(), exp_private_key.value().Get());
8✔
405
        if (ret != OPENSSL_SUCCESS) {
8✔
406
                return expected::unexpected(MakeError(
×
407
                        SetupError,
408
                        "Failed to extract the public key from the private key (" + args.private_key_path
×
409
                                + "): OpenSSL BIO write failed: " + GetOpenSSLErrorMessage()));
×
410
        }
411

412
        // NOTE: At this point we already have a public key available for extraction.
413
        // However, when using some providers in OpenSSL3 the external provider might
414
        // write the key in the old PKCS#1 format. The format is not deprecated, but
415
        // our older backends only understand the format if it is in the PKCS#8
416
        // (SubjectPublicKey) format:
417
        //
418
        // For us who don't speak OpenSSL:
419
        //
420
        // -- BEGIN RSA PUBLIC KEY -- <- PKCS#1 (old format)
421
        // -- BEGIN PUBLIC KEY -- <- PKCS#8 (new format - can hold different key types)
422

423

424
        auto evp_public_key = PkeyPtr(
425
                PEM_read_bio_PUBKEY(bio_public_key.get(), nullptr, nullptr, nullptr), pkey_free_func);
16✔
426

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

434
        auto bio_public_key_new =
435
                unique_ptr<BIO, void (*)(BIO *)>(BIO_new(BIO_s_mem()), bio_free_all_func);
16✔
436

437
        if (bio_public_key_new == nullptr) {
8✔
438
                return expected::unexpected(MakeError(
×
439
                        SetupError,
440
                        "Failed to extract the public key from the public key " + args.private_key_path
×
441
                                + "):" + GetOpenSSLErrorMessage()));
×
442
        }
443

444
        ret = PEM_write_bio_PUBKEY(bio_public_key_new.get(), evp_public_key.get());
8✔
445
        if (ret != OPENSSL_SUCCESS) {
8✔
446
                return expected::unexpected(MakeError(
×
447
                        SetupError,
448
                        "Failed to extract the public key from the private key: (" + args.private_key_path
×
449
                                + "): OpenSSL BIO write failed: " + GetOpenSSLErrorMessage()));
×
450
        }
451

452
        // Inconsistent API, this returns size_t, but the API below uses int. Should not matter for
453
        // key sizes though.
454
        int pending = static_cast<int>(BIO_ctrl_pending(bio_public_key_new.get()));
8✔
455
        if (pending <= 0) {
8✔
456
                return expected::unexpected(MakeError(
×
457
                        SetupError,
458
                        "Failed to extract the public key from bio ctrl: (" + args.private_key_path
×
459
                                + "): Zero byte key unexpected: " + GetOpenSSLErrorMessage()));
×
460
        }
461

462
        vector<uint8_t> key_vector(pending);
8✔
463

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

466
        if (read == 0) {
8✔
467
                MakeError(
×
468
                        SetupError,
469
                        "Failed to extract the public key from (" + args.private_key_path
×
470
                                + "): Zero bytes read from BIO: " + GetOpenSSLErrorMessage());
×
471
        }
472

473
        return string(key_vector.begin(), key_vector.end());
16✔
474
}
475

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

479
        auto md_ctx = unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX *)>(EVP_MD_CTX_new(), EVP_MD_CTX_free);
4✔
480
        if (md_ctx == nullptr) {
2✔
481
                return expected::unexpected(MakeError(
×
482
                        SetupError, "Failed to initialize the OpenSSL md_ctx: " + GetOpenSSLErrorMessage()));
×
483
        }
484

485
        int ret {EVP_DigestSignInit(md_ctx.get(), nullptr, nullptr, nullptr, pkey)};
2✔
486
        if (ret != OPENSSL_SUCCESS) {
2✔
487
                return expected::unexpected(MakeError(
×
488
                        SetupError, "Failed to initialize the OpenSSL signature: " + GetOpenSSLErrorMessage()));
×
489
        }
490

491
        /* Calculate the required size for the signature by passing a nullptr buffer */
492
        ret = EVP_DigestSign(md_ctx.get(), nullptr, &sig_len, raw_data.data(), raw_data.size());
2✔
493
        if (ret != OPENSSL_SUCCESS) {
2✔
494
                return expected::unexpected(MakeError(
×
495
                        SetupError,
496
                        "Failed to find the required size of the signature buffer: "
497
                                + GetOpenSSLErrorMessage()));
×
498
        }
499

500
        vector<uint8_t> sig(sig_len);
2✔
501
        ret = EVP_DigestSign(md_ctx.get(), sig.data(), &sig_len, raw_data.data(), raw_data.size());
2✔
502
        if (ret != OPENSSL_SUCCESS) {
2✔
503
                return expected::unexpected(
×
504
                        MakeError(SetupError, "Failed to sign the message: " + GetOpenSSLErrorMessage()));
×
505
        }
506

507
        // The signature may in some cases be shorter than the previously allocated
508
        // length (which is the max)
509
        sig.resize(sig_len);
2✔
510

511
        return sig;
2✔
512
}
513

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

518
        if (EVP_PKEY_sign_init(pkey_signer_ctx.get()) <= 0) {
8✔
519
                return expected::unexpected(MakeError(
×
520
                        SetupError, "Failed to initialize the OpenSSL signer: " + GetOpenSSLErrorMessage()));
×
521
        }
522
        if (EVP_PKEY_CTX_set_signature_md(pkey_signer_ctx.get(), EVP_sha256()) <= 0) {
8✔
523
                return expected::unexpected(MakeError(
×
524
                        SetupError,
525
                        "Failed to set the OpenSSL signature to sha256: " + GetOpenSSLErrorMessage()));
×
526
        }
527

528
        vector<uint8_t> signature {};
529

530
        // Set the needed signature buffer length
531
        size_t digestlength = MENDER_DIGEST_SHA256_LENGTH, siglength;
532
        if (EVP_PKEY_sign(pkey_signer_ctx.get(), nullptr, &siglength, digest.data(), digestlength)
8✔
533
                <= 0) {
534
                return expected::unexpected(MakeError(
×
535
                        SetupError, "Failed to get the signature buffer length: " + GetOpenSSLErrorMessage()));
×
536
        }
537
        signature.resize(siglength);
8✔
538

539
        if (EVP_PKEY_sign(
8✔
540
                        pkey_signer_ctx.get(), signature.data(), &siglength, digest.data(), digestlength)
541
                <= 0) {
542
                return expected::unexpected(
×
543
                        MakeError(SetupError, "Failed to sign the digest: " + GetOpenSSLErrorMessage()));
×
544
        }
545

546
        // The signature may in some cases be shorter than the previously allocated
547
        // length (which is the max)
548
        signature.resize(siglength);
8✔
549

550
        return signature;
8✔
551
}
552

553
expected::ExpectedBytes SignData(const Args &args, const vector<uint8_t> &raw_data) {
11✔
554
        auto exp_private_key = PrivateKey::Load(args);
11✔
555
        if (!exp_private_key) {
11✔
556
                return expected::unexpected(exp_private_key.error());
2✔
557
        }
558

559
        log::Info("Signing with: " + args.private_key_path);
10✔
560

561
        auto key_type = EVP_PKEY_base_id(exp_private_key.value().Get());
10✔
562

563
        // ED25519 signatures need to be handled independently, because of how the
564
        // signature scheme is designed.
565
        if (key_type == EVP_PKEY_ED25519) {
10✔
566
                return SignED25519(exp_private_key.value().Get(), raw_data);
2✔
567
        }
568

569
        auto exp_shasum = mender::sha::Shasum(raw_data);
8✔
570
        if (!exp_shasum) {
8✔
571
                return expected::unexpected(exp_shasum.error());
×
572
        }
573
        auto digest = exp_shasum.value(); /* The shasummed data = digest in crypto world */
8✔
574
        log::Debug("Shasum is: " + digest.String());
16✔
575

576
        return SignGeneric(exp_private_key.value(), digest);
16✔
577
}
578

579
expected::ExpectedString Sign(const Args &args, const vector<uint8_t> &raw_data) {
11✔
580
        auto exp_signed_data = SignData(args, raw_data);
11✔
581
        if (!exp_signed_data) {
11✔
582
                return expected::unexpected(exp_signed_data.error());
2✔
583
        }
584
        vector<uint8_t> signature = exp_signed_data.value();
10✔
585

586
        return EncodeBase64(signature);
20✔
587
}
588

589
const size_t mender_decode_buf_size = 256;
590
const size_t ecdsa256keySize = 32;
591

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

617
        auto r = unique_ptr<BIGNUM, void (*)(BIGNUM *)>(
618
                BinaryDecoderFn(signature.data(), ecdsa256keySize, nullptr /* allocate new memory for r */),
619
                bn_free);
4✔
620
        if (r == nullptr) {
2✔
621
                return expected::unexpected(MakeError(
×
622
                        SetupError,
623
                        "Failed to extract the r(andom) part from the ECDSA signature in the binary representation: "
624
                                + GetOpenSSLErrorMessage()));
×
625
        }
626
        auto s = unique_ptr<BIGNUM, void (*)(BIGNUM *)>(
627
                BinaryDecoderFn(
628
                        signature.data() + ecdsa256keySize,
629
                        ecdsa256keySize,
630
                        nullptr /* allocate new memory for s */),
631
                bn_free);
4✔
632
        if (s == nullptr) {
2✔
633
                return expected::unexpected(MakeError(
×
634
                        SetupError,
635
                        "Failed to extract the s(ignature) part from the ECDSA signature in the binary representation: "
636
                                + GetOpenSSLErrorMessage()));
×
637
        }
638

639
        // Set the r&s values in the SIG struct
640
        // r & s now owned by ecSig
641
        int ret {ECDSA_SIG_set0(ecSig.get(), r.get(), s.get())};
2✔
642
        if (ret != OPENSSL_SUCCESS) {
2✔
643
                return expected::unexpected(MakeError(
×
644
                        SetupError,
645
                        "Failed to set the signature parts in the ECDSA structure: "
646
                                + GetOpenSSLErrorMessage()));
×
647
        }
648
        r.release();
649
        s.release();
650

651
        /* Allocate some array guaranteed to hold the DER-encoded structure */
652
        vector<uint8_t> der_encoded_byte_array(mender_decode_buf_size);
2✔
653
        unsigned char *arr_p = &der_encoded_byte_array[0];
2✔
654
        int len = i2d_ECDSA_SIG(ecSig.get(), &arr_p);
2✔
655
        if (len < 0) {
2✔
656
                return expected::unexpected(MakeError(
×
657
                        SetupError,
658
                        "Failed to set the signature parts in the ECDSA structure: "
659
                                + GetOpenSSLErrorMessage()));
×
660
        }
661
        /* Resize to the actual size of the DER-encoded signature */
662
        der_encoded_byte_array.resize(len);
2✔
663

664
        return der_encoded_byte_array;
2✔
665
}
666

667

668
expected::ExpectedBool VerifySignData(
669
        const string &public_key_path,
670
        const mender::sha::SHA &shasum,
671
        const vector<uint8_t> &signature);
672

673
static expected::ExpectedBool VerifyECDSASignData(
2✔
674
        const string &public_key_path,
675
        const mender::sha::SHA &shasum,
676
        const vector<uint8_t> &signature) {
677
        expected::ExpectedBytes exp_der_encoded_signature =
678
                TryASN1EncodeMenderCustomBinaryECFormat(signature, shasum, BN_bin2bn)
4✔
679
                        .or_else([&signature, &shasum](error::Error big_endian_error) {
×
680
                                log::Debug(
×
681
                                        "Failed to decode the signature binary blob from our custom binary format assuming the big-endian encoding, error: "
682
                                        + big_endian_error.String()
×
683
                                        + " falling back and trying anew assuming it is little-endian encoded: ");
×
684
                                return TryASN1EncodeMenderCustomBinaryECFormat(signature, shasum, BN_lebin2bn);
×
685
                        });
2✔
686
        if (!exp_der_encoded_signature) {
2✔
687
                return expected::unexpected(
×
688
                        MakeError(VerificationError, exp_der_encoded_signature.error().message));
×
689
        }
690

691
        vector<uint8_t> der_encoded_signature = exp_der_encoded_signature.value();
2✔
692

693
        return VerifySignData(public_key_path, shasum, der_encoded_signature);
2✔
694
}
695

696
static bool OpenSSLSignatureVerificationError(int a) {
697
        /*
698
         * The signature check errored. This is different from the signature being
699
         * wrong. We simply were not able to perform the check in this instance.
700
         * Therefore, we fall back to trying the custom marshalled binary ECDSA
701
         * signature, which we have been using in Mender.
702
         */
703
        return a < 0;
704
}
705

706
expected::ExpectedBool VerifySignData(
16✔
707
        const string &public_key_path,
708
        const mender::sha::SHA &shasum,
709
        const vector<uint8_t> &signature) {
710
        auto bio_key =
711
                unique_ptr<BIO, void (*)(BIO *)>(BIO_new_file(public_key_path.c_str(), "r"), bio_free_func);
32✔
712
        if (bio_key == nullptr) {
16✔
713
                return expected::unexpected(MakeError(
3✔
714
                        SetupError,
715
                        "Failed to open the public key file from (" + public_key_path
6✔
716
                                + "):" + GetOpenSSLErrorMessage()));
15✔
717
        }
718

719
        auto pkey = unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)>(
720
                PEM_read_bio_PUBKEY(bio_key.get(), nullptr, nullptr, nullptr), pkey_free_func);
26✔
721
        if (pkey == nullptr) {
13✔
722
                return expected::unexpected(MakeError(
2✔
723
                        SetupError,
724
                        "Failed to load the public key from(" + public_key_path
4✔
725
                                + "): " + GetOpenSSLErrorMessage()));
10✔
726
        }
727

728
        auto pkey_signer_ctx = unique_ptr<EVP_PKEY_CTX, void (*)(EVP_PKEY_CTX *)>(
729
                EVP_PKEY_CTX_new(pkey.get(), nullptr), pkey_ctx_free_func);
22✔
730

731
        auto ret = EVP_PKEY_verify_init(pkey_signer_ctx.get());
11✔
732
        if (ret <= 0) {
11✔
733
                return expected::unexpected(MakeError(
×
734
                        SetupError, "Failed to initialize the OpenSSL signer: " + GetOpenSSLErrorMessage()));
×
735
        }
736
        ret = EVP_PKEY_CTX_set_signature_md(pkey_signer_ctx.get(), EVP_sha256());
11✔
737
        if (ret <= 0) {
11✔
738
                return expected::unexpected(MakeError(
×
739
                        SetupError,
740
                        "Failed to set the OpenSSL signature to sha256: " + GetOpenSSLErrorMessage()));
×
741
        }
742

743
        // verify signature
744
        ret = EVP_PKEY_verify(
11✔
745
                pkey_signer_ctx.get(), signature.data(), signature.size(), shasum.data(), shasum.size());
746
        if (OpenSSLSignatureVerificationError(ret)) {
11✔
747
                log::Debug(
2✔
748
                        "Failed to verify the signature with the supported OpenSSL binary formats. Falling back to the custom Mender encoded binary format for ECDSA signatures: "
749
                        + GetOpenSSLErrorMessage());
4✔
750
                return VerifyECDSASignData(public_key_path, shasum, signature);
2✔
751
        }
752
        if (ret == OPENSSL_SUCCESS) {
9✔
753
                return true;
754
        }
755
        /* This is the case where ret == 0. The signature is simply wrong */
756
        return false;
757
}
758

759
expected::ExpectedBool VerifySign(
14✔
760
        const string &public_key_path, const mender::sha::SHA &shasum, const string &signature) {
761
        // signature: decode base64
762
        auto exp_decoded_signature = DecodeBase64(signature);
28✔
763
        if (!exp_decoded_signature) {
14✔
764
                return expected::unexpected(exp_decoded_signature.error());
×
765
        }
766
        auto decoded_signature = exp_decoded_signature.value();
14✔
767

768
        return VerifySignData(public_key_path, shasum, decoded_signature);
14✔
769
}
770

771
error::Error PrivateKey::SaveToPEM(const string &private_key_path) {
6✔
772
        auto bio_key = unique_ptr<BIO, void (*)(BIO *)>(
773
                BIO_new_file(private_key_path.c_str(), "w"), bio_free_func);
12✔
774
        if (bio_key == nullptr) {
6✔
775
                return MakeError(
776
                        SetupError,
777
                        "Failed to open the private key file (" + private_key_path
2✔
778
                                + "): " + GetOpenSSLErrorMessage());
4✔
779
        }
780

781
        auto ret =
782
                PEM_write_bio_PrivateKey(bio_key.get(), key.get(), nullptr, nullptr, 0, nullptr, nullptr);
5✔
783
        if (ret != OPENSSL_SUCCESS) {
5✔
784
                return MakeError(
785
                        SetupError,
786
                        "Failed to save the private key to file (" + private_key_path
×
787
                                + "): " + GetOpenSSLErrorMessage());
×
788
        }
789

790
        return error::NoError;
5✔
791
}
792

793
} // namespace crypto
794
} // namespace common
795
} // 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

© 2025 Coveralls, Inc