be09c3828cbfcf1d180c42ffd1b53af2b14983ab
[platform/core/ml/beyond.git] / subprojects / libbeyond-authenticator_ssl / src / authenticator.cc
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "authenticator.h"
18 #include "authenticator_event_object.h"
19
20 #include "beyond/plugin/authenticator_ssl_plugin.h"
21
22 #include <beyond/platform/beyond_platform.h>
23 #include <beyond/private/beyond_private.h>
24
25 #include <cstdio>
26 #include <cerrno>
27 #include <cstdlib>
28 #include <cstring>
29
30 #include <string>
31 #include <exception>
32 #include <memory>
33
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <sys/types.h>
37 #include <sys/socket.h>
38
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>
52
53 #ifndef OPENSSL_NO_ENGINE
54 #include <openssl/engine.h>
55 #endif
56
57 #include <json/json.h>
58
59 #define DEFAULT_MSG_BUFSZ 256
60 #define DEFAULT_PRIME 65537
61 #define DEFAULT_BIO_BUFSZ 4096
62 // NOTE:
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
71
72 #define DAYS_TO_SECONDS(days) ((days)*24 * 60 * 60)
73 #define BITS_TO_BYTES(bits) ((bits) >> 3)
74
75 #define SSLErrPrint(name)                                      \
76     do {                                                       \
77         char msg[DEFAULT_MSG_BUFSZ];                           \
78         ERR_error_string_n(ERR_get_error(), msg, sizeof(msg)); \
79         ErrPrint(name ": %s", msg);                            \
80     } while (0)
81
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,
89 };
90
91 Authenticator *Authenticator::Create(bool enableAsync)
92 {
93     Authenticator *impl;
94     int pfd[2]; // output
95
96     try {
97         impl = new Authenticator();
98     } catch (std::exception &e) {
99         ErrPrint("new failed: %s", e.what());
100         return nullptr;
101     }
102
103     // NOTE:
104     // eventObject only be created if the async mode is enabled
105     impl->eventObject = nullptr;
106     impl->asyncCtx.handlerObject = nullptr;
107
108     if (pipe2(pfd, O_CLOEXEC) < 0) {
109         ErrPrintCode(errno, "pipe2");
110
111         delete impl;
112         impl = nullptr;
113         return nullptr;
114     }
115
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");
121             }
122             if (close(pfd[1]) < 0) {
123                 ErrPrintCode(errno, "close");
124             }
125
126             delete impl;
127             impl = nullptr;
128             return nullptr;
129         }
130
131         impl->asyncCtx.eventLoop = beyond::EventLoop::Create(true, false);
132         if (impl->asyncCtx.eventLoop == nullptr) {
133             ErrPrint("Failed to create an event loop");
134
135             impl->eventObject->Destroy();
136             impl->eventObject = nullptr;
137
138             if (close(pfd[0]) < 0) {
139                 ErrPrintCode(errno, "close");
140             }
141             if (close(pfd[1]) < 0) {
142                 ErrPrintCode(errno, "close");
143             }
144
145             delete impl;
146             impl = nullptr;
147             return nullptr;
148         }
149
150         impl->asyncCtx.eventLoop->SetStopHandler([](beyond::EventLoop *loop, void *data) -> void {
151             Authenticator *impl = static_cast<Authenticator *>(data);
152             impl->CommandCleanup(impl, nullptr);
153             return;
154         },
155                                                  impl);
156
157         int spfd[2]; // command
158         if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, spfd) < 0) {
159             ErrPrintCode(errno, "socketpair");
160
161             impl->asyncCtx.eventLoop->Destroy();
162             impl->asyncCtx.eventLoop = nullptr;
163
164             impl->eventObject->Destroy();
165             impl->eventObject = nullptr;
166
167             if (close(pfd[0]) < 0) {
168                 ErrPrintCode(errno, "close");
169             }
170
171             if (close(pfd[1]) < 0) {
172                 ErrPrintCode(errno, "close");
173             }
174
175             delete impl;
176             impl = nullptr;
177             return nullptr;
178         }
179
180         impl->command = std::make_unique<beyond::CommandObject>(spfd[0]);
181         impl->asyncCtx.command = std::make_unique<beyond::CommandObject>(spfd[1]);
182
183         impl->asyncCtx.handlerObject = impl->asyncCtx.eventLoop->AddEventHandler(
184             // NOTE:
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);
192
193                 int cmdId = -1;
194                 void *_data = nullptr;
195
196                 int ret = cmdObject->Recv(cmdId, _data);
197                 if (ret < 0) {
198                     ErrPrint("Failed to get the command");
199                     return beyond_handler_return::BEYOND_HANDLER_RETURN_CANCEL;
200                 }
201
202                 if (cmdId >= 0 && cmdId < COMMAND::LAST) {
203                     assert(auth->commandTable[cmdId] != nullptr && "Command handler is nullptr");
204                     ret = auth->commandTable[cmdId](auth, _data);
205                     if (ret < 0) {
206                         DbgPrint("Command Handler returns: %d", ret);
207                     }
208                 } else {
209                     ErrPrint("Invalid command request");
210                 }
211
212                 return beyond_handler_return::BEYOND_HANDLER_RETURN_RENEW;
213             },
214             impl);
215
216         if (impl->asyncCtx.handlerObject == nullptr) {
217             ErrPrint("Failed to add the event handler");
218
219             if (close(spfd[0]) < 0) {
220                 ErrPrintCode(errno, "close");
221             }
222
223             if (close(spfd[1]) < 0) {
224                 ErrPrintCode(errno, "close");
225             }
226
227             impl->asyncCtx.eventLoop->Destroy();
228             impl->asyncCtx.eventLoop = nullptr;
229
230             impl->eventObject->Destroy();
231             impl->eventObject = nullptr;
232
233             if (close(pfd[0]) < 0) {
234                 ErrPrintCode(errno, "close");
235             }
236             if (close(pfd[1]) < 0) {
237                 ErrPrintCode(errno, "close");
238             }
239
240             delete impl;
241             impl = nullptr;
242             return nullptr;
243         }
244     }
245
246     impl->outputConsumer = std::make_unique<beyond::CommandObject>(pfd[0]);
247     impl->asyncCtx.outputProducer = std::make_unique<beyond::CommandObject>(pfd[1]);
248     return impl;
249 }
250
251 const char *Authenticator::GetModuleName(void) const
252 {
253     return Authenticator::NAME;
254 }
255
256 const char *Authenticator::GetModuleType(void) const
257 {
258     return ModuleInterface::TYPE_AUTHENTICATOR;
259 }
260
261 void Authenticator::Destroy(void)
262 {
263     if (asyncCtx.eventLoop != nullptr) {
264         asyncCtx.eventLoop->Stop();
265
266         asyncCtx.eventLoop->Destroy();
267
268         asyncCtx.eventLoop = nullptr;
269
270         if (close(command->GetHandle()) < 0) {
271             ErrPrintCode(errno, "close");
272         }
273
274         if (close(asyncCtx.command->GetHandle()) < 0) {
275             ErrPrintCode(errno, "close");
276         }
277     }
278
279     if (close(outputConsumer->GetHandle()) < 0) {
280         ErrPrintCode(errno, "close");
281     }
282
283     if (close(asyncCtx.outputProducer->GetHandle()) < 0) {
284         ErrPrintCode(errno, "close");
285     }
286
287     delete this;
288 }
289
290 int Authenticator::GetHandle(void) const
291 {
292     return eventObject ? eventObject->GetHandle() : -ENOTSUP;
293 }
294
295 int Authenticator::AddHandler(beyond_event_handler_t handler, int type, void *data)
296 {
297     return eventObject ? eventObject->AddHandler(handler, type, data) : -ENOTSUP;
298 }
299
300 int Authenticator::RemoveHandler(beyond_event_handler_t handler, int type, void *data)
301 {
302     return eventObject ? eventObject->RemoveHandler(handler, type, data) : -ENOTSUP;
303 }
304
305 int Authenticator::FetchEventData(EventObjectInterface::EventData *&data)
306 {
307     return eventObject ? eventObject->FetchEventData(data) : -ENOTSUP;
308 }
309
310 int Authenticator::DestroyEventData(EventObjectInterface::EventData *&data)
311 {
312     return eventObject ? eventObject->DestroyEventData(data) : -ENOTSUP;
313 }
314
315 int Authenticator::ConfigureAuthenticator(void *object)
316 {
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");
321     } else {
322         DbgPrint("Module name is %s", module->GetModuleName());
323     }
324     return 0;
325 }
326
327 int Authenticator::ConfigureSecretKey(void *object)
328 {
329     beyond_authenticator_ssl_config_secret_key *secrets = static_cast<beyond_authenticator_ssl_config_secret_key *>(object);
330
331     if (secrets->key != nullptr) {
332         if (secrets->key_bits <= 0) {
333             ErrPrint("Secret key bits must be provided");
334             return -EINVAL;
335         }
336
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();
342     } else {
343         sslConfig.secretKey.clear();
344         sslConfig.secretKeyBits = DEFAULT_SECRET_KEY_BITS;
345     }
346
347     if (sslConfig.secretKey.empty() == true) {
348         return GenerateSecretKey();
349     }
350
351     return LoadSecretKey();
352 }
353
354 int Authenticator::ConfigureJSON(void *object)
355 {
356     Json::Value root;
357     std::string errors;
358     Json::CharReaderBuilder builder;
359     Json::CharReader *reader = builder.newCharReader();
360
361     if (reader == nullptr) {
362         ErrPrint("Unable to create a json reader");
363         return -EFAULT;
364     }
365
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);
370         return -EINVAL;
371     }
372
373     if (errors.empty() == false) {
374         ErrPrint("Failed to parse the JSON string: %s", errors.c_str());
375         return -EFAULT;
376     }
377
378     /*
379      * NOTE: Sample JSON configuration ("ssl")
380      *
381      * {
382      *    "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",
387      *       "bits": -1,
388      *       "serial": 1,
389      *       "days": 3650,
390      *       "is_ca": 1
391      *    },
392      *    "secret_key": {
393      *       "key": "secret key string",
394      *       "key_bits": 256
395      *    }
396      * }
397      */
398     const Json::Value &secretKey = root["secret_key"];
399     if (secretKey.empty() == false) {
400         beyond_authenticator_ssl_config_secret_key secretKeyOption;
401
402         const Json::Value &keyValue = secretKey["key"];
403         if (keyValue.empty() == false && keyValue.isString() == true) {
404             secretKeyOption.key = keyValue.asCString();
405         } else {
406             secretKeyOption.key = nullptr;
407         }
408
409         const Json::Value &keyBitsValue = secretKey["key_bits"];
410         if (keyBitsValue.empty() == false && keyBitsValue.isInt() == true) {
411             secretKeyOption.key_bits = keyBitsValue.asInt();
412         } else {
413             secretKeyOption.key_bits = -1;
414         }
415
416         int ret = ConfigureSecretKey(&secretKeyOption);
417         if (ret < 0) {
418             ErrPrint("Failed to configure the secret key");
419             return ret;
420         }
421     }
422
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();
429         } else {
430             sslOption.passphrase = nullptr;
431         }
432
433         const Json::Value &privateKeyValue = ssl["private_key"];
434         if (privateKeyValue.empty() == false && privateKeyValue.isString() == true) {
435             sslOption.private_key = privateKeyValue.asCString();
436         } else {
437             sslOption.private_key = nullptr;
438         }
439
440         const Json::Value &certificateValue = ssl["certificate"];
441         if (certificateValue.empty() == false && certificateValue.isString() == true) {
442             sslOption.certificate = certificateValue.asCString();
443         } else {
444             sslOption.certificate = nullptr;
445         }
446
447         const Json::Value &alternativeNameValue = ssl["alternative_name"];
448         if (alternativeNameValue.empty() == false && alternativeNameValue.isString() == true) {
449             sslOption.alternative_name = alternativeNameValue.asCString();
450         } else {
451             sslOption.alternative_name = nullptr;
452         }
453
454         const Json::Value &bitsValue = ssl["bits"];
455         if (bitsValue.empty() == false && bitsValue.isInt() == true) {
456             sslOption.bits = bitsValue.asInt();
457         } else {
458             sslOption.bits = -1;
459         }
460
461         const Json::Value &daysValue = ssl["days"];
462         if (daysValue.empty() == false && daysValue.isInt() == true) {
463             sslOption.days = daysValue.asInt();
464         } else {
465             sslOption.days = -1;
466         }
467
468         const Json::Value &serialValue = ssl["serial"];
469         if (serialValue.empty() == false && serialValue.isInt() == true) {
470             sslOption.serial = serialValue.asInt();
471         } else {
472             sslOption.serial = -1;
473         }
474
475         const Json::Value &isCAValue = ssl["is_ca"];
476         if (isCAValue.empty() == false && isCAValue.isInt() == true) {
477             sslOption.isCA = isCAValue.asInt();
478         } else {
479             sslOption.isCA = -1;
480         }
481
482         const Json::Value &enableBase64Value = ssl["enable_base64"];
483         if (enableBase64Value.empty() == false && enableBase64Value.isInt() == true) {
484             sslOption.enableBase64 = enableBase64Value.asInt();
485         } else {
486             sslOption.enableBase64 = -1;
487         }
488
489         int ret = ConfigureSSL(&sslOption);
490         if (ret < 0) {
491             ErrPrint("Failed to configure the SSL");
492             return ret;
493         }
494     }
495
496     return 0;
497 }
498
499 int Authenticator::ConfigureSSL(void *object)
500 {
501     beyond_authenticator_ssl_config_ssl *ssl = static_cast<beyond_authenticator_ssl_config_ssl *>(object);
502
503     if (ssl->passphrase != nullptr) {
504         sslConfig.passphrase = std::string(ssl->passphrase);
505     } else {
506         sslConfig.passphrase.clear();
507     }
508
509     if (ssl->private_key != nullptr) {
510         sslConfig.privateKey = std::string(ssl->private_key);
511     } else {
512         sslConfig.privateKey.clear();
513     }
514
515     if (ssl->certificate != nullptr) {
516         sslConfig.certificate = std::string(ssl->certificate);
517     } else {
518         sslConfig.certificate.clear();
519     }
520
521     if (ssl->alternative_name != nullptr) {
522         sslConfig.alternativeName = std::string(ssl->alternative_name);
523     } else {
524         sslConfig.alternativeName.clear();
525     }
526
527     if (ssl->bits > 0) {
528         sslConfig.bits = ssl->bits;
529     } else if (ssl->bits == 0) {
530         sslConfig.bits = DEFAULT_BITS;
531     }
532
533     if (ssl->days > 0) {
534         sslConfig.days = ssl->days;
535     } else if (ssl->days == 0) {
536         sslConfig.days = DEFAULT_DAYS;
537     }
538
539     if (ssl->serial > 0) {
540         sslConfig.serial = ssl->serial;
541     } else if (ssl->serial == 0) {
542         sslConfig.serial = DEFAULT_SERIAL;
543     }
544
545     if (ssl->isCA >= 0) {
546         sslConfig.isCA = !!ssl->isCA;
547     } else {
548         sslConfig.isCA = true;
549     }
550
551     if (ssl->enableBase64 >= 0) {
552         sslConfig.enableBase64 = !!ssl->enableBase64;
553     } else {
554         sslConfig.enableBase64 = true;
555     }
556
557     return 0;
558 }
559
560 int Authenticator::Configure(const beyond_config *options)
561 {
562     if (options == nullptr) {
563         return 0;
564     }
565
566     if (options->object == nullptr) {
567         ErrPrint("Configure object is nullptr");
568         return -EINVAL;
569     }
570
571     int ret = -EINVAL;
572     switch (options->type) {
573     case BEYOND_PLUGIN_AUTHENTICATOR_SSL_CONFIG_SSL:
574         ret = ConfigureSSL(options->object);
575         break;
576     case BEYOND_CONFIG_TYPE_AUTHENTICATOR:
577         ret = ConfigureAuthenticator(options->object);
578         break;
579     case BEYOND_CONFIG_TYPE_JSON:
580         ret = ConfigureJSON(options->object);
581         break;
582     case BEYOND_PLUGIN_AUTHENTICATOR_SSL_CONFIG_SECRET_KEY:
583         ret = ConfigureSecretKey(options->object);
584         break;
585     default:
586         break;
587     }
588
589     return ret;
590 }
591
592 int Authenticator::CommandGenerate(Authenticator *inst, void *data)
593 {
594     int ret;
595
596     if (inst->sslConfig.privateKey.empty() == true && inst->sslConfig.certificate.empty() == true) {
597         ret = inst->GenerateKey();
598         if (ret == 0) {
599             ret = inst->GenerateCertificate();
600         }
601     } else {
602         ret = inst->LoadCertificate();
603     }
604
605     if (inst->sslContext.secretKey.empty() == true) {
606         ret = inst->GenerateSecretKey();
607     }
608
609     if (inst->eventObject != nullptr) {
610         if (ret == 0) {
611             inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_PREPARE_DONE);
612         } else {
613             inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_PREPARE_ERROR);
614         }
615     }
616
617     return ret;
618 }
619
620 int Authenticator::CommandCrypto(Authenticator *inst, void *data)
621 {
622     CryptoInput *input = static_cast<CryptoInput *>(data);
623     int ret = inst->Crypto(input->op, input->id, input->data, input->size, input->iv, input->ivsize);
624     delete input;
625     input = nullptr;
626
627     if (inst->eventObject != nullptr) {
628         if (ret == 0) {
629             inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_CRYPTO_DONE);
630         } else {
631             inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_CRYPTO_ERROR);
632         }
633     }
634
635     return ret;
636 }
637
638 int Authenticator::CommandGenerateSign(Authenticator *inst, void *data)
639 {
640     GenerateSignData *signData = static_cast<GenerateSignData *>(data);
641     unsigned char *signedData;
642     int signedDataSize;
643
644     signData->status = inst->GenerateSign(signData->data, signData->size, signedData, signedDataSize);
645     if (signData->status == 0) {
646         signData->data = signedData;
647         signData->size = signedDataSize;
648     }
649
650     int ret = inst->asyncCtx.command->Send(COMMAND::GENERATE_SIGN, static_cast<void *>(signData));
651     if (ret < 0) {
652         ErrPrint("Failed to send a key info");
653         free(signedData);
654         signedData = nullptr;
655         delete signData;
656         signData = nullptr;
657     }
658
659     return ret;
660 }
661
662 int Authenticator::CommandVerifySign(Authenticator *inst, void *data)
663 {
664     VerifySignData *signData = static_cast<VerifySignData *>(data);
665
666     signData->status = inst->VerifySign(signData->signedData, signData->signedDataSize, signData->data, signData->size, signData->authentic);
667
668     int ret = inst->asyncCtx.command->Send(COMMAND::VERIFY_SIGN, static_cast<void *>(signData));
669     if (ret < 0) {
670         ErrPrint("Failed to send a key info");
671         delete signData;
672         signData = nullptr;
673     }
674
675     return ret;
676 }
677
678 int Authenticator::CommandGetKey(Authenticator *inst, void *data)
679 {
680     long _id = reinterpret_cast<long>(data);
681     beyond_authenticator_key_id id = static_cast<beyond_authenticator_key_id>(_id);
682     KeyInfo *info;
683     int ret;
684
685     try {
686         info = new KeyInfo();
687     } catch (std::exception &e) {
688         ErrPrint("new: %s", e.what());
689         return -ENOMEM;
690     }
691
692     info->key = nullptr;
693     info->size = 0;
694     info->status = 0;
695
696     switch (id) {
697     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY:
698         info->status = inst->GetPrivateKey(info->key, info->size);
699         break;
700     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY:
701         info->status = inst->GetPublicKey(info->key, info->size);
702         break;
703     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_CERTIFICATE:
704         info->status = inst->GetCertificate(info->key, info->size);
705         break;
706     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_SECRET_KEY:
707         info->status = inst->GetSecretKey(info->key, info->size);
708         break;
709     default:
710         info->status = -EINVAL;
711         break;
712     }
713
714     ret = inst->asyncCtx.command->Send(COMMAND::GETKEY, info);
715     if (ret < 0) {
716         ErrPrint("Failed to send a key info");
717         free(info->key);
718         info->key = nullptr;
719         delete info;
720         info = nullptr;
721     }
722
723     return ret;
724 }
725
726 int Authenticator::Activate(void)
727 {
728     int ret = 0;
729
730     if (asyncCtx.eventLoop != nullptr) {
731         ret = asyncCtx.eventLoop->Run(10, -1, -1);
732         if (ret < 0) {
733             ErrPrint("Failed to run the event loop");
734         } else {
735             DbgPrint("Event loop is running now");
736         }
737     } else {
738         DbgPrint("Event loop is nullptr");
739     }
740
741     activated = (ret == 0);
742
743     return ret;
744 }
745
746 int Authenticator::Prepare(void)
747 {
748     if (activated == false) {
749         ErrPrint("Not yet activated");
750         return -EILSEQ;
751     }
752
753     int ret;
754
755     if (asyncCtx.eventLoop != nullptr) {
756         ret = command->Send(COMMAND::GENERATE);
757         DbgPrint("Send a generate request: %d", ret);
758     } else {
759         ret = CommandGenerate(this, nullptr);
760     }
761
762     return ret;
763 }
764
765 int Authenticator::CommandCleanup(Authenticator *inst, void *data)
766 {
767     EVP_PKEY_free(inst->sslContext.keypair);
768     inst->sslContext.keypair = nullptr;
769
770     X509_free(inst->sslContext.x509);
771     inst->sslContext.x509 = nullptr;
772
773     if (inst->eventObject != nullptr) {
774         inst->eventObject->PublishEventData(BEYOND_PLUGIN_AUTHENTICATOR_EVENT_TYPE_DEACTIVATE_DONE);
775     }
776
777     return 0;
778 }
779
780 int Authenticator::Deactivate(void)
781 {
782     if (activated == false) {
783         ErrPrint("Not yet activated");
784         return -EILSEQ;
785     }
786
787     int ret;
788
789     if (asyncCtx.eventLoop != nullptr) {
790         ret = asyncCtx.eventLoop->Stop();
791     } else {
792         ret = CommandCleanup(this, nullptr);
793     }
794
795     activated = !(ret == 0);
796     return ret;
797 }
798
799 int Authenticator::CryptoAsymmetric(int opid, beyond_authenticator_key_id id, const void *in, size_t inlen, void *&out, size_t &outlen)
800 {
801     int (*operation[])(EVP_PKEY_CTX * ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) = {
802         EVP_PKEY_encrypt,
803         EVP_PKEY_decrypt,
804     };
805
806     int (*init[])(EVP_PKEY_CTX * ctx) = {
807         EVP_PKEY_encrypt_init,
808         EVP_PKEY_decrypt_init,
809     };
810
811     int ret;
812
813     EVP_PKEY *key;
814     EVP_PKEY *_key = nullptr;
815
816     if (id == BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY) {
817         if (sslContext.keypair == nullptr) {
818             ErrPrint("Private key is not found");
819             return -EINVAL;
820         }
821
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");
826             return -EINVAL;
827         }
828
829         key = X509_get_pubkey(sslContext.x509);
830         if (key == nullptr) {
831             SSLErrPrint("X509_get_pubkey");
832             return -EFAULT;
833         }
834
835         _key = key;
836     } else {
837         ErrPrint("Invalid key id");
838         return -EINVAL;
839     }
840
841     EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, nullptr);
842     if (ctx == nullptr) {
843         SSLErrPrint("EVP_PKEY_CTX_new");
844         EVP_PKEY_free(_key);
845         _key = nullptr;
846         return -EFAULT;
847     }
848
849     ret = 0;
850     do {
851         if ((init[opid])(ctx) <= 0) {
852             SSLErrPrint("EVP_PKEY_encrypt_init");
853             ret = -EFAULT;
854             break;
855         }
856
857         if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0) {
858             SSLErrPrint("EVP_PKEY_CTX_set_rsa_padding");
859             ret = -EFAULT;
860             break;
861         }
862
863         ret = (operation[opid])(ctx, nullptr, &outlen, static_cast<const unsigned char *>(in), inlen);
864         if (ret == -2) {
865             ErrPrint("Not supported");
866             ret = -ENOTSUP;
867             break;
868         } else if (ret <= 0) {
869             SSLErrPrint("EVP_PKEY_encrypt or EVP_PKEY_decrypt");
870             ret = -EFAULT;
871             break;
872         }
873
874         ret = 0;
875
876         out = calloc(1, outlen);
877         if (out == nullptr) {
878             ret = -errno;
879             ErrPrintCode(errno, "calloc");
880             break;
881         }
882
883         if ((operation[opid])(ctx, static_cast<unsigned char *>(out), &outlen, static_cast<const unsigned char *>(in), inlen) <= 0) {
884             ret = -EFAULT;
885             SSLErrPrint("EVP_PKEY_encrypt or EVP_PKEY_decrypt");
886             free(out);
887             out = nullptr;
888             break;
889         }
890     } while (0);
891
892     EVP_PKEY_CTX_free(ctx);
893     ctx = nullptr;
894     EVP_PKEY_free(_key);
895     _key = nullptr;
896
897     return ret;
898 }
899
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)
901 {
902     int (*operation[])(EVP_CIPHER_CTX *, unsigned char *, int *, const unsigned char *, int) = {
903         EVP_EncryptUpdate,
904         EVP_DecryptUpdate,
905     };
906
907     int (*init[])(EVP_CIPHER_CTX *, const EVP_CIPHER *, ENGINE *, const unsigned char *, const unsigned char *) = {
908         EVP_EncryptInit_ex,
909         EVP_DecryptInit_ex,
910     };
911
912     int (*finalize[])(EVP_CIPHER_CTX *, unsigned char *, int *) = {
913         EVP_EncryptFinal_ex,
914         EVP_DecryptFinal_ex,
915     };
916
917     int ret;
918
919     EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
920     if (ctx == nullptr) {
921         return -EFAULT;
922     }
923
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));
925     if (ret != 1) {
926         SSLErrPrint("init");
927         EVP_CIPHER_CTX_free(ctx);
928         ctx = nullptr;
929         return -EFAULT;
930     }
931
932     // Enable padding: default
933     ret = EVP_CIPHER_CTX_set_padding(ctx, 1);
934     if (ret != 1) {
935         SSLErrPrint("set_padding");
936         EVP_CIPHER_CTX_free(ctx);
937         ctx = nullptr;
938         return -EFAULT;
939     }
940
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;
945
946     out = calloc(1, outlen);
947     if (out == nullptr) {
948         ErrPrintCode(errno, "calloc");
949         EVP_CIPHER_CTX_free(ctx);
950         ctx = nullptr;
951         return -ENOMEM;
952     }
953
954     int _outlen = outlen;
955     ret = (operation[opid])(ctx, static_cast<unsigned char *>(out), &_outlen, static_cast<const unsigned char *>(in), inlen);
956     if (ret != 1) {
957         SSLErrPrint("operation");
958         free(out);
959         out = nullptr;
960         EVP_CIPHER_CTX_free(ctx);
961         ctx = nullptr;
962         return -EFAULT;
963     }
964
965     int tmplen = 0;
966     ret = (finalize[opid])(ctx, static_cast<unsigned char *>(out) + _outlen, &tmplen);
967     if (ret != 1) {
968         SSLErrPrint("finalize");
969         free(out);
970         out = nullptr;
971         EVP_CIPHER_CTX_free(ctx);
972         ctx = nullptr;
973         return -EFAULT;
974     }
975
976     _outlen += tmplen;
977     if (_outlen < static_cast<int>(outlen)) {
978         void *_out = realloc(out, _outlen);
979         if (_out == nullptr) {
980             ErrPrintCode(errno, "realloc, go ahead");
981         } else {
982             out = _out;
983         }
984
985         outlen = _outlen;
986     }
987
988     EVP_CIPHER_CTX_free(ctx);
989     ctx = nullptr;
990     return 0;
991 }
992
993 // NOTE:
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)
997 {
998     if (opid < 0 || opid >= 2) {
999         assert((opid >= 0 && opid < 2) && "Invalid operation");
1000         ErrPrint("Invalid operation");
1001         return -EINVAL;
1002     }
1003
1004     void *_in = nullptr;
1005     void *in;
1006     size_t inlen;
1007     void *out = nullptr;
1008     size_t outlen = 0;
1009     int ret = 0;
1010
1011     if (opid == CRYPTO_OP::DECRYPT && sslConfig.enableBase64 == true) {
1012         int tmp;
1013         unsigned char *__in;
1014         ret = DecodeBase64(__in, tmp, static_cast<const char *>(data), size);
1015         if (ret < 0) {
1016             ErrPrint("Failed to decode base64");
1017             return ret;
1018         }
1019         inlen = static_cast<size_t>(tmp);
1020         in = __in;
1021         _in = __in;
1022     } else {
1023         in = const_cast<void *>(data);
1024         inlen = static_cast<size_t>(size);
1025     }
1026
1027     switch (id) {
1028     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_CERTIFICATE:
1029         id = beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY;
1030         FALLTHROUGH;
1031     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY:
1032         FALLTHROUGH;
1033     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY:
1034         ret = CryptoAsymmetric(opid, id, in, inlen, out, outlen);
1035         break;
1036     case beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_SECRET_KEY:
1037         ret = CryptoSymmetric(opid, id, in, inlen, out, outlen, iv, ivsize);
1038         break;
1039     default:
1040         ret = -EINVAL;
1041         break;
1042     }
1043
1044     free(_in);
1045     _in = nullptr;
1046
1047     CryptoOutput *output = nullptr;
1048
1049     do {
1050         if (ret < 0) {
1051             break;
1052         }
1053
1054         try {
1055             output = new CryptoOutput();
1056         } catch (std::exception &e) {
1057             ErrPrint("new failed: %s", e.what());
1058             free(out);
1059             out = nullptr;
1060             ret = -ENOMEM;
1061             break;
1062         }
1063
1064         if (opid == CRYPTO_OP::ENCRYPT && sslConfig.enableBase64 == true) {
1065             char *_output;
1066             int _outputSize;
1067             ret = EncodeBase64(_output, _outputSize, static_cast<unsigned char *>(out), outlen);
1068             free(out);
1069             out = nullptr;
1070             if (ret < 0) {
1071                 ErrPrint("EncodeBase64 returns error: %d", ret);
1072                 delete output;
1073                 output = nullptr;
1074                 break;
1075             } else if (_output == nullptr || _outputSize <= 0) {
1076                 ErrPrint("Invalid encoded data");
1077                 delete output;
1078                 output = nullptr;
1079                 ret = -EINVAL;
1080                 break;
1081             }
1082             output->output = _output;
1083             output->size = _outputSize;
1084             out = _output;
1085         } else {
1086             output->output = out;
1087             output->size = outlen;
1088         }
1089     } while (0);
1090
1091     // TODO:
1092     // ret value should be used to send output result
1093     // the output should be data and status
1094     DbgPrint("return status: %d", ret);
1095
1096     ret = asyncCtx.outputProducer->Send(OUTPUT::CRYPTO_OUTPUT, static_cast<void *>(output));
1097     if (ret < 0) {
1098         delete output;
1099         output = nullptr;
1100         free(out);
1101         out = nullptr;
1102     }
1103
1104     return ret;
1105 }
1106
1107 int Authenticator::Encrypt(beyond_authenticator_key_id id, const void *data, int size, const void *iv, int ivsize)
1108 {
1109     if (activated == false) {
1110         ErrPrint("Not yet activated");
1111         return -EILSEQ;
1112     }
1113
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");
1117             return -EINVAL;
1118         }
1119     } else if (id == beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY) {
1120         ErrPrint("Invalid operation");
1121         return -EINVAL;
1122     }
1123
1124     int ret;
1125     if (asyncCtx.eventLoop != nullptr) {
1126         CryptoInput *input;
1127
1128         try {
1129             input = new CryptoInput();
1130         } catch (std::exception &e) {
1131             ErrPrint("new: %s", e.what());
1132             return -ENOMEM;
1133         }
1134
1135         input->op = CRYPTO_OP::ENCRYPT;
1136         input->id = id;
1137         input->data = data;
1138         input->size = size;
1139         input->iv = iv;
1140         input->ivsize = ivsize;
1141
1142         ret = command->Send(COMMAND::CRYPTO, input);
1143         if (ret < 0) {
1144             delete input;
1145             input = nullptr;
1146         }
1147     } else {
1148         ret = Crypto(CRYPTO_OP::ENCRYPT, id, data, size, iv, ivsize);
1149     }
1150     return ret;
1151 }
1152
1153 int Authenticator::Decrypt(beyond_authenticator_key_id id, const void *data, int size, const void *iv, int ivsize)
1154 {
1155     if (activated == false) {
1156         ErrPrint("Not yet activated");
1157         return -EILSEQ;
1158     }
1159
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");
1163             return -EINVAL;
1164         }
1165     } else if (id == beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PUBLIC_KEY) {
1166         ErrPrint("Invalid operation");
1167         return -EINVAL;
1168     }
1169
1170     int ret;
1171     if (asyncCtx.eventLoop != nullptr) {
1172         CryptoInput *input;
1173
1174         try {
1175             input = new CryptoInput();
1176         } catch (std::exception &e) {
1177             ErrPrint("new: %s", e.what());
1178             return -ENOMEM;
1179         }
1180
1181         input->op = CRYPTO_OP::DECRYPT;
1182         input->id = id;
1183         input->data = data;
1184         input->size = size;
1185         input->iv = iv;
1186         input->ivsize = ivsize;
1187
1188         ret = command->Send(COMMAND::CRYPTO, input);
1189         if (ret < 0) {
1190             delete input;
1191             input = nullptr;
1192         }
1193     } else {
1194         ret = Crypto(CRYPTO_OP::DECRYPT, id, data, size, iv, ivsize);
1195     }
1196
1197     return ret;
1198 }
1199
1200 int Authenticator::GetResult(void *&data, int &size)
1201 {
1202     if (activated == false) {
1203         ErrPrint("Not yet activated");
1204         return -EILSEQ;
1205     }
1206
1207     int cmdId = -1;
1208     void *_data = nullptr;
1209     int ret = outputConsumer->Recv(cmdId, _data);
1210     if (cmdId != OUTPUT::CRYPTO_OUTPUT) {
1211         ErrPrint("data: %p", _data);
1212         return -EFAULT;
1213     }
1214
1215     if (_data == nullptr) {
1216         ret = -EINVAL;
1217     } else {
1218         CryptoOutput *output = static_cast<CryptoOutput *>(_data);
1219         data = output->output;
1220         size = output->size;
1221         delete output;
1222         output = nullptr;
1223     }
1224     return ret;
1225 }
1226
1227 int Authenticator::GetPrivateKey(void *&key, int &size)
1228 {
1229     // TODO:
1230     // Validate to access member variable, if the enableAsync is true
1231     if (sslContext.keypair == nullptr) {
1232         ErrPrint("Private key is not prepared");
1233         return -EINVAL;
1234     }
1235
1236     BIO *result = BIO_new(BIO_s_mem());
1237     if (result == nullptr) {
1238         SSLErrPrint("BIO_new");
1239         return -EFAULT;
1240     }
1241
1242     // TODO:
1243     // If it is not activated,
1244     // return -EILSEQ;
1245
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
1254             ) != 1) {
1255         SSLErrPrint("PEM_write_bio_PrivateKey");
1256         BIO_free(result);
1257         result = nullptr;
1258         return -EFAULT;
1259     }
1260
1261     char buffer[DEFAULT_BIO_BUFSZ] = { '\0' };
1262     int sz = BIO_read(result, static_cast<void *>(buffer), sizeof(buffer));
1263     if (sz <= 0) {
1264         SSLErrPrint("BIO_read");
1265         BIO_free(result);
1266         result = nullptr;
1267         return -EFAULT;
1268     }
1269
1270     BIO_free(result);
1271     result = nullptr;
1272
1273     void *_key = calloc(1, sz + 1);
1274     if (_key == nullptr) {
1275         int ret = -errno;
1276         ErrPrintCode(errno, "calloc");
1277         return ret;
1278     }
1279     memcpy(_key, buffer, sz);
1280
1281     key = _key;
1282     size = sz;
1283     DumpToFile("private.key", key, size);
1284     return 0;
1285 }
1286
1287 int Authenticator::GetPublicKey(void *&key, int &size)
1288 {
1289     // TODO:
1290     // Validate to access member variable, if the enableAsync is true
1291     if (sslContext.x509 == nullptr) {
1292         ErrPrint("Certificate is not prepared");
1293         return -EINVAL;
1294     }
1295
1296     BIO *result = BIO_new(BIO_s_mem());
1297     if (result == nullptr) {
1298         SSLErrPrint("BIO_new");
1299         return -EFAULT;
1300     }
1301
1302     // TODO:
1303     // If it is not activated,
1304     // return -EILSEQ;
1305
1306     EVP_PKEY *pubkey = X509_get_pubkey(sslContext.x509);
1307     if (pubkey == nullptr) {
1308         SSLErrPrint("X509_get_pubkey");
1309         BIO_free(result);
1310         result = nullptr;
1311         return -EFAULT;
1312     }
1313
1314     RSA *rsa = EVP_PKEY_get1_RSA(pubkey);
1315     if (rsa == nullptr) {
1316         SSLErrPrint("EVP_PKEY_get1_RSA");
1317         EVP_PKEY_free(pubkey);
1318         pubkey = nullptr;
1319         BIO_free(result);
1320         result = nullptr;
1321         return -EFAULT;
1322     }
1323
1324     if (PEM_write_bio_RSAPublicKey(result, rsa) != 1) {
1325         SSLErrPrint("PEM_write_bio_RSAPublicKey");
1326         RSA_free(rsa);
1327         rsa = nullptr;
1328
1329         EVP_PKEY_free(pubkey);
1330         pubkey = nullptr;
1331         BIO_free(result);
1332         result = nullptr;
1333         return -EFAULT;
1334     }
1335
1336     RSA_free(rsa);
1337     rsa = nullptr;
1338
1339     EVP_PKEY_free(pubkey);
1340     pubkey = nullptr;
1341
1342     char buffer[DEFAULT_BIO_BUFSZ] = { '\0' };
1343     int sz = BIO_read(result, static_cast<void *>(buffer), sizeof(buffer));
1344     if (sz <= 0) {
1345         SSLErrPrint("BIO_read");
1346         BIO_free(result);
1347         result = nullptr;
1348         return -EFAULT;
1349     }
1350
1351     BIO_free(result);
1352     result = nullptr;
1353
1354     void *_key = calloc(1, sz + 1);
1355     if (_key == nullptr) {
1356         int ret = -errno;
1357         ErrPrintCode(errno, "calloc");
1358         return ret;
1359     }
1360     memcpy(_key, buffer, sz);
1361
1362     key = _key;
1363     size = sz;
1364     DumpToFile("public.key", key, size);
1365     return 0;
1366 }
1367
1368 int Authenticator::GetCertificate(void *&key, int &size)
1369 {
1370     // TODO:
1371     // Validate to access member variable, if the enableAsync is true
1372     if (sslContext.x509 == nullptr) {
1373         ErrPrint("Certificate is not prepared");
1374         return -EINVAL;
1375     }
1376
1377     BIO *result = BIO_new(BIO_s_mem());
1378     if (result == nullptr) {
1379         SSLErrPrint("BIO_new");
1380         return -EFAULT;
1381     }
1382
1383     // TODO:
1384     // If it is not activated,
1385     // return -EILSEQ;
1386
1387     if (PEM_write_bio_X509(result, sslContext.x509) != 1) {
1388         SSLErrPrint("PEM_write_bio_X509");
1389         BIO_free(result);
1390         result = nullptr;
1391         return -EFAULT;
1392     }
1393
1394     char buffer[DEFAULT_BIO_BUFSZ] = { '\0' };
1395     int sz = BIO_read(result, static_cast<void *>(buffer), sizeof(buffer));
1396     if (sz <= 0) {
1397         SSLErrPrint("BIO_read");
1398         BIO_free(result);
1399         result = nullptr;
1400         return -EFAULT;
1401     }
1402
1403     BIO_free(result);
1404     result = nullptr;
1405
1406     void *_key = calloc(1, sz + 1);
1407     if (_key == nullptr) {
1408         int ret = -errno;
1409         ErrPrintCode(errno, "calloc");
1410         return ret;
1411     }
1412     memcpy(_key, buffer, sz);
1413
1414     key = _key;
1415     size = sz;
1416     DumpToFile("certificate.key", key, size);
1417     return 0;
1418 }
1419
1420 int Authenticator::GetSecretKey(void *&key, int &size)
1421 {
1422     if (sslContext.secretKey.empty() == true) {
1423         ErrPrint("SecretKey is not prepared");
1424         return -EINVAL;
1425     }
1426
1427     char *output = nullptr;
1428     int outputSize = 0;
1429     if (sslConfig.enableBase64 == true) {
1430         int ret = EncodeBase64(output, outputSize, reinterpret_cast<const unsigned char *>(sslContext.secretKey.c_str()), sslContext.secretKey.size());
1431         if (ret < 0) {
1432             return ret;
1433         } else if (output == nullptr) {
1434             return -EINVAL;
1435         } else if (outputSize <= 0) {
1436             free(output);
1437             return -EINVAL;
1438         }
1439     } else {
1440         outputSize = sslContext.secretKey.size();
1441         output = static_cast<char *>(calloc(1, outputSize));
1442         if (output == nullptr) {
1443             int ret = -errno;
1444             ErrPrintCode(errno, "calloc");
1445             return ret;
1446         }
1447
1448         memcpy(output, sslContext.secretKey.c_str(), outputSize);
1449     }
1450
1451     key = output;
1452     size = outputSize;
1453     DumpToFile("secret.key", key, size);
1454     return 0;
1455 }
1456
1457 int Authenticator::GetKey(beyond_authenticator_key_id id, void *&key, int &size)
1458 {
1459     int ret;
1460
1461     if (asyncCtx.eventLoop != nullptr) {
1462         ret = command->Send(COMMAND::GETKEY, reinterpret_cast<void *>(id));
1463         if (ret < 0) {
1464             ErrPrint("Failed to send a command");
1465         } else {
1466             int cmdId = -1;
1467             void *data = nullptr;
1468
1469             ret = command->Recv(cmdId, data);
1470             if (ret < 0 || cmdId < 0 || data == nullptr) {
1471                 ErrPrint("Failed to receive");
1472             } else {
1473                 KeyInfo *info = static_cast<KeyInfo *>(data);
1474                 key = info->key;
1475                 size = info->size;
1476                 ret = info->status;
1477                 delete info;
1478                 info = nullptr;
1479             }
1480         }
1481     } else {
1482         switch (id) {
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);
1491             break;
1492         default:
1493             ret = -EINVAL;
1494             break;
1495         }
1496     }
1497
1498     return ret;
1499 }
1500
1501 int Authenticator::GenerateSignature(const unsigned char *data, int dataSize, unsigned char *&encoded, int &encodedSize)
1502 {
1503     if (asyncCtx.eventLoop != nullptr) {
1504         GenerateSignData *_data;
1505
1506         try {
1507             _data = new GenerateSignData();
1508         } catch (std::exception &e) {
1509             ErrPrint("new: %s", e.what());
1510             return -ENOMEM;
1511         }
1512
1513         _data->data = const_cast<unsigned char *>(data);
1514         _data->size = dataSize;
1515         _data->status = 0;
1516
1517         int ret = command->Send(COMMAND::GENERATE_SIGN, reinterpret_cast<void *>(_data));
1518         if (ret < 0) {
1519             ErrPrint("Failed to send a command");
1520             delete _data;
1521             _data = nullptr;
1522         } else {
1523             int cmdId = -1;
1524             void *recvData = nullptr;
1525
1526             ret = command->Recv(cmdId, recvData);
1527             if (ret < 0) {
1528                 ErrPrint("Failed to receive");
1529             } else if (cmdId < 0 || recvData == nullptr) {
1530                 ErrPrint("Invalid command and data");
1531                 ret = -EINVAL;
1532             } else {
1533                 _data = static_cast<GenerateSignData *>(recvData);
1534                 ret = _data->status;
1535                 if (ret == 0) {
1536                     encoded = _data->data;
1537                     encodedSize = _data->size;
1538                 }
1539                 delete _data;
1540                 _data = nullptr;
1541             }
1542         }
1543
1544         return ret;
1545     }
1546
1547     return GenerateSign(data, dataSize, encoded, encodedSize);
1548 }
1549
1550 int Authenticator::VerifySignature(unsigned char *signedData, int signedDataSize, const unsigned char *original, int originalSize, bool &authentic)
1551 {
1552     if (asyncCtx.eventLoop != nullptr) {
1553         VerifySignData *data;
1554
1555         try {
1556             data = new VerifySignData();
1557         } catch (std::exception &e) {
1558             ErrPrint("new: %s", e.what());
1559             return -ENOMEM;
1560         }
1561
1562         data->data = original;
1563         data->size = originalSize;
1564         data->signedData = signedData;
1565         data->signedDataSize = signedDataSize;
1566         data->authentic = false;
1567         data->status = 0;
1568
1569         int ret = command->Send(COMMAND::VERIFY_SIGN, reinterpret_cast<void *>(data));
1570         if (ret < 0) {
1571             ErrPrint("Failed to send a command");
1572             delete data;
1573             data = nullptr;
1574         } else {
1575             int cmdId = -1;
1576             void *_data = nullptr;
1577
1578             ret = command->Recv(cmdId, _data);
1579             if (ret < 0) {
1580                 ErrPrint("Failed to receive");
1581             } else if (cmdId < 0 || _data == nullptr) {
1582                 ErrPrint("Invalid cmdId or cmdData");
1583                 ret = -EINVAL;
1584             } else {
1585                 data = static_cast<VerifySignData *>(_data);
1586                 ret = data->status;
1587                 if (ret == 0) {
1588                     authentic = data->authentic;
1589                 }
1590                 delete data;
1591                 data = nullptr;
1592             }
1593         }
1594
1595         return ret;
1596     }
1597
1598     return VerifySign(signedData, signedDataSize, original, originalSize, authentic);
1599 }
1600
1601 int Authenticator::GenerateSign(const unsigned char *data, int dataSize, unsigned char *&encoded, int &encodedSize)
1602 {
1603     if (sslContext.keypair == nullptr) {
1604         ErrPrint("keypair is not prepared");
1605         return -EINVAL;
1606     }
1607
1608     RSA *rsa = EVP_PKEY_get1_RSA(sslContext.keypair);
1609     if (rsa == nullptr) {
1610         SSLErrPrint("EVP_PKEY_get1_RSA");
1611         return -EFAULT;
1612     }
1613
1614     EVP_PKEY *pKey = EVP_PKEY_new();
1615     if (pKey == nullptr) {
1616         SSLErrPrint("EVP_PKEY_new");
1617         RSA_free(rsa);
1618         rsa = nullptr;
1619         return -EFAULT;
1620     }
1621
1622     if (EVP_PKEY_assign_RSA(pKey, rsa) != 1) {
1623         SSLErrPrint("EVP_PKEY_assign_RSA");
1624         RSA_free(rsa);
1625         rsa = nullptr;
1626         EVP_PKEY_free(pKey);
1627         pKey = nullptr;
1628         return -EFAULT;
1629     }
1630     rsa = nullptr;
1631
1632     EVP_MD_CTX *ctx = EVP_MD_CTX_create();
1633     if (ctx == NULL) {
1634         SSLErrPrint("EVP_MD_CTX_create");
1635         EVP_PKEY_free(pKey);
1636         pKey = nullptr;
1637         return -EFAULT;
1638     }
1639
1640     const EVP_MD *md = EVP_get_digestbyname("SHA256");
1641     if (md == NULL) {
1642         SSLErrPrint("EVP_get_digestbyname");
1643         EVP_MD_CTX_destroy(ctx);
1644         ctx = nullptr;
1645         EVP_PKEY_free(pKey);
1646         pKey = nullptr;
1647         return -EFAULT;
1648     }
1649
1650     if (EVP_DigestSignInit(ctx, NULL, md, NULL, pKey) <= 0) {
1651         SSLErrPrint("EVP_DigestSignInit");
1652         EVP_MD_CTX_destroy(ctx);
1653         ctx = nullptr;
1654         EVP_PKEY_free(pKey);
1655         pKey = nullptr;
1656         return -EFAULT;
1657     }
1658
1659     if (EVP_DigestSignUpdate(ctx, data, dataSize) <= 0) {
1660         SSLErrPrint("EVP_DigestSignUpdate");
1661         EVP_MD_CTX_destroy(ctx);
1662         ctx = nullptr;
1663         EVP_PKEY_free(pKey);
1664         pKey = nullptr;
1665         return -EFAULT;
1666     }
1667
1668     if (EVP_DigestSignFinal(ctx, NULL, (size_t *)&encodedSize) <= 0) {
1669         SSLErrPrint("EVP_DigestSignFinal");
1670         EVP_MD_CTX_destroy(ctx);
1671         ctx = nullptr;
1672         EVP_PKEY_free(pKey);
1673         pKey = nullptr;
1674         return -EFAULT;
1675     }
1676
1677     unsigned char *_encoded;
1678     _encoded = static_cast<unsigned char *>(calloc(1, encodedSize));
1679     if (_encoded == nullptr) {
1680         int ret = -errno;
1681         ErrPrintCode(errno, "calloc");
1682         EVP_MD_CTX_destroy(ctx);
1683         ctx = nullptr;
1684         EVP_PKEY_free(pKey);
1685         pKey = nullptr;
1686         return ret;
1687     }
1688
1689     if (EVP_DigestSignFinal(ctx, _encoded, (size_t *)&encodedSize) <= 0) {
1690         SSLErrPrint("EVP_DigestSignFinal");
1691         free(_encoded);
1692         _encoded = nullptr;
1693         EVP_MD_CTX_destroy(ctx);
1694         ctx = nullptr;
1695         EVP_PKEY_free(pKey);
1696         pKey = nullptr;
1697         return -EFAULT;
1698     }
1699
1700     encoded = _encoded;
1701
1702     EVP_MD_CTX_destroy(ctx);
1703     ctx = nullptr;
1704     EVP_PKEY_free(pKey);
1705     pKey = nullptr;
1706     return 0;
1707 }
1708
1709 int Authenticator::VerifySign(const unsigned char *signedData, int signedDataSize, const unsigned char *original, int originalSize, bool &authentic)
1710 {
1711     // TODO:
1712     // If it is not activated,
1713     // return -EILSEQ;
1714     if (sslContext.x509 == nullptr) {
1715         ErrPrint("Certificate is not prepared");
1716         return -EINVAL;
1717     }
1718
1719     EVP_PKEY *pubkey = X509_get_pubkey(sslContext.x509);
1720     if (pubkey == nullptr) {
1721         SSLErrPrint("X509_get_pubkey");
1722         return -EFAULT;
1723     }
1724
1725     RSA *rsa = EVP_PKEY_get1_RSA(pubkey);
1726     if (rsa == nullptr) {
1727         SSLErrPrint("EVP_PKEY_get1_RSA");
1728         EVP_PKEY_free(pubkey);
1729         pubkey = nullptr;
1730         return -EFAULT;
1731     }
1732
1733     EVP_PKEY *pKey = EVP_PKEY_new();
1734     if (pKey == nullptr) {
1735         SSLErrPrint("EVP_PKEY_new");
1736         RSA_free(rsa);
1737         rsa = nullptr;
1738
1739         EVP_PKEY_free(pubkey);
1740         pubkey = nullptr;
1741         return -EFAULT;
1742     }
1743
1744     if (EVP_PKEY_assign_RSA(pKey, rsa) != 1) {
1745         SSLErrPrint("EVP_PKEY_assign_RSA");
1746         RSA_free(rsa);
1747         rsa = nullptr;
1748
1749         EVP_PKEY_free(pubkey);
1750         pubkey = nullptr;
1751         return -EFAULT;
1752     }
1753     rsa = nullptr;
1754
1755     EVP_MD_CTX *ctx = EVP_MD_CTX_create();
1756     if (ctx == NULL) {
1757         SSLErrPrint("EVP_MD_CTX_create");
1758         EVP_PKEY_free(pubkey);
1759         pubkey = nullptr;
1760         return -EFAULT;
1761     }
1762
1763     const EVP_MD *md = EVP_get_digestbyname("SHA256");
1764     if (md == NULL) {
1765         SSLErrPrint("EVP_get_digestbyname");
1766         EVP_MD_CTX_destroy(ctx);
1767         ctx = nullptr;
1768         EVP_PKEY_free(pubkey);
1769         pubkey = nullptr;
1770         return -EFAULT;
1771     }
1772
1773     if (EVP_DigestVerifyInit(ctx, NULL, md, NULL, pKey) <= 0) {
1774         SSLErrPrint("EVP_DigestVerifyInit");
1775         EVP_MD_CTX_destroy(ctx);
1776         ctx = nullptr;
1777         EVP_PKEY_free(pubkey);
1778         pubkey = nullptr;
1779         return -EFAULT;
1780     }
1781
1782     if (EVP_DigestVerifyUpdate(ctx, original, originalSize) <= 0) {
1783         SSLErrPrint("EVP_DigestVerifyUpdate");
1784         EVP_MD_CTX_destroy(ctx);
1785         ctx = nullptr;
1786         EVP_PKEY_free(pubkey);
1787         pubkey = nullptr;
1788         return -EFAULT;
1789     }
1790
1791     int ret = EVP_DigestVerifyFinal(ctx, signedData, signedDataSize);
1792     EVP_MD_CTX_destroy(ctx);
1793     ctx = nullptr;
1794     EVP_PKEY_free(pubkey);
1795     pubkey = nullptr;
1796
1797     authentic = (ret == 1);
1798
1799     return (ret >= 0) ? 0 : -EFAULT;
1800 }
1801
1802 Authenticator::Authenticator(void)
1803     : sslConfig{
1804         .bits = DEFAULT_BITS,
1805         .serial = DEFAULT_SERIAL,
1806         .days = DEFAULT_DAYS,
1807         .isCA = true,
1808         .enableBase64 = true,
1809         .secretKeyBits = DEFAULT_SECRET_KEY_BITS,
1810     }
1811     , sslContext{
1812         .x509 = nullptr,
1813         .keypair = nullptr,
1814     }
1815     , asyncCtx{
1816         .eventLoop = nullptr,
1817         .handlerObject = nullptr,
1818     }
1819     , eventObject(nullptr)
1820     , activated(false)
1821     , authenticator(nullptr)
1822 {
1823 }
1824
1825 Authenticator::~Authenticator(void)
1826 {
1827 }
1828
1829 /* Add extension using V3 code: we can set the config file as NULL
1830  * because we wont reference any other sections.
1831  */
1832 int Authenticator::AddExtension(X509 *cert, int nid, char *value, X509 *issuer)
1833 {
1834     X509_EXTENSION *ex;
1835     X509V3_CTX ctx;
1836
1837     if (issuer == nullptr) {
1838         issuer = cert;
1839     }
1840
1841     /* This sets the 'context' of the extensions. */
1842     /* No configuration database */
1843     X509V3_set_ctx_nodb(&ctx);
1844
1845     /* Issuer and subject certs: both the target since it is self signed,
1846          * no request and no CRL
1847          */
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);
1852         return -EFAULT;
1853     }
1854
1855     X509_add_ext(cert, ex, -1);
1856     X509_EXTENSION_free(ex);
1857     ex = nullptr;
1858     return 0;
1859 }
1860
1861 int Authenticator::LoadPrivateKey(const char *keyString, int keyLength, EVP_PKEY *&keypair)
1862 {
1863     BIO *bio = BIO_new(BIO_s_mem());
1864     if (bio == nullptr) {
1865         SSLErrPrint("BIO_new");
1866         return -EFAULT;
1867     }
1868
1869     if (BIO_write(bio, keyString, keyLength) <= 0) {
1870         SSLErrPrint("BIO_write");
1871         BIO_free(bio);
1872         bio = nullptr;
1873         return -EFAULT;
1874     }
1875
1876     EVP_PKEY *_keypair = PEM_read_bio_PrivateKey(bio, nullptr, 0, 0);
1877     if (_keypair == nullptr) {
1878         SSLErrPrint("BIO_read_bio_PrivateKey");
1879         BIO_free(bio);
1880         bio = nullptr;
1881         return -EFAULT;
1882     }
1883
1884     BIO_free(bio);
1885     bio = nullptr;
1886     keypair = _keypair;
1887     return 0;
1888 }
1889
1890 int Authenticator::LoadSecretKey(void)
1891 {
1892     if (sslConfig.enableBase64 == true) {
1893         unsigned char *output = nullptr;
1894         int outputLength = 0;
1895
1896         int ret = DecodeBase64(output, outputLength, sslConfig.secretKey.c_str(), BITS_TO_BYTES(sslConfig.secretKeyBits));
1897         if (ret < 0) {
1898             ErrPrint("Invalid encoding");
1899             return ret;
1900         }
1901
1902         sslContext.secretKey = std::string(reinterpret_cast<char *>(output), outputLength);
1903         free(output);
1904     } else {
1905         sslContext.secretKey = sslConfig.secretKey;
1906     }
1907
1908     return 0;
1909 }
1910
1911 int Authenticator::LoadCertificate(const char *certificateString, int certificateStringLength, X509 *&x509)
1912 {
1913     BIO *bio = BIO_new(BIO_s_mem());
1914     if (bio == nullptr) {
1915         SSLErrPrint("BIO_new");
1916         return -EFAULT;
1917     }
1918
1919     if (BIO_write(bio, certificateString, certificateStringLength) <= 0) {
1920         SSLErrPrint("BIO_write");
1921         BIO_free(bio);
1922         bio = nullptr;
1923         return -EFAULT;
1924     }
1925
1926     X509 *_x509 = PEM_read_bio_X509(bio, nullptr, 0, 0);
1927     if (_x509 == nullptr) {
1928         SSLErrPrint("BIO_read_bio_PrivateKey");
1929         BIO_free(bio);
1930         bio = nullptr;
1931         return -EFAULT;
1932     }
1933
1934     BIO_free(bio);
1935     bio = nullptr;
1936     x509 = _x509;
1937     return 0;
1938 }
1939
1940 int Authenticator::LoadCertificate(void)
1941 {
1942     int ret = -ENOENT;
1943
1944     if (sslConfig.privateKey.empty() == false) {
1945         EVP_PKEY *pkey = nullptr;
1946         ret = LoadPrivateKey(sslConfig.privateKey.c_str(), sslConfig.privateKey.size(), pkey);
1947         if (ret < 0) {
1948             return ret;
1949         } else if (pkey == nullptr) {
1950             ErrPrint("Unable to load a private key");
1951             return -EFAULT;
1952         }
1953
1954         DbgPrint("Private key is loaded");
1955         EVP_PKEY_free(sslContext.keypair);
1956         sslContext.keypair = pkey;
1957     }
1958
1959     if (sslConfig.certificate.empty() == false) {
1960         X509 *x509 = nullptr;
1961         ret = LoadCertificate(sslConfig.certificate.c_str(), sslConfig.certificate.size(), x509);
1962         if (ret < 0) {
1963             return ret;
1964         }
1965
1966         DbgPrint("Certificate key is loaded");
1967         X509_free(sslContext.x509);
1968         sslContext.x509 = x509;
1969     }
1970
1971     return ret;
1972 }
1973
1974 int Authenticator::GenerateSecretKey(void)
1975 {
1976     int keyLength = BITS_TO_BYTES(sslConfig.secretKeyBits);
1977     unsigned char *buffer;
1978
1979     buffer = static_cast<unsigned char *>(malloc(keyLength));
1980     if (buffer == nullptr) {
1981         int ret = -errno;
1982         ErrPrintCode(errno, "malloc");
1983         return ret;
1984     }
1985
1986     // For a secret key to generate use SSL
1987     if (!RAND_bytes(buffer, keyLength)) {
1988         SSLErrPrint("RAND Failed");
1989         return -EFAULT;
1990     }
1991
1992     sslContext.secretKey = std::string(reinterpret_cast<char *>(buffer), keyLength);
1993     free(buffer);
1994     return 0;
1995 }
1996
1997 int Authenticator::GenerateKey(void)
1998 {
1999     int bits = sslConfig.bits;
2000
2001     RSA *rsa = nullptr;
2002     int ret = 0;
2003     EVP_PKEY *keypair = nullptr;
2004
2005 #ifndef NDEBUG
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");
2014         return -EFAULT;
2015     }
2016 #endif // OPENSSL_NO_STDIO
2017 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2018 #endif // NDEBUG
2019
2020     do {
2021         keypair = EVP_PKEY_new();
2022         if (keypair == nullptr) {
2023             SSLErrPrint("EVP_PKEY_new");
2024             ret = -EFAULT;
2025             break;
2026         }
2027
2028         rsa = RSA_new();
2029         if (rsa == nullptr) {
2030             ret = -EFAULT;
2031             break;
2032         }
2033
2034         BIGNUM *bn = BN_new();
2035         if (bn == nullptr) {
2036             ret = -EFAULT;
2037             break;
2038         }
2039
2040         BN_set_word(bn, DEFAULT_PRIME);
2041
2042         if (RSA_generate_key_ex(rsa, bits, bn, nullptr) == 0) {
2043             SSLErrPrint("RSA_generate_key_ex");
2044
2045             BN_clear_free(bn);
2046             bn = nullptr;
2047
2048             ret = -EFAULT;
2049             break;
2050         }
2051
2052         BN_clear_free(bn);
2053         bn = nullptr;
2054
2055         if (EVP_PKEY_assign_RSA(keypair, rsa) == 0) {
2056             SSLErrPrint("EVP_PKEY_assign_RSA");
2057             ret = -EFAULT;
2058             break;
2059         }
2060
2061         rsa = nullptr;
2062     } while (0);
2063
2064     if (rsa != nullptr) {
2065         RSA_free(rsa);
2066         rsa = nullptr;
2067     }
2068
2069     if (ret < 0) {
2070         ErrPrint("Clean up keypair");
2071         EVP_PKEY_free(keypair);
2072         keypair = nullptr;
2073     } else {
2074         EVP_PKEY_free(sslContext.keypair);
2075         sslContext.keypair = keypair;
2076     }
2077
2078 #ifndef OPENSSL_NO_ENGINE
2079     ENGINE_cleanup();
2080 #endif
2081
2082     CRYPTO_cleanup_all_ex_data();
2083
2084 #ifndef NDEBUG
2085
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);
2091
2092     char buffer[DEFAULT_BIO_BUFSZ];
2093     int sz = BIO_read(bio_err, buffer, sizeof(buffer));
2094     if (sz > 0) {
2095         ErrPrint("CRYPTO_mem_leaks: %s", buffer);
2096     } else {
2097         SSLErrPrint("BIO_read");
2098     }
2099
2100     BIO_free(bio_err);
2101 #endif // OPENSSL_NO_STDIO
2102     bio_err = nullptr;
2103 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2104 #endif // NDEBUG
2105
2106     return ret;
2107 }
2108
2109 int Authenticator::GenerateCertificate(void)
2110 {
2111     int serial = sslConfig.serial;
2112     int days = sslConfig.days;
2113     int ret = 0;
2114
2115 #ifndef NDEBUG
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");
2124         return -EFAULT;
2125     }
2126 #endif // OPENSSL_NO_STDIO
2127 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2128 #endif // NDEBUG
2129
2130     X509 *x509;
2131     do {
2132         x509 = X509_new();
2133         if (x509 == nullptr) {
2134             SSLErrPrint("X509_new");
2135             ret = -EFAULT;
2136             break;
2137         }
2138
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)));
2144
2145         X509_NAME *name = X509_get_subject_name(x509);
2146         if (name == nullptr) {
2147             SSLErrPrint("X509_get_subject_name");
2148             ret = -EFAULT;
2149             break;
2150         }
2151
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"));
2159         } else {
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"));
2165         }
2166
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()));
2171         }
2172
2173         X509_set_subject_name(x509, name);
2174
2175         AddExtension(x509, NID_subject_key_identifier, const_cast<char *>("hash"));
2176
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");
2181                 ret = -EFAULT;
2182                 break;
2183             }
2184         } else {
2185             void *key = nullptr;
2186             int keyLength = 0;
2187
2188             ret = authenticator->GetKey(beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_PRIVATE_KEY, key, keyLength);
2189             if (ret < 0) {
2190                 ErrPrint("Failed to get the private key from the authenticator");
2191                 break;
2192             }
2193
2194             EVP_PKEY *pkey_ca = nullptr;
2195             ret = LoadPrivateKey(static_cast<char *>(key), keyLength, pkey_ca);
2196             if (ret < 0) {
2197                 ErrPrint("Failed to load the private key");
2198                 break;
2199             } else if (pkey_ca == nullptr) {
2200                 ErrPrint("Private key is invalid");
2201                 ret = -EINVAL;
2202                 break;
2203             }
2204
2205             free(key);
2206             key = nullptr;
2207             keyLength = 0;
2208
2209             ret = authenticator->GetKey(beyond_authenticator_key_id::BEYOND_AUTHENTICATOR_KEY_ID_CERTIFICATE, key, keyLength);
2210             if (ret < 0) {
2211                 ErrPrint("Failed to get the certificate from the authenticator");
2212                 EVP_PKEY_free(pkey_ca);
2213                 pkey_ca = nullptr;
2214                 break;
2215             }
2216
2217             X509 *x509_ca = nullptr;
2218             ret = LoadCertificate(static_cast<char *>(key), keyLength, x509_ca);
2219             free(key);
2220             key = nullptr;
2221             keyLength = 0;
2222             if (ret < 0) {
2223                 ErrPrint("Failed to load the certificate");
2224                 EVP_PKEY_free(pkey_ca);
2225                 pkey_ca = nullptr;
2226                 break;
2227             } else if (x509_ca == nullptr) {
2228                 ErrPrint("Certiicate is invalid");
2229                 EVP_PKEY_free(pkey_ca);
2230                 pkey_ca = nullptr;
2231                 ret = -EINVAL;
2232                 break;
2233             }
2234
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);
2237
2238             X509_free(x509_ca);
2239             x509_ca = nullptr;
2240
2241             ret = X509_sign(x509, pkey_ca, EVP_sha256());
2242             EVP_PKEY_free(pkey_ca);
2243             pkey_ca = nullptr;
2244             if (ret == 0) {
2245                 SSLErrPrint("X509_sign");
2246                 ret = -EFAULT;
2247                 break;
2248             }
2249
2250             ret = 0;
2251         }
2252     } while (0);
2253
2254     if (ret < 0) {
2255         ErrPrint("Clean up x509");
2256         X509_free(x509);
2257         x509 = nullptr;
2258     } else {
2259         X509_free(sslContext.x509);
2260         sslContext.x509 = x509;
2261     }
2262
2263 #ifndef OPENSSL_NO_ENGINE
2264     ENGINE_cleanup();
2265 #endif
2266
2267     CRYPTO_cleanup_all_ex_data();
2268
2269 #ifndef NDEBUG
2270
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);
2276
2277     char buffer[DEFAULT_BIO_BUFSZ];
2278     int sz = BIO_read(bio_err, buffer, sizeof(buffer));
2279     if (sz > 0) {
2280         ErrPrint("CRYPTO_mem_leaks: %s", buffer);
2281     } else {
2282         SSLErrPrint("BIO_read");
2283     }
2284
2285     BIO_free(bio_err);
2286 #endif // OPENSSL_NO_STDIO
2287     bio_err = nullptr;
2288 #endif // OPENSSL_NO_CRYPTO_MDEBUG
2289 #endif // NDEBUG
2290
2291     return ret;
2292 }
2293
2294 int Authenticator::EncodeBase64(char *&output, int &outputLength, const unsigned char *input, int length)
2295 {
2296     BIO *b64f = BIO_new(BIO_f_base64());
2297     if (b64f == nullptr) {
2298         SSLErrPrint("BIO_new");
2299         return -EFAULT;
2300     }
2301
2302     BIO *buff = BIO_new(BIO_s_mem());
2303     if (buff == nullptr) {
2304         SSLErrPrint("BIO_new");
2305         BIO_free_all(b64f);
2306         return -EFAULT;
2307     }
2308
2309     buff = BIO_push(b64f, buff);
2310     assert(buff != nullptr && !!"BIO_push() failed");
2311
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");
2315
2316     ret = BIO_write(buff, input, length);
2317     if (ret == -2) {
2318         ErrPrint("Method is not implemented");
2319         BIO_free_all(buff);
2320         return -ENOTSUP;
2321     } else if (ret <= 0) {
2322         // NOTE:
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");
2327         BIO_free_all(buff);
2328         return -EFAULT;
2329     }
2330
2331     ret = BIO_flush(buff);
2332     if (ret <= 0) {
2333         ErrPrint("Failed to do flush");
2334         BIO_free_all(buff);
2335         return -EFAULT;
2336     }
2337
2338     BUF_MEM *ptr = nullptr;
2339     BIO_get_mem_ptr(buff, &ptr);
2340     if (ptr == nullptr) {
2341         ErrPrint("Failed to get BUF_MEM");
2342         BIO_free_all(buff);
2343         return -EFAULT;
2344     } else if (ptr->length <= 0 || ptr->data == nullptr) {
2345         ErrPrint("Invalid buffer gotten");
2346         BIO_free_all(buff);
2347         return -EINVAL;
2348     }
2349
2350     char *_output = static_cast<char *>(calloc(1, ptr->length + 1));
2351     if (_output == nullptr) {
2352         ret = -errno;
2353         ErrPrintCode(errno, "calloc");
2354         BIO_free_all(buff);
2355         return ret;
2356     }
2357     memcpy(_output, ptr->data, ptr->length);
2358
2359     output = _output;
2360     outputLength = ptr->length;
2361     BIO_free_all(buff);
2362     return 0;
2363 }
2364
2365 int Authenticator::DecodeBase64(unsigned char *&output, int &outputLength, const char *input, int length)
2366 {
2367     BIO *b64f = BIO_new(BIO_f_base64());
2368     if (b64f == nullptr) {
2369         SSLErrPrint("BIO_new");
2370         return -EFAULT;
2371     }
2372
2373     BIO *buff = BIO_new_mem_buf(static_cast<const void *>(input), length);
2374     if (buff == nullptr) {
2375         SSLErrPrint("BIO_new_mem_buf");
2376         BIO_free(b64f);
2377         b64f = nullptr;
2378         return -EFAULT;
2379     }
2380
2381     buff = BIO_push(b64f, buff);
2382     if (buff == nullptr) {
2383         assert(!"BIO_push() failed");
2384         BIO_free(b64f);
2385         b64f = nullptr;
2386         BIO_free(buff);
2387         buff = nullptr;
2388         return -EFAULT;
2389     }
2390
2391     BIO_set_flags(buff, BIO_FLAGS_BASE64_NO_NL);
2392     int ret = BIO_set_close(buff, BIO_CLOSE);
2393     if (ret != 1) {
2394         assert(!"BIO_set_close() returns unexpected value");
2395         ErrPrint("BIO_set_close() returns unexpected value");
2396         // NOTE:
2397         // Go ahead in case of the release mode.
2398     }
2399
2400     // NOTE:
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) {
2408         ret = -errno;
2409         ErrPrintCode(errno, "calloc");
2410         BIO_free_all(buff);
2411         return ret;
2412     }
2413
2414     _outputLength = BIO_read(buff, _output, _outputLength);
2415     BIO_free_all(buff);
2416     if (_outputLength == -2) {
2417         ErrPrint("Method is not implemented");
2418         free(_output);
2419         _output = nullptr;
2420         return -ENOTSUP;
2421     } else if (_outputLength <= 0) {
2422         SSLErrPrint("BIO_read");
2423         free(_output);
2424         _output = nullptr;
2425         return -EFAULT;
2426     }
2427
2428     // NOTE:
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) {
2433         ret = -errno;
2434         ErrPrintCode(errno, "realloc");
2435         free(static_cast<void *>(_output));
2436         _output = nullptr;
2437         return ret;
2438     }
2439
2440     output = static_cast<unsigned char *>(__output);
2441     outputLength = _outputLength;
2442     return 0;
2443 }