Debian Codegraph @

src/CertificateAuthority.cpp

raw
1 #ifdef HAVE_CONFIG_H
2 #include "e2config.h"
3 #endif
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <string.h>
13 #include <errno.h>
14
15 #include <climits>
16 #include <string>
17 #include <iostream>
18
19 #include <openssl/pem.h>
20 #include <openssl/evp.h>
21 #include <openssl/conf.h>
22 #include <openssl/x509.h>
23 #include <openssl/x509v3.h>
24 #include "openssl/bio.h"
25 #include "openssl/ssl.h"
26 #include "openssl/err.h"
27
28 #include "CertificateAuthority.hpp"
29 #include "OptionContainer.hpp"
30 #include "Logger.hpp"
31
32 extern OptionContainer o;
33
34 void log_ssl_errors(const char *mess, const char *site) {
35 //E2LOGGER_debugnet(mess, site);
36 if( o.logger.log_ssl_errors ) {
37 E2LOGGER_error("SSL Error: ", mess, " at: ", site);
38 unsigned long e;
39 char buff[512];
40 while ((e = ERR_get_error())) {
41 ERR_error_string(e, &buff[0]);
42 E2LOGGER_error("SSL Error: ", buff, " at: ", site);
43 }
44 }
45 }
46
47 CertificateAuthority::CertificateAuthority(const char *caCert,
48 const char *caPrivKey,
49 const char *certPrivKey,
50 const char *certPath,
51 time_t &caStart,
52 time_t &caEnd)
53 {
54 FILE *fp;
55 char pem[7200];
56
57
58 DEBUG_thttps("in new CertAuth gen_cert_start is ",caStart, " gen_cert_end is ",caEnd);
59
60 //load the ca cert
61 fp = fopen(caCert, "r");
62 if (fp == NULL) {
63 E2LOGGER_error("Couldn't open ca certificate file ", caCert);
64 exit(1);
65 }
66 _caCert = PEM_read_X509(fp, NULL, NULL, NULL);
67 if (_caCert == NULL) {
68 log_ssl_errors("Couldn't load ca certificate from ", caCert);
69 exit(1);
70 }
71 fclose(fp);
72
73 // Now check date validity of cert
74 {
75 auto rc = X509_cmp_current_time(X509_get_notBefore(_caCert));
76 if (rc == 1) {
77 E2LOGGER_error("Certificate notBefore is in the future");
78 exit(1);
79 }
80 if (rc == 0) {
81 E2LOGGER_error("Error in checking certificate notBefore");
82 exit(1);
83 }
84 rc = X509_cmp_current_time(X509_get_notAfter(_caCert));
85 if (rc == -1) {
86 E2LOGGER_error("CA root Certificate has expiredi - I need a new certificate");
87 exit(1);
88 }
89 if (rc == 0) {
90 E2LOGGER_error("Error in checking certificate notAfter");
91 exit(1);
92 }
93 notBefore = X509_get_notBefore(_caCert);
94 notAfter = X509_get_notAfter(_caCert);
95 int ex_day = 0;
96 int ex_secs = 0;
97 auto now_time = ASN1_TIME_set(nullptr,time(nullptr));
98 ASN1_TIME_diff(&ex_day,&ex_secs,now_time,notAfter);
99 //Add logic here
100 if (ex_day < 90 ) {
101 E2LOGGER_warning("Root CA Certificate expires in ",ex_day," days - install new cert on clients NOW");
102 }
103 #ifdef DEBUG_HIGH
104 else {
105 DEBUG_thttps("Root CA Certificate expires in ",ex_day," days ");
106 }
107 #endif
108
109 if (!checkValidNotBefore(caStart)) {
110 E2LOGGER_warning(
111 "generated_cert_start is too early for CA root cert - adjusted to match CA Root cert notBefore ",
112 caStart);
113 }
114 if (!checkValidNotAfter(caEnd)) {
115 E2LOGGER_warning(
116 "generated_cert_end is too late for CA root cert - adjusted to match CA Root cert notAfter ",
117 caEnd);
118 }
119
120 }
121
122 // open again to get raw PEM for hash
123 fp = fopen(caCert, "r");
124 for (int i = 0;i < 7200;i++) {
125 pem[i] = '\0';
126 }
127 int rc = 0;
128 rc = fread(pem,72,99,fp);
129 if(rc < 1) {
130 E2LOGGER_error("Unable to re-read ca certificate file");
131 exit(1);
132 }
133 fclose(fp);
134
135 //load the ca priv key
136 fp = fopen(caPrivKey, "r");
137 if (fp == NULL) {
138 E2LOGGER_error("Couldn't open ca private key");
139 exit(1);
140 }
141 _caPrivKey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
142 if (_caPrivKey == NULL) {
143 E2LOGGER_error("Couldn't load ca private key");
144 exit(1);
145 }
146
147 fclose(fp);
148
149 //load the priv key to use with generated certificates
150 fp = fopen(certPrivKey, "r");
151 if (fp == NULL) {
152 E2LOGGER_error("Couldn't open certificate private key");
153 exit(1);
154 }
155 _certPrivKey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
156
157 if (_certPrivKey == NULL) {
158 E2LOGGER_error("Couldn't load certificate private key");
159 exit(1);
160 }
161 fclose(fp);
162
163 //TODO should check this is a writable dir
164 _certPath = certPath;
165 _certPathLen = sizeof(certPath);
166 _certLinks = certPath; // temp to check if this works
167 _ca_start = caStart;
168 _ca_end = caEnd;
169
170 // Generate hash to be added to cert server name to produce serial unique rootCA_PEM/start_date/stop_date
171
172 // ASN1_TIME *not_before = X509_get_notBefore(_caCert);
173 // ASN1_TIME *not_after = X509_get_notAfter(_caCert);
174
175 // Make hash
176 String tem = pem;
177 String tem2((long)caStart), tem3((long)caEnd);
178 tem += tem2;
179 tem += tem3;
180 cert_start_stop_hash = tem.md5();
181 DEBUG_config("modifing string to be hashed (rootCA.pem + cartstart + certend is: ", tem);
182 DEBUG_config("modifing hash is: ", cert_start_stop_hash);
183 }
184
185 void CertificateAuthority::ans1_time_to_time_t(ASN1_TIME *a_time, time_t *t_time) { // Sets t_time to 0 on failure
186 int days = 0, secs = 0;
187 ASN1_TIME *aepoch = ASN1_TIME_set(nullptr,0);
188 if(ASN1_TIME_diff(&days,&secs,aepoch,a_time) == 1) {
189 if ( days > 0) {
190 *t_time = (days * 60 * 60 * 24) + secs;
191 return;
192 }
193 };
194 *t_time = (time_t) 0;
195 return;
196 }
197
198 bool CertificateAuthority::checkValidNotAfter(time_t &end) {
199 time_t notAfter_t = 0;
200 ans1_time_to_time_t(X509_get_notAfter(_caCert), &notAfter_t);
201 if ((notAfter_t > 0) && (notAfter_t < end)) {
202 end = notAfter_t;
203 return false;
204 }
205 return true;
206 }
207
208 bool CertificateAuthority::checkValidNotBefore(time_t &start) {
209 time_t notBefore_t = 0;
210 ans1_time_to_time_t(X509_get_notBefore(_caCert), &notBefore_t);
211 if ((notBefore_t > 0) && (notBefore_t > start)) {
212 start = notBefore_t;
213 return false;
214 }
215 return true;
216 }
217
218 bool CertificateAuthority::getSerial(const char *commonname, struct ca_serial *caser)
219 {
220 //generate hash of hostname
221 char cnhash[EVP_MAX_MD_SIZE];
222 unsigned int cnhashlen;
223
224 std::string sname(commonname );
225 sname += cert_start_stop_hash;
226
227 DEBUG_debug("Generating serial no for ", commonname );
228
229 EVP_MD_CTX *mdctx;
230 #if OPENSSL_VERSION_NUMBER < 0x10100000L
231 #error "openssl version 1.1 or greater is required"
232 #endif
233 mdctx = EVP_MD_CTX_new();
234 const EVP_MD *md = EVP_md5();
235 EVP_MD_CTX_init(mdctx);
236
237 bool failed = false;
238 if (!failed && EVP_DigestInit_ex(mdctx, md, NULL) < 1) {
239 failed = true;
240 }
241
242 if (!failed && EVP_DigestUpdate(mdctx, sname.c_str(), strlen(sname.c_str())) < 1) {
243 failed = true;
244 }
245
246 if (!failed && EVP_DigestFinal_ex(mdctx, (unsigned char *)cnhash, &cnhashlen) < 1) {
247 failed = true;
248 }
249
250 EVP_MD_CTX_free(mdctx);
251
252 if (failed) {
253 return false;
254 }
255
256 //convert to asn1 to use as serial
257 BIGNUM *bn = BN_bin2bn((const unsigned char *)cnhash, cnhashlen, NULL);
258
259 if (bn == NULL) {
260 return false;
261 }
262
263 char *dbg = BN_bn2hex(bn);
264 if (dbg != NULL) {
265 DEBUG_debug("Serial no is ", dbg);
266 } else {
267 DEBUG_debug("bn2hex returned null instead of serial number");
268 }
269 caser->charhex = dbg;
270 caser->asn = BN_to_ASN1_INTEGER(bn, NULL);
271 BN_free(bn);
272 return true;
273 }
274
275 //write a certificate to disk being careful to avoid race conditions.
276 //returns true if it already existed or false on error
277 //common name (sh/c)ould be derived from the certificate but that would add to the complexity of the code
278 bool CertificateAuthority::writeCertificate(const char *commonname, X509 *newCert, struct ca_serial *caser)
279 {
280 std::string path(caser->filename);
281 std::string dirpath(caser->filepath);
282
283 // make directory path
284 int rc = mkpath(dirpath.c_str(), 0700); // only want e2g to have access to these dir
285 if (rc != 0) {
286 E2LOGGER_error("error creating certificate sub-directory: ", dirpath);
287 return false;
288 }
289
290 //open file
291 struct flock fl;
292 fl.l_type = F_WRLCK;
293 fl.l_whence = SEEK_SET;
294 fl.l_start = 0;
295 fl.l_len = 0;
296 fl.l_pid = getpid();
297
298 DEBUG_debug("certificate file is ",path);
299 int fd = open(path.c_str(), O_RDWR | O_CREAT, S_IWUSR | S_IRUSR); //only e2g has access
300 if (fd < 0) {
301 E2LOGGER_error("error opening new certificate");
302 exit(1);
303 }
304
305 //lock file with blocking lock and see if its bigger than 0 bytes
306 if (fcntl(fd, F_SETLKW, &fl) < 0) {
307 close(fd);
308 return false;
309 }
310
311 off_t pos = lseek(fd, 0, SEEK_END);
312
313 //check if someone else created the file before we did (avoid the race condition)
314 if (pos < 0) {
315 DEBUG_debug("error seeking to find certificate size ");
316 fl.l_type = F_UNLCK;
317 fcntl(fd, F_SETLK, &fl);
318 close(fd);
319 return false;
320 } else if (pos > 0) {
321 //didnt get first lock so cert should be there now
322 DEBUG_debug("didnt get first lock pos was ", pos);
323 fl.l_type = F_UNLCK;
324 fcntl(fd, F_SETLK, &fl);
325 close(fd);
326 return true;
327 }
328
329 //looks like we got the first lock so write the certificate
330 //write the cert to a file
331 DEBUG_debug("got first lock ");
332 FILE *fp = fdopen(fd, "w");
333 if (fp == NULL) {
334 return false;
335 }
336
337 if (PEM_write_X509(fp, newCert) < 1) {
338 fclose(fp);
339 return false;
340 }
341
342 if (fflush(fp) == EOF) {
343 fclose(fp);
344 return false;
345 }
346
347 if (fsync(fd) < 0) {
348 fclose(fp);
349 return false;
350 }
351
352 //unlock the file
353 fl.l_type = F_UNLCK;
354 fcntl(fd, F_SETLK, &fl);
355 fclose(fp);
356 close(fd);
357 return true;
358 }
359
360 //generate a certificate for a given hostname
361 X509 *CertificateAuthority::generateCertificate(const char *commonname, struct ca_serial *cser, bool is_ip)
362 {
363 //create a blank cert
364 ERR_clear_error();
365 X509 *newCert = X509_new();
366 if (newCert == NULL) {
367 log_ssl_errors("new blank cert failed for %s", commonname);
368 return NULL;
369 }
370
371 ERR_clear_error();
372 if (X509_set_version(newCert, 2) < 1) {
373 log_ssl_errors("set_version on cert failed for %s", commonname);
374 X509_free(newCert);
375 return NULL;
376 }
377
378 //set a serial on the cert
379 ERR_clear_error();
380 if (X509_set_serialNumber(newCert, (cser->asn)) < 1) {
381 log_ssl_errors("set_serialNumber on cert failed for %s", commonname);
382 X509_free(newCert);
383 return NULL;
384 }
385
386 //set valid from and expires dates
387 // now from fixed date - should ensure regenerated certs are same and that servers in loadbalanced arrary give same cert
388 if (!ASN1_TIME_set(X509_get_notBefore(newCert), _ca_start)) {
389 DEBUG_debug("get_notBefore on cert failed for ", commonname );
390 X509_free(newCert);
391 return NULL;
392 }
393
394 if (!ASN1_TIME_set(X509_get_notAfter(newCert), _ca_end)) {
395 DEBUG_debug("get_notAfter on cert failed for ", commonname);
396 X509_free(newCert);
397 return NULL;
398 }
399
400 //set the public key of the new cert
401 //the private key data type also contains the pub key which is used below.
402 ERR_clear_error();
403 if (X509_set_pubkey(newCert, _certPrivKey) < 1) {
404 log_ssl_errors("set_pubkey on cert failed for %s", commonname);
405 X509_free(newCert);
406 return NULL;
407 }
408
409 //create a name section
410 ERR_clear_error();
411 X509_NAME *name = X509_get_subject_name(newCert);
412 if (name == NULL) {
413 log_ssl_errors("get_subject_name on cert failed for %s", commonname);
414 X509_free(newCert);
415 return NULL;
416 }
417
418 //add the cn of the site we want a cert for the destination
419 ERR_clear_error();
420 int rc = X509_NAME_add_entry_by_txt(name, "CN",
421 MBSTRING_ASC, (unsigned char *)commonname, -1, -1, 0);
422
423 if (rc < 1) {
424 log_ssl_errors("NAME_add_entry_by_txt on cert failed for %s", commonname);
425 // X509_NAME_free(name);
426 X509_free(newCert);
427 return NULL;
428 }
429
430 //set the issuer name of the cert to the cn of the ca
431 ERR_clear_error();
432 X509_NAME *subjectName = X509_get_subject_name(_caCert);
433 if (subjectName == NULL) {
434 log_ssl_errors("get_subject_name on ca_cert failed for %s", commonname);
435 X509_free(newCert);
436 return NULL;
437 }
438
439 ERR_clear_error();
440 if (X509_set_issuer_name(newCert, subjectName) < 1) {
441 log_ssl_errors("set_issuer_name on cert failed for %s", commonname);
442 // X509_NAME_free(subjectName);
443 X509_free(newCert);
444 return NULL;
445 }
446
447 // set authority_key_id to subject_key_id of the CA
448 ERR_clear_error();
449 const ASN1_OCTET_STRING *auth_key_id = X509_get0_subject_key_id(_caCert);
450 if (auth_key_id == NULL) {
451 log_ssl_errors("get_subject_key_id on ca_cert failed for %s", commonname);
452 X509_free(newCert);
453 return NULL;
454 }
455
456 ERR_clear_error();
457 AUTHORITY_KEYID *akid = AUTHORITY_KEYID_new();
458 akid->keyid = ASN1_OCTET_STRING_new();
459 ASN1_OCTET_STRING_set(akid->keyid,auth_key_id->data,auth_key_id->length);
460 X509_EXTENSION *ext = NULL;
461 ext = X509V3_EXT_i2d(NID_authority_key_identifier,0,akid);
462 if( !X509_add_ext(newCert,ext, -1 )) {
463 log_ssl_errors("Error adding authority_key_id to the request", commonname);
464 AUTHORITY_KEYID_free(akid);
465 X509_EXTENSION_free(ext);
466 X509_free(newCert);
467 return NULL;
468 }
469 X509_EXTENSION_free(ext);
470 AUTHORITY_KEYID_free(akid);
471
472 String temp1;
473
474 // E2LOGGER_error("common name is ",commonname);
475 String temp2 = commonname;
476 if(temp2.contains(":")) {
477 bool not_first_one = false;
478 temp2 += ":";
479 // E2LOGGER_error("temp2 is ",temp2);
480 while (!temp2.empty()) {
481 String temp3 = temp2.before(":");
482 temp2 = temp2.after(":");
483 if (not_first_one) {
484 temp1 += ", ";
485 }
486 not_first_one = true;
487 if (temp3.isIp())
488 temp1 += "IP:";
489 else
490 temp1 += "DNS:";
491 temp1 += temp3;
492 }
493 // E2LOGGER_error("alt_name string is ",tem:p1);
494 char *value = (char*) temp1.toCharArray();
495 if( !addExtension(newCert, NID_subject_alt_name, value))
496 log_ssl_errors("Error adding subjectAltName to the request", commonname);
497
498 } else {
499 if (is_ip)
500 temp1 = "IP:";
501 else
502 temp1 = "DNS:";
503 temp1 += temp2;
504 // E2LOGGER_error("alt_name string is ",temp1);
505 char *value = (char*) temp1.toCharArray();
506 if( !addExtension(newCert, NID_subject_alt_name, value))
507 log_ssl_errors("Error adding subjectAltName to the request", commonname);
508 }
509
510
511 //sign it using the ca
512 ERR_clear_error();
513 if (!X509_sign(newCert, _caPrivKey, EVP_sha256())) {
514 log_ssl_errors("X509_sign on cert failed for %s", commonname);
515 X509_free(newCert);
516 return NULL;
517 }
518
519 DEBUG_debug("certificate create ", name );
520
521 return newCert;
522 }
523
524 //sets cert to the certificate for commonname
525 //returns true if the cert was loaded from cache / false if it was generated
526 bool CertificateAuthority::getServerCertificate(const char *commonname, X509 **cert, struct ca_serial *caser, bool is_ip)
527 {
528
529 getSerial(commonname, caser);
530 std::string filename(caser->charhex);
531
532 // Generate directory path
533 std::string subpath(filename.substr(0, 2) + '/' + filename.substr(2, 2)
534 + '/' + filename.substr(4, 2) + '/');
535 std::string filepath(_certLinks + subpath);
536 std::string path(_certLinks + subpath + filename.substr(6));
537 caser->filepath = strdup(filepath.c_str());
538 caser->filename = strdup(path.c_str());
539
540 DEBUG_debug("looking for cert ", path);
541 //check to see if there is a symlink to the file
542 // std::string path(_certLinks + filename);
543 FILE *link = fopen(path.c_str(), "r");
544
545 if (link != NULL) {
546 DEBUG_debug("Certificate found");
547
548 //if there was then the certificate has already been created
549 *cert = PEM_read_X509(link, NULL, NULL, NULL);
550
551 fclose(link);
552
553 //dont need to check the return as this returns null if it couldnt load a cert
554 return true;
555 } else {
556 DEBUG_debug("Certificate not found. Creating one");
557
558 //generate a certificate
559 *cert = generateCertificate(commonname, caser, is_ip);
560 return false;
561 }
562 }
563
564 EVP_PKEY *CertificateAuthority::getServerPkey()
565 {
566 EVP_PKEY_up_ref(_certPrivKey);
567 return _certPrivKey;
568 }
569
570 int CertificateAuthority::do_mkdir(const char *path, mode_t mode)
571 {
572 struct stat st;
573 int status = 0;
574
575 if (stat(path, &st) != 0) {
576 /* Directory does not exist. EEXIST for race condition */
577 if (mkdir(path, mode) != 0 && errno != EEXIST)
578 status = -1;
579 } else if (!S_ISDIR(st.st_mode)) {
580 errno = ENOTDIR;
581 status = -1;
582 }
583
584 return (status);
585 }
586
587 // mkpath - ensure all sub-directories in path exist
588 int CertificateAuthority::mkpath(const char *path, mode_t mode)
589 {
590 char *pp;
591 char *sp;
592 int status;
593 char *copypath = strdup(path);
594
595 status = 0;
596 pp = copypath + _certPathLen; //start checking within generated cert directory
597 while (status == 0 && (sp = strchr(pp, '/')) != 0) {
598 if (sp != pp) {
599 *sp = '\0';
600 status = do_mkdir(copypath, mode);
601 *sp = '/';
602 }
603 pp = sp + 1;
604 }
605 if (status == 0)
606 status = do_mkdir(path, mode);
607 free(copypath);
608 return (status);
609 }
610
611 bool CertificateAuthority::free_ca_serial(struct ca_serial *cs)
612 {
613 if (cs->asn != NULL)
614 ASN1_INTEGER_free(cs->asn);
615 if (cs->charhex != NULL)
616 OPENSSL_free(cs->charhex);
617 // free(cs->charhex);
618 if (cs->filepath != NULL)
619 free(cs->filepath);
620 if (cs->filename != NULL)
621 free(cs->filename);
622 return true;
623 }
624
625 CertificateAuthority::~CertificateAuthority()
626 {
627 if (_caCert) X509_free(_caCert);
628 if (_caPrivKey) EVP_PKEY_free(_caPrivKey);
629 if (_certPrivKey) EVP_PKEY_free(_certPrivKey);
630 }
631
632 bool CertificateAuthority::addExtension(X509 *cert, int nid, char *value)
633 {
634 X509_EXTENSION *ex = NULL;
635
636 ex = X509V3_EXT_conf_nid(NULL,NULL , nid, value);
637
638 int result = X509_add_ext(cert, ex, -1);
639
640 X509_EXTENSION_free(ex);
641
642 return (result > 0) ? true : false;
643 }
644
645 //String CertificateAuthority::ASN1TIME2String(ASN1_TIME *atime)
646 //{
647
648 //};