2 * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "authenticator.h"
18 #include "authenticator_event_object.h"
20 #include "beyond/plugin/authenticator_ssl_plugin.h"
22 #include <beyond/platform/beyond_platform.h>
23 #include <beyond/private/beyond_private.h>
36 #include <sys/types.h>
37 #include <sys/socket.h>
39 #include <openssl/opensslconf.h>
40 #include <openssl/opensslv.h>
41 #include <openssl/err.h>
42 #include <openssl/rsa.h>
43 #include <openssl/bn.h>
44 #include <openssl/crypto.h>
45 #include <openssl/bio.h>
46 #include <openssl/evp.h>
47 #include <openssl/pem.h>
48 #include <openssl/conf.h>
49 #include <openssl/x509.h>
50 #include <openssl/x509v3.h>
51 #include <openssl/rand.h>
53 #ifndef OPENSSL_NO_ENGINE
54 #include <openssl/engine.h>
57 #include <json/json.h>
59 #define DEFAULT_MSG_BUFSZ 256
60 #define DEFAULT_PRIME 65537
61 #define DEFAULT_BIO_BUFSZ 4096
63 // At least now, the secret key is used for GST pipeline encryption
64 // And for the gRPC session authentication.
65 // But the GST pipeline(srtpenc) element is limit its key size from 30 to 46 bytes.
66 // Let's keep the secret key length by the requirements
67 #define DEFAULT_SECRET_KEY_BITS 256
68 #define DEFAULT_BITS 4096
69 #define DEFAULT_SERIAL 1
70 #define DEFAULT_DAYS 365
72 #define DAYS_TO_SECONDS(days) ((days)*24 * 60 * 60)
73 #define BITS_TO_BYTES(bits) ((bits) >> 3)
75 #define SSLErrPrint(name) \
77 char msg[DEFAULT_MSG_BUFSZ]; \
78 ERR_error_string_n(ERR_get_error(), msg, sizeof(msg)); \
79 ErrPrint(name ": %s", msg); \
82 Authenticator::CommandHandler Authenticator::commandTable[COMMAND::LAST] = {
83 Authenticator::CommandGenerate,
84 Authenticator::CommandCleanup,
85 Authenticator::CommandCrypto,
86 Authenticator::CommandGetKey,
87 Authenticator::CommandGenerateSign,
88 Authenticator::CommandVerifySign,
91 Authenticator *Authenticator::Create(bool enableAsync)
97 impl = new Authenticator();
98 } catch (std::exception &e) {
99 ErrPrint("new failed: %s", e.what());
104 // eventObject only be created if the async mode is enabled
105 impl->eventObject = nullptr;
106 impl->asyncCtx.handlerObject = nullptr;
108 if (pipe2(pfd, O_CLOEXEC) < 0) {
109 ErrPrintCode(errno, "pipe2");
116 if (enableAsync == true) {
117 impl->eventObject = Authenticator::EventObject::Create();
118 if (impl->eventObject == nullptr) {
119 if (close(pfd[0]) < 0) {
120 ErrPrintCode(errno, "close");
122 if (close(pfd[1]) < 0) {
123 ErrPrintCode(errno, "close");
131 impl->asyncCtx.eventLoop = beyond::EventLoop::Create(true, false);
132 if (impl->asyncCtx.eventLoop == nullptr) {
133 ErrPrint("Failed to create an event loop");
135 impl->eventObject->Destroy();
136 impl->eventObject = nullptr;
138 if (close(pfd[0]) < 0) {
139 ErrPrintCode(errno, "close");
141 if (close(pfd[1]) < 0) {
142 ErrPrintCode(errno, "close");
150 impl->asyncCtx.eventLoop->SetStopHandler([](beyond::EventLoop *loop, void *data) -> void {
151 Authenticator *impl = static_cast<Authenticator *>(data);
152 impl->CommandCleanup(impl, nullptr);
157 int spfd[2]; // command
158 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, spfd) < 0) {
159 ErrPrintCode(errno, "socketpair");
161 impl->asyncCtx.eventLoop->Destroy();
162 impl->asyncCtx.eventLoop = nullptr;
164 impl->eventObject->Destroy();
165 impl->eventObject = nullptr;
167 if (close(pfd[0]) < 0) {
168 ErrPrintCode(errno, "close");
171 if (close(pfd[1]) < 0) {
172 ErrPrintCode(errno, "close");
180 impl->command = std::make_unique<beyond::CommandObject>(spfd[0]);
181 impl->asyncCtx.command = std::make_unique<beyond::CommandObject>(spfd[1]);
183 impl->asyncCtx.handlerObject = impl->asyncCtx.eventLoop->AddEventHandler(
185 // get the unique_ptr's raw pointer
186 // Does this break the unique_ptr's concept?
187 static_cast<beyond::EventObjectBaseInterface *>(impl->asyncCtx.command.get()),
188 beyond_event_type::BEYOND_EVENT_TYPE_READ | beyond_event_type::BEYOND_EVENT_TYPE_ERROR,
189 [](beyond::EventObjectBaseInterface *eventObject, int type, void *data) -> beyond_handler_return {
190 beyond::CommandObject *cmdObject = static_cast<beyond::CommandObject *>(eventObject);
191 Authenticator *auth = static_cast<Authenticator *>(data);
194 void *_data = nullptr;
196 int ret = cmdObject->Recv(cmdId, _data);
198 ErrPrint("Failed to get the command");
199 return beyond_handler_return::BEYOND_HANDLER_RETURN_CANCEL;
202 if (cmdId >= 0 && cmdId < COMMAND::LAST) {
203 assert(auth->commandTable[cmdId] != nullptr && "Command handler is nullptr");
204 ret = auth->commandTable[cmdId](auth, _data);
206 DbgPrint("Command Handler returns: %d", ret);
209 ErrPrint("Invalid command request");
212 return beyond_handler_return::BEYOND_HANDLER_RETURN_RENEW;
216 if (impl->asyncCtx.handlerObject == nullptr) {
217 ErrPrint("Failed to add the event handler");
219 if (close(spfd[0]) < 0) {
220 ErrPrintCode(errno, "close");
223 if (close(spfd[1]) < 0) {
224 ErrPrintCode(errno, "close");
227 impl->asyncCtx.eventLoop->Destroy();
228 impl->asyncCtx.eventLoop = nullptr;
230 impl->eventObject->Destroy();
231 impl->eventObject = nullptr;
233 if (close(pfd[0]) < 0) {
234 ErrPrintCode(errno, "close");
236 if (close(pfd[1]) < 0) {
237 ErrPrintCode(errno, "close");
246 impl->outputConsumer = std::make_unique<beyond::CommandObject>(pfd[0]);
247 impl->asyncCtx.outputProducer = std::make_unique<beyond::CommandObject>(pfd[1]);
251 const char *Authenticator::GetModuleName(void) const
253 return Authenticator::NAME;
256 const char *Authenticator::GetModuleType(void) const
258 return ModuleInterface::TYPE_AUTHENTICATOR;
261 void Authenticator::Destroy(void)
263 if (asyncCtx.eventLoop != nullptr) {
264 asyncCtx.eventLoop->Stop();
266 asyncCtx.eventLoop->Destroy();
268 asyncCtx.eventLoop = nullptr;
270 if (close(command->GetHandle()) < 0) {
271 ErrPrintCode(errno, "close");
274 if (close(asyncCtx.command->GetHandle()) < 0) {
275 ErrPrintCode(errno, "close");
279 if (close(outputConsumer->GetHandle()) < 0) {
280 ErrPrintCode(errno, "close");
283 if (close(asyncCtx.outputProducer->GetHandle()) < 0) {
284 ErrPrintCode(errno, "close");
290 int Authenticator::GetHandle(void) const
292 return eventObject ? eventObject->GetHandle() : -ENOTSUP;
295 int Authenticator::AddHandler(beyond_event_handler_t handler, int type, void *data)
297 return eventObject ? eventObject->AddHandler(handler, type, data) : -ENOTSUP;
300 int Authenticator::RemoveHandler(beyond_event_handler_t handler, int type, void *data)
302 return eventObject ? eventObject->RemoveHandler(handler, type, data) : -ENOTSUP;
305 int Authenticator::FetchEventData(EventObjectInterface::EventData *&data)
307 return eventObject ? eventObject->FetchEventData(data) : -ENOTSUP;
310 int Authenticator::DestroyEventData(EventObjectInterface::EventData *&data)
312 return eventObject ? eventObject->DestroyEventData(data) : -ENOTSUP;
315 int Authenticator::ConfigureAuthenticator(void *object)
317 authenticator = static_cast<beyond::AuthenticatorInterface *>(object);
318 beyond::ModuleInterface *module = dynamic_cast<beyond::ModuleInterface *>(authenticator);
319 if (module == nullptr) {
320 ErrPrint("Failed to cast to the module interface");
322 DbgPrint("Module name is %s", module->GetModuleName());
327 int Authenticator::ConfigureSecretKey(void *object)
329 beyond_authenticator_ssl_config_secret_key *secrets = static_cast<beyond_authenticator_ssl_config_secret_key *>(object);
331 if (secrets->key != nullptr) {
332 if (secrets->key_bits <= 0) {
333 ErrPrint("Secret key bits must be provided");
337 sslConfig.secretKey = std::string(secrets->key, BITS_TO_BYTES(secrets->key_bits));
338 sslConfig.secretKeyBits = secrets->key_bits;
339 } else if (secrets->key_bits >= 0) {
340 sslConfig.secretKeyBits = secrets->key_bits;
341 sslConfig.secretKey.clear();
343 sslConfig.secretKey.clear();
344 sslConfig.secretKeyBits = DEFAULT_SECRET_KEY_BITS;
347 if (sslConfig.secretKey.empty() == true) {
348 return GenerateSecretKey();
351 return LoadSecretKey();
354 int Authenticator::ConfigureJSON(void *object)
358 Json::CharReaderBuilder builder;
359 Json::CharReader *reader = builder.newCharReader();
361 if (reader == nullptr) {
362 ErrPrint("Unable to create a json reader");
366 const char *jsonStr = static_cast<char *>(object);
367 bool jsonParseStatus = reader->parse(jsonStr, jsonStr + strlen(jsonStr), &root, &errors);
368 if (jsonParseStatus == false) {
369 ErrPrint("Failed to parse the json string: %s", jsonStr);
373 if (errors.empty() == false) {
374 ErrPrint("Failed to parse the JSON string: %s", errors.c_str());
379 * NOTE: Sample JSON configuration ("ssl")
383 * "passphrase": "secret key string",
384 * "private_key": "BEGIN PRIVATE KEY ..... END PRIVATE KEY",
385 * "certificate": "BEGIN CERTIFICATE ..... END CERTIFICATE",
386 * "alternative_name": "127.0.0.1",
393 * "key": "secret key string",
398 const Json::Value &secretKey = root["secret_key"];
399 if (secretKey.empty() == false) {
400 beyond_authenticator_ssl_config_secret_key secretKeyOption;
402 const Json::Value &keyValue = secretKey["key"];
403 if (keyValue.empty() == false && keyValue.isString() == true) {
404 secretKeyOption.key = keyValue.asCString();
406 secretKeyOption.key = nullptr;
409 const Json::Value &keyBitsValue = secretKey["key_bits"];
410 if (keyBitsValue.empty() == false && keyBitsValue.isInt() == true) {
411 secretKeyOption.key_bits = keyBitsValue.asInt();
413 secretKeyOption.key_bits = -1;
416 int ret = ConfigureSecretKey(&secretKeyOption);
418 ErrPrint("Failed to configure the secret key");
423 const Json::Value &ssl = root["ssl"];
424 if (ssl.empty() == false) {
425 beyond_authenticator_ssl_config_ssl sslOption;
426 const Json::Value &passphraseValue = ssl["passphrase"];
427 if (passphraseValue.empty() == false && passphraseValue.isString() == true) {
428 sslOption.passphrase = passphraseValue.asCString();
430 sslOption.passphrase = nullptr;
433 const Json::Value &privateKeyValue = ssl["private_key"];
434 if (privateKeyValue.empty() == false && privateKeyValue.isString() == true) {
435 sslOption.private_key = privateKeyValue.asCString();
437 sslOption.private_key = nullptr;
440 const Json::Value &certificateValue = ssl["certificate"];
441 if (certificateValue.empty() == false && certificateValue.isString() == true) {
442 sslOption.certificate = certificateValue.asCString();
444 sslOption.certificate = nullptr;
447 const Json::Value &alternativeNameValue = ssl["alternative_name"];
448 if (alternativeNameValue.empty() == false && alternativeNameValue.isString() == true) {
449 sslOption.alternative_name = alternativeNameValue.asCString();
451 sslOption.alternative_name = nullptr;
454 const Json::Value &bitsValue = ssl["bits"];
455 if (bitsValue.empty() == false && bitsValue.isInt() == true) {
456 sslOption.bits = bitsValue.asInt();
461 const Json::Value &daysValue = ssl["days"];
462 if (daysValue.empty() == false && daysValue.isInt() == true) {
463 sslOption.days = daysValue.asInt();
468 const Json::Value &serialValue = ssl["serial"];
469 if (serialValue.empty() == false && serialValue.isInt() == true) {
470 sslOption.serial = serialValue.asInt();
472 sslOption.serial = -1;
475 const Json::Value &isCAValue = ssl["is_ca"];
476 if (isCAValue.empty() == false && isCAValue.isInt() == true) {
477 sslOption.isCA = isCAValue.asInt();
482 const Json::Value &enableBase64Value = ssl["enable_base64"];
483 if (enableBase64Value.empty() == false && enableBase64Value.isInt() == true) {
484 sslOption.enableBase64 = enableBase64Value.asInt();
486 sslOption.enableBase64 = -1;
489 int ret = ConfigureSSL(&sslOption);
491 ErrPrint("Failed to configure the SSL");
499 int Authenticator::ConfigureSSL(void *object)
501 beyond_authenticator_ssl_config_ssl *ssl = static_cast<beyond_authenticator_ssl_config_ssl *>(object);
503 if (ssl->passphrase != nullptr) {
504 sslConfig.passphrase = std::string(ssl->passphrase);
506 sslConfig.passphrase.clear();
509 if (ssl->private_key != nullptr) {
510 sslConfig.privateKey = std::string(ssl->private_key);
512 sslConfig.privateKey.clear();
515 if (ssl->certificate != nullptr) {
516 sslConfig.certificate = std::string(ssl->certificate);
518 sslConfig.certificate.clear();
521 if (ssl->alternative_name != nullptr) {
522 sslConfig.alternativeName = std::string(ssl->alternative_name);
524 sslConfig.alternativeName.clear();
528 sslConfig.bits = ssl->bits;
529 } else if (ssl->bits == 0) {
530 sslConfig.bits = DEFAULT_BITS;
534 sslConfig.days = ssl->days;
535 } else if (ssl->days == 0) {
536 sslConfig.days = DEFAULT_DAYS;
539 if (ssl->serial > 0) {
540 sslConfig.serial = ssl->serial;
541 } else if (ssl->serial == 0) {
542 sslConfig.serial = DEFAULT_SERIAL;
545 if (ssl->isCA >= 0) {
546 sslConfig.isCA = !!ssl->isCA;
548 sslConfig.isCA = true;
551 if (ssl->enableBase64 >= 0) {
552 sslConfig.enableBase64 = !!ssl->enableBase64;
554 sslConfig.enableBase64 = true;
560 int Authenticator::Configure(const beyond_config *options)
562 if (options == nullptr) {
566 if (options->object == nullptr) {
567 ErrPrint("Configure object is nullptr");
572 switch (options->type) {
573 case BEYOND_PLUGIN_AUTHENTICATOR_SSL_CONFIG_SSL:
574 ret = ConfigureSSL(options->object);
576 case BEYOND_CONFIG_TYPE_AUTHENTICATOR:
577 ret = ConfigureAuthenticator(options->object);
579 case BEYOND_CONFIG_TYPE_JSON:
580 ret = ConfigureJSON(options->object);
582 case BEYOND_PLUGIN_AUTHENTICATOR_SSL_CONFIG_SECRET_KEY:
583 ret = ConfigureSecretKey(options->object);
592 int Authenticator::CommandGenerate(Authenticator *inst, void *data)
596 if (inst->sslConfig.privateKey.empty() == true && inst->sslConfig.certificate.empty() == true) {
597 ret = inst->GenerateKey();
599 ret = inst->GenerateCertificate();
602 ret = inst->LoadCertificate();
605 if (inst->sslContext.secretKey.empty() == true) {
606 ret = inst->GenerateSecretKey();
609 if (inst->eventObject != nullptr) {
611 inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_PREPARE_DONE);
613 inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_PREPARE_ERROR);
620 int Authenticator::CommandCrypto(Authenticator *inst, void *data)
622 CryptoInput *input = static_cast<CryptoInput *>(data);
623 int ret = inst->Crypto(input->op, input->id, input->data, input->size, input->iv, input->ivsize);
627 if (inst->eventObject != nullptr) {
629 inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_CRYPTO_DONE);
631 inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_CRYPTO_ERROR);
638 int Authenticator::CommandGenerateSign(Authenticator *inst, void *data)
640 GenerateSignData *signData = static_cast<GenerateSignData *>(data);
641 unsigned char *signedData;
644 signData->status = inst->GenerateSign(signData->data, signData->size, signedData, signedDataSize);
645 if (signData->status == 0) {
646 signData->data = signedData;
647 signData->size = signedDataSize;
650 int ret = inst->asyncCtx.command->Send(COMMAND::GENERATE_SIGN, static_cast<void *>(signData));
652 ErrPrint("Failed to send a key info");
654 signedData = nullptr;
662 int Authenticator::CommandVerifySign(Authenticator *inst, void *data)
664 VerifySignData *signData = static_cast<VerifySignData *>(data);
666 signData->status = inst->VerifySign(signData->signedData, signData->signedDataSize, signData->data, signData->size, signData->authentic);
668 int ret = inst->asyncCtx.command->Send(COMMAND::VERIFY_SIGN, static_cast<void *>(signData));
670 ErrPrint("Failed to send a key info");
678 int Authenticator::CommandGetKey(Authenticator *inst, void *data)
680 long _id = reinterpret_cast<long>(data);
681 beyond_authenticator_key_id id = static_cast<beyond_authenticator_key_id>(_id);
686 info = new KeyInfo();
687 } catch (std::exception &e) {
688 ErrPrint("new: %s", e.what());
697 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY:
698 info->status = inst->GetPrivateKey(info->key, info->size);
700 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY:
701 info->status = inst->GetPublicKey(info->key, info->size);
703 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_CERTIFICATE:
704 info->status = inst->GetCertificate(info->key, info->size);
706 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_SECRET_KEY:
707 info->status = inst->GetSecretKey(info->key, info->size);
710 info->status = -EINVAL;
714 ret = inst->asyncCtx.command->Send(COMMAND::GETKEY, info);
716 ErrPrint("Failed to send a key info");
726 int Authenticator::Activate(void)
730 if (asyncCtx.eventLoop != nullptr) {
731 ret = asyncCtx.eventLoop->Run(10, -1, -1);
733 ErrPrint("Failed to run the event loop");
735 DbgPrint("Event loop is running now");
738 DbgPrint("Event loop is nullptr");
741 activated = (ret == 0);
746 int Authenticator::Prepare(void)
748 if (activated == false) {
749 ErrPrint("Not yet activated");
755 if (asyncCtx.eventLoop != nullptr) {
756 ret = command->Send(COMMAND::GENERATE);
757 DbgPrint("Send a generate request: %d", ret);
759 ret = CommandGenerate(this, nullptr);
765 int Authenticator::CommandCleanup(Authenticator *inst, void *data)
767 EVP_PKEY_free(inst->sslContext.keypair);
768 inst->sslContext.keypair = nullptr;
770 X509_free(inst->sslContext.x509);
771 inst->sslContext.x509 = nullptr;
773 if (inst->eventObject != nullptr) {
774 inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_DEACTIVATE_DONE);
780 int Authenticator::Deactivate(void)
782 if (activated == false) {
783 ErrPrint("Not yet activated");
789 if (asyncCtx.eventLoop != nullptr) {
790 ret = asyncCtx.eventLoop->Stop();
792 ret = CommandCleanup(this, nullptr);
795 activated = !(ret == 0);
799 int Authenticator::CryptoAsymmetric(int opid, beyond_authenticator_key_id id, const void *in, size_t inlen, void *&out, size_t &outlen)
801 int (*operation[])(EVP_PKEY_CTX * ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) = {
806 int (*init[])(EVP_PKEY_CTX * ctx) = {
807 EVP_PKEY_encrypt_init,
808 EVP_PKEY_decrypt_init,
814 EVP_PKEY *_key = nullptr;
816 if (id == BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY) {
817 if (sslContext.keypair == nullptr) {
818 ErrPrint("Private key is not found");
822 key = sslContext.keypair;
823 } else if (id == BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY) {
824 if (sslContext.x509 == nullptr) {
825 ErrPrint("x509 certificate is not found");
829 key = X509_get_pubkey(sslContext.x509);
830 if (key == nullptr) {
831 SSLErrPrint("X509_get_pubkey");
837 ErrPrint("Invalid key id");
841 EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, nullptr);
842 if (ctx == nullptr) {
843 SSLErrPrint("EVP_PKEY_CTX_new");
851 if ((init[opid])(ctx) <= 0) {
852 SSLErrPrint("EVP_PKEY_encrypt_init");
857 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0) {
858 SSLErrPrint("EVP_PKEY_CTX_set_rsa_padding");
863 ret = (operation[opid])(ctx, nullptr, &outlen, static_cast<const unsigned char *>(in), inlen);
865 ErrPrint("Not supported");
868 } else if (ret <= 0) {
869 SSLErrPrint("EVP_PKEY_encrypt or EVP_PKEY_decrypt");
876 out = calloc(1, outlen);
877 if (out == nullptr) {
879 ErrPrintCode(errno, "calloc");
883 if ((operation[opid])(ctx, static_cast<unsigned char *>(out), &outlen, static_cast<const unsigned char *>(in), inlen) <= 0) {
885 SSLErrPrint("EVP_PKEY_encrypt or EVP_PKEY_decrypt");
892 EVP_PKEY_CTX_free(ctx);
900 int Authenticator::CryptoSymmetric(int opid, beyond_authenticator_key_id id, const void *in, size_t inlen, void *&out, size_t &outlen, const void *iv, size_t ivsize)
902 int (*operation[])(EVP_CIPHER_CTX *, unsigned char *, int *, const unsigned char *, int) = {
907 int (*init[])(EVP_CIPHER_CTX *, const EVP_CIPHER *, ENGINE *, const unsigned char *, const unsigned char *) = {
912 int (*finalize[])(EVP_CIPHER_CTX *, unsigned char *, int *) = {
919 EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
920 if (ctx == nullptr) {
924 ret = (init[opid])(ctx, EVP_aes_256_cbc(), nullptr, reinterpret_cast<const unsigned char *>(sslContext.secretKey.c_str()), static_cast<const unsigned char *>(iv));
927 EVP_CIPHER_CTX_free(ctx);
932 // Enable padding: default
933 ret = EVP_CIPHER_CTX_set_padding(ctx, 1);
935 SSLErrPrint("set_padding");
936 EVP_CIPHER_CTX_free(ctx);
941 size_t blockSize = EVP_CIPHER_block_size(EVP_aes_256_cbc());
942 int paddingSize = inlen % blockSize;
943 paddingSize = (paddingSize == 0) ? 0 : (blockSize - paddingSize);
944 outlen = inlen + paddingSize;
946 out = calloc(1, outlen);
947 if (out == nullptr) {
948 ErrPrintCode(errno, "calloc");
949 EVP_CIPHER_CTX_free(ctx);
954 int _outlen = outlen;
955 ret = (operation[opid])(ctx, static_cast<unsigned char *>(out), &_outlen, static_cast<const unsigned char *>(in), inlen);
957 SSLErrPrint("operation");
960 EVP_CIPHER_CTX_free(ctx);
966 ret = (finalize[opid])(ctx, static_cast<unsigned char *>(out) + _outlen, &tmplen);
968 SSLErrPrint("finalize");
971 EVP_CIPHER_CTX_free(ctx);
977 if (_outlen < static_cast<int>(outlen)) {
978 void *_out = realloc(out, _outlen);
979 if (_out == nullptr) {
980 ErrPrintCode(errno, "realloc, go ahead");
988 EVP_CIPHER_CTX_free(ctx);
994 // If this function takes too much time,
995 // it is possible to move this to a new thread.
996 int Authenticator::Crypto(int opid, beyond_authenticator_key_id id, const void *data, int size, const void *iv, int ivsize)
998 if (opid < 0 || opid >= 2) {
999 assert((opid >= 0 && opid < 2) && "Invalid operation");
1000 ErrPrint("Invalid operation");
1004 void *_in = nullptr;
1007 void *out = nullptr;
1011 if (opid == CRYPTO_OP::DECRYPT && sslConfig.enableBase64 == true) {
1013 unsigned char *__in;
1014 ret = DecodeBase64(__in, tmp, static_cast<const char *>(data), size);
1016 ErrPrint("Failed to decode base64");
1019 inlen = static_cast<size_t>(tmp);
1023 in = const_cast<void *>(data);
1024 inlen = static_cast<size_t>(size);
1028 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_CERTIFICATE:
1029 id = beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY;
1031 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY:
1033 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY:
1034 ret = CryptoAsymmetric(opid, id, in, inlen, out, outlen);
1036 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_SECRET_KEY:
1037 ret = CryptoSymmetric(opid, id, in, inlen, out, outlen, iv, ivsize);
1047 CryptoOutput *output = nullptr;
1055 output = new CryptoOutput();
1056 } catch (std::exception &e) {
1057 ErrPrint("new failed: %s", e.what());
1064 if (opid == CRYPTO_OP::ENCRYPT && sslConfig.enableBase64 == true) {
1067 ret = EncodeBase64(_output, _outputSize, static_cast<unsigned char *>(out), outlen);
1071 ErrPrint("EncodeBase64 returns error: %d", ret);
1075 } else if (_output == nullptr || _outputSize <= 0) {
1076 ErrPrint("Invalid encoded data");
1082 output->output = _output;
1083 output->size = _outputSize;
1086 output->output = out;
1087 output->size = outlen;
1092 // ret value should be used to send output result
1093 // the output should be data and status
1094 DbgPrint("return status: %d", ret);
1096 ret = asyncCtx.outputProducer->Send(OUTPUT::CRYPTO_OUTPUT, static_cast<void *>(output));
1107 int Authenticator::Encrypt(beyond_authenticator_key_id id, const void *data, int size, const void *iv, int ivsize)
1109 if (activated == false) {
1110 ErrPrint("Not yet activated");
1114 if (id == beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_SECRET_KEY) {
1115 if (iv == nullptr || ivsize <= 0) {
1116 ErrPrint("Initial vector must be provided");
1119 } else if (id == beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY) {
1120 ErrPrint("Invalid operation");
1125 if (asyncCtx.eventLoop != nullptr) {
1129 input = new CryptoInput();
1130 } catch (std::exception &e) {
1131 ErrPrint("new: %s", e.what());
1135 input->op = CRYPTO_OP::ENCRYPT;
1140 input->ivsize = ivsize;
1142 ret = command->Send(COMMAND::CRYPTO, input);
1148 ret = Crypto(CRYPTO_OP::ENCRYPT, id, data, size, iv, ivsize);
1153 int Authenticator::Decrypt(beyond_authenticator_key_id id, const void *data, int size, const void *iv, int ivsize)
1155 if (activated == false) {
1156 ErrPrint("Not yet activated");
1160 if (id == beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_SECRET_KEY) {
1161 if (iv == nullptr || ivsize <= 0) {
1162 ErrPrint("Initial vector must be provided");
1165 } else if (id == beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY) {
1166 ErrPrint("Invalid operation");
1171 if (asyncCtx.eventLoop != nullptr) {
1175 input = new CryptoInput();
1176 } catch (std::exception &e) {
1177 ErrPrint("new: %s", e.what());
1181 input->op = CRYPTO_OP::DECRYPT;
1186 input->ivsize = ivsize;
1188 ret = command->Send(COMMAND::CRYPTO, input);
1194 ret = Crypto(CRYPTO_OP::DECRYPT, id, data, size, iv, ivsize);
1200 int Authenticator::GetResult(void *&data, int &size)
1202 if (activated == false) {
1203 ErrPrint("Not yet activated");
1208 void *_data = nullptr;
1209 int ret = outputConsumer->Recv(cmdId, _data);
1210 if (cmdId != OUTPUT::CRYPTO_OUTPUT) {
1211 ErrPrint("data: %p", _data);
1215 if (_data == nullptr) {
1218 CryptoOutput *output = static_cast<CryptoOutput *>(_data);
1219 data = output->output;
1220 size = output->size;
1227 int Authenticator::GetPrivateKey(void *&key, int &size)
1230 // Validate to access member variable, if the enableAsync is true
1231 if (sslContext.keypair == nullptr) {
1232 ErrPrint("Private key is not prepared");
1236 BIO *result = BIO_new(BIO_s_mem());
1237 if (result == nullptr) {
1238 SSLErrPrint("BIO_new");
1243 // If it is not activated,
1246 if (PEM_write_bio_PrivateKey(
1247 result, // BIO to write private key to
1248 sslContext.keypair, // EVP_PKEY structure
1249 nullptr, // default cipher for encrypting the key on disk
1250 nullptr, // passphrase required for decrypting the key on disk
1251 0, // length of the passphrase string
1252 nullptr, // callback for requesting a password
1253 nullptr // data to pass to the callback
1255 SSLErrPrint("PEM_write_bio_PrivateKey");
1261 char buffer[DEFAULT_BIO_BUFSZ] = { '\0' };
1262 int sz = BIO_read(result, static_cast<void *>(buffer), sizeof(buffer));
1264 SSLErrPrint("BIO_read");
1273 void *_key = calloc(1, sz + 1);
1274 if (_key == nullptr) {
1276 ErrPrintCode(errno, "calloc");
1279 memcpy(_key, buffer, sz);
1283 DumpToFile("private.key", key, size);
1287 int Authenticator::GetPublicKey(void *&key, int &size)
1290 // Validate to access member variable, if the enableAsync is true
1291 if (sslContext.x509 == nullptr) {
1292 ErrPrint("Certificate is not prepared");
1296 BIO *result = BIO_new(BIO_s_mem());
1297 if (result == nullptr) {
1298 SSLErrPrint("BIO_new");
1303 // If it is not activated,
1306 EVP_PKEY *pubkey = X509_get_pubkey(sslContext.x509);
1307 if (pubkey == nullptr) {
1308 SSLErrPrint("X509_get_pubkey");
1314 RSA *rsa = EVP_PKEY_get1_RSA(pubkey);
1315 if (rsa == nullptr) {
1316 SSLErrPrint("EVP_PKEY_get1_RSA");
1317 EVP_PKEY_free(pubkey);
1324 if (PEM_write_bio_RSAPublicKey(result, rsa) != 1) {
1325 SSLErrPrint("PEM_write_bio_RSAPublicKey");
1329 EVP_PKEY_free(pubkey);
1339 EVP_PKEY_free(pubkey);
1342 char buffer[DEFAULT_BIO_BUFSZ] = { '\0' };
1343 int sz = BIO_read(result, static_cast<void *>(buffer), sizeof(buffer));
1345 SSLErrPrint("BIO_read");
1354 void *_key = calloc(1, sz + 1);
1355 if (_key == nullptr) {
1357 ErrPrintCode(errno, "calloc");
1360 memcpy(_key, buffer, sz);
1364 DumpToFile("public.key", key, size);
1368 int Authenticator::GetCertificate(void *&key, int &size)
1371 // Validate to access member variable, if the enableAsync is true
1372 if (sslContext.x509 == nullptr) {
1373 ErrPrint("Certificate is not prepared");
1377 BIO *result = BIO_new(BIO_s_mem());
1378 if (result == nullptr) {
1379 SSLErrPrint("BIO_new");
1384 // If it is not activated,
1387 if (PEM_write_bio_X509(result, sslContext.x509) != 1) {
1388 SSLErrPrint("PEM_write_bio_X509");
1394 char buffer[DEFAULT_BIO_BUFSZ] = { '\0' };
1395 int sz = BIO_read(result, static_cast<void *>(buffer), sizeof(buffer));
1397 SSLErrPrint("BIO_read");
1406 void *_key = calloc(1, sz + 1);
1407 if (_key == nullptr) {
1409 ErrPrintCode(errno, "calloc");
1412 memcpy(_key, buffer, sz);
1416 DumpToFile("certificate.key", key, size);
1420 int Authenticator::GetSecretKey(void *&key, int &size)
1422 if (sslContext.secretKey.empty() == true) {
1423 ErrPrint("SecretKey is not prepared");
1427 char *output = nullptr;
1429 if (sslConfig.enableBase64 == true) {
1430 int ret = EncodeBase64(output, outputSize, reinterpret_cast<const unsigned char *>(sslContext.secretKey.c_str()), sslContext.secretKey.size());
1433 } else if (output == nullptr) {
1435 } else if (outputSize <= 0) {
1440 outputSize = sslContext.secretKey.size();
1441 output = static_cast<char *>(calloc(1, outputSize));
1442 if (output == nullptr) {
1444 ErrPrintCode(errno, "calloc");
1448 memcpy(output, sslContext.secretKey.c_str(), outputSize);
1453 DumpToFile("secret.key", key, size);
1457 int Authenticator::GetKey(beyond_authenticator_key_id id, void *&key, int &size)
1461 if (asyncCtx.eventLoop != nullptr) {
1462 ret = command->Send(COMMAND::GETKEY, reinterpret_cast<void *>(id));
1464 ErrPrint("Failed to send a command");
1467 void *data = nullptr;
1469 ret = command->Recv(cmdId, data);
1470 if (ret < 0 || cmdId < 0 || data == nullptr) {
1471 ErrPrint("Failed to receive");
1473 KeyInfo *info = static_cast<KeyInfo *>(data);
1483 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY:
1484 return GetPrivateKey(key, size);
1485 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY:
1486 return GetPublicKey(key, size);
1487 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_CERTIFICATE:
1488 return GetCertificate(key, size);
1489 case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_SECRET_KEY:
1490 return GetSecretKey(key, size);
1501 int Authenticator::GenerateSignature(const unsigned char *data, int dataSize, unsigned char *&encoded, int &encodedSize)
1503 if (asyncCtx.eventLoop != nullptr) {
1504 GenerateSignData *_data;
1507 _data = new GenerateSignData();
1508 } catch (std::exception &e) {
1509 ErrPrint("new: %s", e.what());
1513 _data->data = const_cast<unsigned char *>(data);
1514 _data->size = dataSize;
1517 int ret = command->Send(COMMAND::GENERATE_SIGN, reinterpret_cast<void *>(_data));
1519 ErrPrint("Failed to send a command");
1524 void *recvData = nullptr;
1526 ret = command->Recv(cmdId, recvData);
1528 ErrPrint("Failed to receive");
1529 } else if (cmdId < 0 || recvData == nullptr) {
1530 ErrPrint("Invalid command and data");
1533 _data = static_cast<GenerateSignData *>(recvData);
1534 ret = _data->status;
1536 encoded = _data->data;
1537 encodedSize = _data->size;
1547 return GenerateSign(data, dataSize, encoded, encodedSize);
1550 int Authenticator::VerifySignature(unsigned char *signedData, int signedDataSize, const unsigned char *original, int originalSize, bool &authentic)
1552 if (asyncCtx.eventLoop != nullptr) {
1553 VerifySignData *data;
1556 data = new VerifySignData();
1557 } catch (std::exception &e) {
1558 ErrPrint("new: %s", e.what());
1562 data->data = original;
1563 data->size = originalSize;
1564 data->signedData = signedData;
1565 data->signedDataSize = signedDataSize;
1566 data->authentic = false;
1569 int ret = command->Send(COMMAND::VERIFY_SIGN, reinterpret_cast<void *>(data));
1571 ErrPrint("Failed to send a command");
1576 void *_data = nullptr;
1578 ret = command->Recv(cmdId, _data);
1580 ErrPrint("Failed to receive");
1581 } else if (cmdId < 0 || _data == nullptr) {
1582 ErrPrint("Invalid cmdId or cmdData");
1585 data = static_cast<VerifySignData *>(_data);
1588 authentic = data->authentic;
1598 return VerifySign(signedData, signedDataSize, original, originalSize, authentic);
1601 int Authenticator::GenerateSign(const unsigned char *data, int dataSize, unsigned char *&encoded, int &encodedSize)
1603 if (sslContext.keypair == nullptr) {
1604 ErrPrint("keypair is not prepared");
1608 RSA *rsa = EVP_PKEY_get1_RSA(sslContext.keypair);
1609 if (rsa == nullptr) {
1610 SSLErrPrint("EVP_PKEY_get1_RSA");
1614 EVP_PKEY *pKey = EVP_PKEY_new();
1615 if (pKey == nullptr) {
1616 SSLErrPrint("EVP_PKEY_new");
1622 if (EVP_PKEY_assign_RSA(pKey, rsa) != 1) {
1623 SSLErrPrint("EVP_PKEY_assign_RSA");
1626 EVP_PKEY_free(pKey);
1632 EVP_MD_CTX *ctx = EVP_MD_CTX_create();
1634 SSLErrPrint("EVP_MD_CTX_create");
1635 EVP_PKEY_free(pKey);
1640 const EVP_MD *md = EVP_get_digestbyname("SHA256");
1642 SSLErrPrint("EVP_get_digestbyname");
1643 EVP_MD_CTX_destroy(ctx);
1645 EVP_PKEY_free(pKey);
1650 if (EVP_DigestSignInit(ctx, NULL, md, NULL, pKey) <= 0) {
1651 SSLErrPrint("EVP_DigestSignInit");
1652 EVP_MD_CTX_destroy(ctx);
1654 EVP_PKEY_free(pKey);
1659 if (EVP_DigestSignUpdate(ctx, data, dataSize) <= 0) {
1660 SSLErrPrint("EVP_DigestSignUpdate");
1661 EVP_MD_CTX_destroy(ctx);
1663 EVP_PKEY_free(pKey);
1668 if (EVP_DigestSignFinal(ctx, NULL, (size_t *)&encodedSize) <= 0) {
1669 SSLErrPrint("EVP_DigestSignFinal");
1670 EVP_MD_CTX_destroy(ctx);
1672 EVP_PKEY_free(pKey);
1677 unsigned char *_encoded;
1678 _encoded = static_cast<unsigned char *>(calloc(1, encodedSize));
1679 if (_encoded == nullptr) {
1681 ErrPrintCode(errno, "calloc");
1682 EVP_MD_CTX_destroy(ctx);
1684 EVP_PKEY_free(pKey);
1689 if (EVP_DigestSignFinal(ctx, _encoded, (size_t *)&encodedSize) <= 0) {
1690 SSLErrPrint("EVP_DigestSignFinal");
1693 EVP_MD_CTX_destroy(ctx);
1695 EVP_PKEY_free(pKey);
1702 EVP_MD_CTX_destroy(ctx);
1704 EVP_PKEY_free(pKey);
1709 int Authenticator::VerifySign(const unsigned char *signedData, int signedDataSize, const unsigned char *original, int originalSize, bool &authentic)
1712 // If it is not activated,
1714 if (sslContext.x509 == nullptr) {
1715 ErrPrint("Certificate is not prepared");
1719 EVP_PKEY *pubkey = X509_get_pubkey(sslContext.x509);
1720 if (pubkey == nullptr) {
1721 SSLErrPrint("X509_get_pubkey");
1725 RSA *rsa = EVP_PKEY_get1_RSA(pubkey);
1726 if (rsa == nullptr) {
1727 SSLErrPrint("EVP_PKEY_get1_RSA");
1728 EVP_PKEY_free(pubkey);
1733 EVP_PKEY *pKey = EVP_PKEY_new();
1734 if (pKey == nullptr) {
1735 SSLErrPrint("EVP_PKEY_new");
1739 EVP_PKEY_free(pubkey);
1744 if (EVP_PKEY_assign_RSA(pKey, rsa) != 1) {
1745 SSLErrPrint("EVP_PKEY_assign_RSA");
1749 EVP_PKEY_free(pubkey);
1755 EVP_MD_CTX *ctx = EVP_MD_CTX_create();
1757 SSLErrPrint("EVP_MD_CTX_create");
1758 EVP_PKEY_free(pubkey);
1763 const EVP_MD *md = EVP_get_digestbyname("SHA256");
1765 SSLErrPrint("EVP_get_digestbyname");
1766 EVP_MD_CTX_destroy(ctx);
1768 EVP_PKEY_free(pubkey);
1773 if (EVP_DigestVerifyInit(ctx, NULL, md, NULL, pKey) <= 0) {
1774 SSLErrPrint("EVP_DigestVerifyInit");
1775 EVP_MD_CTX_destroy(ctx);
1777 EVP_PKEY_free(pubkey);
1782 if (EVP_DigestVerifyUpdate(ctx, original, originalSize) <= 0) {
1783 SSLErrPrint("EVP_DigestVerifyUpdate");
1784 EVP_MD_CTX_destroy(ctx);
1786 EVP_PKEY_free(pubkey);
1791 int ret = EVP_DigestVerifyFinal(ctx, signedData, signedDataSize);
1792 EVP_MD_CTX_destroy(ctx);
1794 EVP_PKEY_free(pubkey);
1797 authentic = (ret == 1);
1799 return (ret >= 0) ? 0 : -EFAULT;
1802 Authenticator::Authenticator(void)
1804 .bits = DEFAULT_BITS,
1805 .serial = DEFAULT_SERIAL,
1806 .days = DEFAULT_DAYS,
1808 .enableBase64 = true,
1809 .secretKeyBits = DEFAULT_SECRET_KEY_BITS,
1816 .eventLoop = nullptr,
1817 .handlerObject = nullptr,
1819 , eventObject(nullptr)
1821 , authenticator(nullptr)
1825 Authenticator::~Authenticator(void)
1829 /* Add extension using V3 code: we can set the config file as NULL
1830 * because we wont reference any other sections.
1832 int Authenticator::AddExtension(X509 *cert, int nid, char *value, X509 *issuer)
1837 if (issuer == nullptr) {
1841 /* This sets the 'context' of the extensions. */
1842 /* No configuration database */
1843 X509V3_set_ctx_nodb(&ctx);
1845 /* Issuer and subject certs: both the target since it is self signed,
1846 * no request and no CRL
1848 X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
1849 ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
1850 if (ex == nullptr) {
1851 ErrPrint("Failed to call X509V3_EXT_conf_nid (%s)", value);
1855 X509_add_ext(cert, ex, -1);
1856 X509_EXTENSION_free(ex);
1861 int Authenticator::LoadPrivateKey(const char *keyString, int keyLength, EVP_PKEY *&keypair)
1863 BIO *bio = BIO_new(BIO_s_mem());
1864 if (bio == nullptr) {
1865 SSLErrPrint("BIO_new");
1869 if (BIO_write(bio, keyString, keyLength) <= 0) {
1870 SSLErrPrint("BIO_write");
1876 EVP_PKEY *_keypair = PEM_read_bio_PrivateKey(bio, nullptr, 0, 0);
1877 if (_keypair == nullptr) {
1878 SSLErrPrint("BIO_read_bio_PrivateKey");
1890 int Authenticator::LoadSecretKey(void)
1892 if (sslConfig.enableBase64 == true) {
1893 unsigned char *output = nullptr;
1894 int outputLength = 0;
1896 int ret = DecodeBase64(output, outputLength, sslConfig.secretKey.c_str(), BITS_TO_BYTES(sslConfig.secretKeyBits));
1898 ErrPrint("Invalid encoding");
1902 sslContext.secretKey = std::string(reinterpret_cast<char *>(output), outputLength);
1905 sslContext.secretKey = sslConfig.secretKey;
1911 int Authenticator::LoadCertificate(const char *certificateString, int certificateStringLength, X509 *&x509)
1913 BIO *bio = BIO_new(BIO_s_mem());
1914 if (bio == nullptr) {
1915 SSLErrPrint("BIO_new");
1919 if (BIO_write(bio, certificateString, certificateStringLength) <= 0) {
1920 SSLErrPrint("BIO_write");
1926 X509 *_x509 = PEM_read_bio_X509(bio, nullptr, 0, 0);
1927 if (_x509 == nullptr) {
1928 SSLErrPrint("BIO_read_bio_PrivateKey");
1940 int Authenticator::LoadCertificate(void)
1944 if (sslConfig.privateKey.empty() == false) {
1945 EVP_PKEY *pkey = nullptr;
1946 ret = LoadPrivateKey(sslConfig.privateKey.c_str(), sslConfig.privateKey.size(), pkey);
1949 } else if (pkey == nullptr) {
1950 ErrPrint("Unable to load a private key");
1954 DbgPrint("Private key is loaded");
1955 EVP_PKEY_free(sslContext.keypair);
1956 sslContext.keypair = pkey;
1959 if (sslConfig.certificate.empty() == false) {
1960 X509 *x509 = nullptr;
1961 ret = LoadCertificate(sslConfig.certificate.c_str(), sslConfig.certificate.size(), x509);
1966 DbgPrint("Certificate key is loaded");
1967 X509_free(sslContext.x509);
1968 sslContext.x509 = x509;
1974 int Authenticator::GenerateSecretKey(void)
1976 int keyLength = BITS_TO_BYTES(sslConfig.secretKeyBits);
1977 unsigned char *buffer;
1979 buffer = static_cast<unsigned char *>(malloc(keyLength));
1980 if (buffer == nullptr) {
1982 ErrPrintCode(errno, "malloc");
1986 // For a secret key to generate use SSL
1987 if (!RAND_bytes(buffer, keyLength)) {
1988 SSLErrPrint("RAND Failed");
1992 sslContext.secretKey = std::string(reinterpret_cast<char *>(buffer), keyLength);
1997 int Authenticator::GenerateKey(void)
1999 int bits = sslConfig.bits;
2003 EVP_PKEY *keypair = nullptr;
2006 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
2007 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
2008 #ifndef OPENSSL_NO_STDIO
2009 FILE *bio_err = stderr;
2010 #else // OPENSSL_NO_STDIO
2011 BIO *bio_err = BIO_new(BIO_s_mem());
2012 if (bio_err == nullptr) {
2013 ErrPrint("Failed to create a bio");
2016 #endif // OPENSSL_NO_STDIO
2017 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2021 keypair = EVP_PKEY_new();
2022 if (keypair == nullptr) {
2023 SSLErrPrint("EVP_PKEY_new");
2029 if (rsa == nullptr) {
2034 BIGNUM *bn = BN_new();
2035 if (bn == nullptr) {
2040 BN_set_word(bn, DEFAULT_PRIME);
2042 if (RSA_generate_key_ex(rsa, bits, bn, nullptr) == 0) {
2043 SSLErrPrint("RSA_generate_key_ex");
2055 if (EVP_PKEY_assign_RSA(keypair, rsa) == 0) {
2056 SSLErrPrint("EVP_PKEY_assign_RSA");
2064 if (rsa != nullptr) {
2070 ErrPrint("Clean up keypair");
2071 EVP_PKEY_free(keypair);
2074 EVP_PKEY_free(sslContext.keypair);
2075 sslContext.keypair = keypair;
2078 #ifndef OPENSSL_NO_ENGINE
2082 CRYPTO_cleanup_all_ex_data();
2086 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
2087 #ifndef OPENSSL_NO_STDIO
2088 CRYPTO_mem_leaks_fp(bio_err);
2089 #else // OPENSSL_NO_STDIO
2090 CRYPTO_mem_leaks(bio_err);
2092 char buffer[DEFAULT_BIO_BUFSZ];
2093 int sz = BIO_read(bio_err, buffer, sizeof(buffer));
2095 ErrPrint("CRYPTO_mem_leaks: %s", buffer);
2097 SSLErrPrint("BIO_read");
2101 #endif // OPENSSL_NO_STDIO
2103 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2109 int Authenticator::GenerateCertificate(void)
2111 int serial = sslConfig.serial;
2112 int days = sslConfig.days;
2116 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
2117 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
2118 #ifndef OPENSSL_NO_STDIO
2119 FILE *bio_err = stderr;
2120 #else // OPENSSL_NO_STDIO
2121 BIO *bio_err = BIO_new(BIO_s_mem());
2122 if (bio_err == nullptr) {
2123 ErrPrint("Failed to create a bio");
2126 #endif // OPENSSL_NO_STDIO
2127 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2133 if (x509 == nullptr) {
2134 SSLErrPrint("X509_new");
2139 X509_set_version(x509, 2);
2140 X509_set_pubkey(x509, sslContext.keypair);
2141 ASN1_INTEGER_set(X509_get_serialNumber(x509), serial);
2142 X509_gmtime_adj(X509_get_notBefore(x509), 0);
2143 X509_gmtime_adj(X509_get_notAfter(x509), static_cast<long>(DAYS_TO_SECONDS(days)));
2145 X509_NAME *name = X509_get_subject_name(x509);
2146 if (name == nullptr) {
2147 SSLErrPrint("X509_get_subject_name");
2152 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, reinterpret_cast<const unsigned char *>("KR"), -1, -1, 0);
2153 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, reinterpret_cast<const unsigned char *>("BeyonD"), -1, -1, 0);
2154 if (sslConfig.isCA == true) {
2155 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<const unsigned char *>("beyond.net"), -1, -1, 0);
2156 AddExtension(x509, NID_basic_constraints, const_cast<char *>("critical,CA:TRUE,pathlen:0"));
2157 AddExtension(x509, NID_key_usage, const_cast<char *>("critical,keyCertSign,cRLSign,keyEncipherment"));
2158 AddExtension(x509, NID_netscape_cert_type, const_cast<char *>("sslCA,emailCA,objCA"));
2160 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, reinterpret_cast<const unsigned char *>("Inference"), -1, -1, 0);
2161 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<const unsigned char *>("edge.beyond.net"), -1, -1, 0);
2162 AddExtension(x509, NID_basic_constraints, const_cast<char *>("critical,CA:FALSE"));
2163 AddExtension(x509, NID_key_usage, const_cast<char *>("critical,keyCertSign,cRLSign,keyEncipherment,nonRepudiation,digitalSignature"));
2164 AddExtension(x509, NID_ext_key_usage, const_cast<char *>("serverAuth,clientAuth"));
2167 if (sslConfig.alternativeName.empty() == false) {
2168 DbgPrint("Add entry of subjectAltName for the IP Address based authentication (%s)", sslConfig.alternativeName.c_str());
2169 std::string altName = std::string("IP:") + sslConfig.alternativeName;
2170 AddExtension(x509, NID_subject_alt_name, const_cast<char *>(altName.c_str()));
2173 X509_set_subject_name(x509, name);
2175 AddExtension(x509, NID_subject_key_identifier, const_cast<char *>("hash"));
2177 if (authenticator == nullptr) {
2178 X509_set_issuer_name(x509, name);
2179 if (X509_sign(x509, sslContext.keypair, EVP_sha256()) == 0) {
2180 SSLErrPrint("EVP_PKEY_assign_RSA");
2185 void *key = nullptr;
2188 ret = authenticator->GetKey(beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY, key, keyLength);
2190 ErrPrint("Failed to get the private key from the authenticator");
2194 EVP_PKEY *pkey_ca = nullptr;
2195 ret = LoadPrivateKey(static_cast<char *>(key), keyLength, pkey_ca);
2197 ErrPrint("Failed to load the private key");
2199 } else if (pkey_ca == nullptr) {
2200 ErrPrint("Private key is invalid");
2209 ret = authenticator->GetKey(beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_CERTIFICATE, key, keyLength);
2211 ErrPrint("Failed to get the certificate from the authenticator");
2212 EVP_PKEY_free(pkey_ca);
2217 X509 *x509_ca = nullptr;
2218 ret = LoadCertificate(static_cast<char *>(key), keyLength, x509_ca);
2223 ErrPrint("Failed to load the certificate");
2224 EVP_PKEY_free(pkey_ca);
2227 } else if (x509_ca == nullptr) {
2228 ErrPrint("Certiicate is invalid");
2229 EVP_PKEY_free(pkey_ca);
2235 X509_set_issuer_name(x509, X509_get_subject_name(x509_ca));
2236 AddExtension(x509, NID_authority_key_identifier, const_cast<char *>("keyid:always,issuer:always"), x509_ca);
2241 ret = X509_sign(x509, pkey_ca, EVP_sha256());
2242 EVP_PKEY_free(pkey_ca);
2245 SSLErrPrint("X509_sign");
2255 ErrPrint("Clean up x509");
2259 X509_free(sslContext.x509);
2260 sslContext.x509 = x509;
2263 #ifndef OPENSSL_NO_ENGINE
2267 CRYPTO_cleanup_all_ex_data();
2271 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
2272 #ifndef OPENSSL_NO_STDIO
2273 CRYPTO_mem_leaks_fp(bio_err);
2274 #else // OPENSSL_NO_STDIO
2275 CRYPTO_mem_leaks(bio_err);
2277 char buffer[DEFAULT_BIO_BUFSZ];
2278 int sz = BIO_read(bio_err, buffer, sizeof(buffer));
2280 ErrPrint("CRYPTO_mem_leaks: %s", buffer);
2282 SSLErrPrint("BIO_read");
2286 #endif // OPENSSL_NO_STDIO
2288 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2294 int Authenticator::EncodeBase64(char *&output, int &outputLength, const unsigned char *input, int length)
2296 BIO *b64f = BIO_new(BIO_f_base64());
2297 if (b64f == nullptr) {
2298 SSLErrPrint("BIO_new");
2302 BIO *buff = BIO_new(BIO_s_mem());
2303 if (buff == nullptr) {
2304 SSLErrPrint("BIO_new");
2309 buff = BIO_push(b64f, buff);
2310 assert(buff != nullptr && !!"BIO_push() failed");
2312 BIO_set_flags(buff, BIO_FLAGS_BASE64_NO_NL);
2313 int ret = BIO_set_close(buff, BIO_CLOSE);
2314 assert(ret == 1 && !!"BIO_set_close() returns unpredicted value");
2316 ret = BIO_write(buff, input, length);
2318 ErrPrint("Method is not implemented");
2321 } else if (ret <= 0) {
2323 // Nomally, this not an error.
2324 // However, we do not have any case to get into this situation.
2325 // So I just deal it as an error case.
2326 ErrPrint("No data was written");
2331 ret = BIO_flush(buff);
2333 ErrPrint("Failed to do flush");
2338 BUF_MEM *ptr = nullptr;
2339 BIO_get_mem_ptr(buff, &ptr);
2340 if (ptr == nullptr) {
2341 ErrPrint("Failed to get BUF_MEM");
2344 } else if (ptr->length <= 0 || ptr->data == nullptr) {
2345 ErrPrint("Invalid buffer gotten");
2350 char *_output = static_cast<char *>(calloc(1, ptr->length + 1));
2351 if (_output == nullptr) {
2353 ErrPrintCode(errno, "calloc");
2357 memcpy(_output, ptr->data, ptr->length);
2360 outputLength = ptr->length;
2365 int Authenticator::DecodeBase64(unsigned char *&output, int &outputLength, const char *input, int length)
2367 BIO *b64f = BIO_new(BIO_f_base64());
2368 if (b64f == nullptr) {
2369 SSLErrPrint("BIO_new");
2373 BIO *buff = BIO_new_mem_buf(static_cast<const void *>(input), length);
2374 if (buff == nullptr) {
2375 SSLErrPrint("BIO_new_mem_buf");
2381 buff = BIO_push(b64f, buff);
2382 if (buff == nullptr) {
2383 assert(!"BIO_push() failed");
2391 BIO_set_flags(buff, BIO_FLAGS_BASE64_NO_NL);
2392 int ret = BIO_set_close(buff, BIO_CLOSE);
2394 assert(!"BIO_set_close() returns unexpected value");
2395 ErrPrint("BIO_set_close() returns unexpected value");
2397 // Go ahead in case of the release mode.
2401 // We will allocate enough memory for decoding encoded data
2402 // But we can sure that the decoded data must smaller than encoded data
2403 // Therefore, we are going to allocate input size buffer first
2404 // and then reallocate it with its decoded size
2405 int _outputLength = length;
2406 unsigned char *_output = static_cast<unsigned char *>(calloc(1, _outputLength));
2407 if (_output == nullptr) {
2409 ErrPrintCode(errno, "calloc");
2414 _outputLength = BIO_read(buff, _output, _outputLength);
2416 if (_outputLength == -2) {
2417 ErrPrint("Method is not implemented");
2421 } else if (_outputLength <= 0) {
2422 SSLErrPrint("BIO_read");
2429 // Decoded data is not a string,
2430 // it does not necessary to be ended with '\0'
2431 void *__output = static_cast<void *>(realloc(static_cast<void *>(_output), _outputLength));
2432 if (__output == nullptr) {
2434 ErrPrintCode(errno, "realloc");
2435 free(static_cast<void *>(_output));
2440 output = static_cast<unsigned char *>(__output);
2441 outputLength = _outputLength;