1505af0177997db9acad95c0269139b684aa5e60
[public/netxms.git] / src / server / core / cert.cpp
1 /*
2 ** NetXMS - Network Management System
3 ** Copyright (C) 2007-2017 Victor Kirhenshtein
4 **
5 ** This program is free software; you can redistribute it and/or modify
6 ** it under the terms of the GNU General Public License as published by
7 ** the Free Software Foundation; either version 2 of the License, or
8 ** (at your option) any later version.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 ** GNU General Public License for more details.
14 **
15 ** You should have received a copy of the GNU General Public License
16 ** along with this program; if not, write to the Free Software
17 ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 **
19 ** File: cert.cpp
20 **
21 **/
22
23 #include "nxcore.h"
24 #include <nxcrypto.h>
25
26 #ifdef _WITH_ENCRYPTION
27
28 // WARNING! this hack works only for d2i_X509(); be careful when adding new code
29 #ifdef OPENSSL_CONST
30 # undef OPENSSL_CONST
31 #endif
32 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
33 # define OPENSSL_CONST const
34 #else
35 # define OPENSSL_CONST
36 #endif
37
38 #if OPENSSL_VERSION_NUMBER < 0x10000000L
39 inline int EVP_PKEY_id(EVP_PKEY *key)
40 {
41 return key->type;
42 }
43 #endif
44
45 #if OPENSSL_VERSION_NUMBER < 0x10100000L
46 inline ASN1_TIME *X509_getm_notBefore(const X509 *x)
47 {
48 return X509_get_notBefore(x);
49 }
50
51 inline ASN1_TIME *X509_getm_notAfter(const X509 *x)
52 {
53 return X509_get_notAfter(x);
54 }
55 #endif
56
57 /**
58 * Server certificate file information
59 */
60 TCHAR *g_serverCACertificatesPath = NULL;
61 TCHAR g_serverCertificatePath[MAX_PATH] = _T("");
62 TCHAR g_serverCertificateKeyPath[MAX_PATH] = _T("");
63 char g_serverCertificatePassword[MAX_PASSWORD] = "";
64
65 /**
66 * Server certificate
67 */
68 static ObjectRefArray<X509> s_serverCACertificates(8, 8);
69 static X509 *s_serverCertificate = NULL;
70 static EVP_PKEY *s_serverCertificateKey = NULL;
71
72 /**
73 * Trusted CA certificate store
74 */
75 static X509_STORE *s_trustedCertificateStore = NULL;
76 static Mutex s_certificateStoreLock;
77
78 /**
79 * Issue certificate signed with server's certificate
80 */
81 X509 *IssueCertificate(X509_REQ *request, const char *ou, const char *cn, int days)
82 {
83 nxlog_debug(4, _T("IssueCertificate: new certificate request (CN override: %hs, OU override: %hs)"),
84 (cn != NULL) ? cn : "<not set>", (ou != NULL) ? ou : "<not set>");
85
86 X509_NAME *requestSubject = X509_REQ_get_subject_name(request);
87 if (requestSubject == NULL)
88 {
89 nxlog_debug(4, _T("IssueCertificate: cannot get subject from certificate request"));
90 return NULL;
91 }
92
93 X509 *cert = X509_new();
94 if (cert == NULL)
95 {
96 nxlog_debug(4, _T("IssueCertificate: call to X509_new() failed"));
97 return NULL;
98 }
99
100 if (X509_set_version(cert, 2) != 1)
101 {
102 nxlog_debug(4, _T("IssueCertificate: call to X509_set_version() failed"));
103 X509_free(cert);
104 return NULL;
105 }
106
107 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
108 ASN1_INTEGER *serial = ASN1_INTEGER_new();
109 #else
110 ASN1_INTEGER *serial = M_ASN1_INTEGER_new();
111 #endif
112 ASN1_INTEGER_set(serial, 0);
113 int rc = X509_set_serialNumber(cert, serial);
114 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
115 ASN1_INTEGER_free(serial);
116 #else
117 M_ASN1_INTEGER_free(serial);
118 #endif
119 if (rc != 1)
120 {
121 nxlog_debug(4, _T("IssueCertificate: cannot set certificate serial number"));
122 X509_free(cert);
123 return NULL;
124 }
125
126 X509_NAME *subject;
127 if ((cn != NULL) || (ou != NULL))
128 {
129 subject = X509_NAME_dup(requestSubject);
130 if (subject != NULL)
131 {
132 if (ou != NULL)
133 {
134 int idx = X509_NAME_get_index_by_NID(subject, NID_organizationalUnitName, -1);
135 if (idx != -1)
136 X509_NAME_delete_entry(subject, idx);
137 if (!X509_NAME_add_entry_by_txt(subject, "OU", MBSTRING_UTF8, (const BYTE *)ou, -1, -1, 0))
138 nxlog_debug(4, _T("IssueCertificate: X509_NAME_add_entry_by_txt failed for OU=%hs"), ou);
139 }
140 if (cn != NULL)
141 {
142 int idx = X509_NAME_get_index_by_NID(subject, NID_commonName, -1);
143 if (idx != -1)
144 X509_NAME_delete_entry(subject, idx);
145 if (!X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_UTF8, (const BYTE *)cn, -1, -1, 0))
146 nxlog_debug(4, _T("IssueCertificate: X509_NAME_add_entry_by_txt failed for CN=%hs"), cn);
147 }
148 }
149 else
150 {
151 nxlog_debug(4, _T("IssueCertificate: call to X509_NAME_dup() failed"));
152 }
153 }
154 else
155 {
156 subject = requestSubject;
157 }
158
159 if (subject == NULL)
160 {
161 X509_free(cert);
162 return NULL;
163 }
164
165 rc = X509_set_subject_name(cert, subject);
166 if (subject != requestSubject)
167 X509_NAME_free(subject);
168 if (rc != 1)
169 {
170 nxlog_debug(4, _T("IssueCertificate: call to X509_set_subject_name() failed"));
171 X509_free(cert);
172 return NULL;
173 }
174
175 X509_NAME *issuerName = X509_get_subject_name(s_serverCertificate);
176 if (issuerName == NULL)
177 {
178 nxlog_debug(4, _T("IssueCertificate: cannot get CA subject name"));
179 X509_free(cert);
180 return NULL;
181 }
182
183 if (X509_set_issuer_name(cert, issuerName) != 1)
184 {
185 nxlog_debug(4, _T("IssueCertificate: call to X509_set_issuer_name() failed"));
186 X509_free(cert);
187 return NULL;
188 }
189
190 EVP_PKEY *pubkey = X509_REQ_get_pubkey(request);
191 if (pubkey == NULL)
192 {
193 nxlog_debug(4, _T("IssueCertificate: call to X509_REQ_get_pubkey() failed"));
194 X509_free(cert);
195 return NULL;
196 }
197
198 if (X509_REQ_verify(request, pubkey) != 1)
199 {
200 nxlog_debug(4, _T("IssueCertificate: certificate request verification failed"));
201 EVP_PKEY_free(pubkey);
202 X509_free(cert);
203 return NULL;
204 }
205
206 rc = X509_set_pubkey(cert, pubkey);
207 EVP_PKEY_free(pubkey);
208 if (rc != 1)
209 {
210 nxlog_debug(4, _T("IssueCertificate: call to X509_set_pubkey() failed"));
211 X509_free(cert);
212 return NULL;
213 }
214
215 if (X509_gmtime_adj(X509_getm_notBefore(cert), 0) == NULL)
216 {
217 nxlog_debug(4, _T("IssueCertificate: cannot set start time"));
218 X509_free(cert);
219 return NULL;
220 }
221
222 if (X509_gmtime_adj(X509_getm_notAfter(cert), days * 86400) == NULL)
223 {
224 nxlog_debug(4, _T("IssueCertificate: cannot set end time"));
225 X509_free(cert);
226 return NULL;
227 }
228
229 if (X509_sign(cert, s_serverCertificateKey, EVP_sha256()) == 0)
230 {
231 nxlog_debug(4, _T("IssueCertificate: call to X509_sign() failed"));
232 X509_free(cert);
233 return NULL;
234 }
235
236 char subjectName[1024];
237 X509_NAME_oneline(X509_get_subject_name(cert), subjectName, 1024);
238 nxlog_debug(4, _T("IssueCertificate: new certificate with subject \"%hs\" issued successfully"), subjectName);
239 return cert;
240 }
241
242 /**
243 * Get CN from certificate
244 */
245 bool GetCertificateSubjectField(X509 *cert, int nid, TCHAR *buffer, size_t size)
246 {
247 X509_NAME *subject = X509_get_subject_name(cert);
248 if (subject == NULL)
249 return false;
250
251 int idx = X509_NAME_get_index_by_NID(subject, nid, -1);
252 if (idx == -1)
253 return false;
254
255 X509_NAME_ENTRY *entry = X509_NAME_get_entry(subject, idx);
256 if (entry == NULL)
257 return false;
258
259 ASN1_STRING *data = X509_NAME_ENTRY_get_data(entry);
260 if (data == NULL)
261 return false;
262
263 unsigned char *text;
264 ASN1_STRING_to_UTF8(&text, data);
265 #ifdef UNICODE
266 MultiByteToWideChar(CP_UTF8, 0, (char *)text, -1, buffer, (int)size);
267 #else
268 utf8_to_mb((char *)text, -1, buffer, (int)size);
269 #endif
270 buffer[size - 1] = 0;
271 OPENSSL_free(text);
272 return true;
273 }
274
275 /**
276 * Get CN from certificate
277 */
278 bool GetCertificateCN(X509 *cert, TCHAR *buffer, size_t size)
279 {
280 return GetCertificateSubjectField(cert, NID_commonName, buffer, size);
281 }
282
283 /**
284 * Get OU from certificate
285 */
286 bool GetCertificateOU(X509 *cert, TCHAR *buffer, size_t size)
287 {
288 return GetCertificateSubjectField(cert, NID_organizationalUnitName, buffer, size);
289 }
290
291 /**
292 * Get country name from server certificate
293 */
294 bool GetServerCertificateCountry(TCHAR *buffer, size_t size)
295 {
296 if (s_serverCertificate == NULL)
297 return false;
298 return GetCertificateSubjectField(s_serverCertificate, NID_countryName, buffer, size);
299 }
300
301 /**
302 * Get organization name from server certificate
303 */
304 bool GetServerCertificateOrganization(TCHAR *buffer, size_t size)
305 {
306 if (s_serverCertificate == NULL)
307 return false;
308 return GetCertificateSubjectField(s_serverCertificate, NID_organizationName, buffer, size);
309 }
310
311 /**
312 * Create X509 certificate structure from login message
313 */
314 X509 *CertificateFromLoginMessage(NXCPMessage *msg)
315 {
316 X509 *cert = NULL;
317 size_t len;
318 const BYTE *data = msg->getBinaryFieldPtr(VID_CERTIFICATE, &len);
319 if ((data != NULL) && (len > 0))
320 {
321 OPENSSL_CONST BYTE *p = (OPENSSL_CONST BYTE *)data;
322 cert = d2i_X509(NULL, &p, (long)len);
323 }
324 return cert;
325 }
326
327 /**
328 * Check public key
329 */
330 static BOOL CheckPublicKey(EVP_PKEY *key, const TCHAR *mappingData)
331 {
332 int pkeyLen;
333 unsigned char *ucBuf, *uctempBuf;
334 TCHAR *pkeyText;
335 BOOL valid;
336
337 pkeyLen = i2d_PublicKey(key, NULL);
338 ucBuf = (unsigned char *)malloc(pkeyLen +1);
339 uctempBuf = ucBuf;
340 i2d_PublicKey(key, &uctempBuf);
341
342 pkeyText = (TCHAR *)malloc((pkeyLen * 2 + 1) * sizeof(TCHAR));
343 BinToStr(ucBuf, pkeyLen, pkeyText);
344
345 valid = !_tcscmp(pkeyText, mappingData);
346
347 free(ucBuf);
348 free(pkeyText);
349
350 return valid;
351 }
352
353 /**
354 * Check ciertificate's CN
355 */
356 static BOOL CheckCommonName(X509 *cert, const TCHAR *cn)
357 {
358 TCHAR certCn[256];
359 if (!GetCertificateCN(cert, certCn, 256))
360 return FALSE;
361
362 nxlog_debug(3, _T("Certificate CN=\"%s\", user CN=\"%s\""), certCn, cn);
363 return !_tcsicmp(certCn, cn);
364 }
365
366 /**
367 * Validate user's certificate
368 */
369 bool ValidateUserCertificate(X509 *cert, const TCHAR *login, const BYTE *challenge, const BYTE *signature,
370 size_t sigLen, int mappingMethod, const TCHAR *mappingData)
371 {
372 BOOL bValid = FALSE;
373
374 char subjectName[1024];
375 X509_NAME_oneline(X509_get_subject_name(cert), subjectName, 1024);
376 #ifdef UNICODE
377 WCHAR certSubject[1024];
378 MultiByteToWideChar(CP_UTF8, 0, subjectName, -1, certSubject, 1024);
379 #else
380 const char *certSubject = subjectName;
381 #endif
382
383 DbgPrintf(3, _T("Validating certificate \"%s\" for user %s"), certSubject, login);
384 s_certificateStoreLock.lock();
385
386 if (s_trustedCertificateStore == NULL)
387 {
388 DbgPrintf(3, _T("Cannot validate user certificate because certificate store is not initialized"));
389 s_certificateStoreLock.unlock();
390 return FALSE;
391 }
392
393 // Validate signature
394 EVP_PKEY *pKey = X509_get_pubkey(cert);
395 if (pKey != NULL)
396 {
397 BYTE hash[SHA1_DIGEST_SIZE];
398 CalculateSHA1Hash(challenge, CLIENT_CHALLENGE_SIZE, hash);
399 switch(EVP_PKEY_id(pKey))
400 {
401 case EVP_PKEY_RSA:
402 bValid = RSA_verify(NID_sha1, hash, SHA1_DIGEST_SIZE, signature, static_cast<unsigned int>(sigLen), EVP_PKEY_get1_RSA(pKey));
403 break;
404 default:
405 DbgPrintf(3, _T("Unknown key type %d in certificate \"%s\" for user %s"), EVP_PKEY_id(pKey), certSubject, login);
406 break;
407 }
408 }
409
410 // Validate certificate
411 if (bValid)
412 {
413 X509_STORE_CTX *pStore = X509_STORE_CTX_new();
414 if (pStore != NULL)
415 {
416 X509_STORE_CTX_init(pStore, s_trustedCertificateStore, cert, NULL);
417 bValid = X509_verify_cert(pStore);
418 X509_STORE_CTX_free(pStore);
419 DbgPrintf(3, _T("Certificate \"%s\" for user %s - validation %s"),
420 certSubject, login, bValid ? _T("successful") : _T("failed"));
421 }
422 else
423 {
424 TCHAR szBuffer[256];
425 DbgPrintf(3, _T("X509_STORE_CTX_new() failed: %s"), _ERR_error_tstring(ERR_get_error(), szBuffer));
426 bValid = FALSE;
427 }
428 }
429
430 // Check user mapping
431 if (bValid)
432 {
433 switch(mappingMethod)
434 {
435 case USER_MAP_CERT_BY_SUBJECT:
436 bValid = !_tcsicmp(certSubject, CHECK_NULL_EX(mappingData));
437 break;
438 case USER_MAP_CERT_BY_PUBKEY:
439 bValid = CheckPublicKey(pKey, CHECK_NULL_EX(mappingData));
440 break;
441 case USER_MAP_CERT_BY_CN:
442 bValid = CheckCommonName(cert, ((mappingData != NULL) && (*mappingData != 0)) ? mappingData : login);
443 break;
444 default:
445 DbgPrintf(3, _T("Invalid certificate mapping method %d for user %s"), mappingMethod, login);
446 bValid = FALSE;
447 break;
448 }
449 }
450
451 s_certificateStoreLock.unlock();
452 return bValid;
453 }
454
455 /**
456 * Validate agent certificate
457 */
458 bool ValidateAgentCertificate(X509 *cert)
459 {
460 X509_STORE *store = X509_STORE_new();
461 if (store == NULL)
462 {
463 nxlog_debug(3, _T("ValidateAgentCertificate: cannot create certificate store"));
464 }
465
466 for(int i = 0; i < s_serverCACertificates.size(); i++)
467 X509_STORE_add_cert(store, s_serverCACertificates.get(i));
468 X509_STORE_add_cert(store, s_serverCertificate);
469 bool valid = false;
470
471 X509_STORE_CTX *ctx = X509_STORE_CTX_new();
472 if (ctx != NULL)
473 {
474 X509_STORE_CTX_init(ctx, store, cert, NULL);
475 valid = (X509_verify_cert(ctx) == 1);
476 X509_STORE_CTX_free(ctx);
477 }
478 else
479 {
480 TCHAR buffer[256];
481 nxlog_debug(3, _T("ValidateAgentCertificate: X509_STORE_CTX_new() failed: %s"), _ERR_error_tstring(ERR_get_error(), buffer));
482 }
483
484 X509_STORE_free(store);
485 return valid;
486 }
487
488 /**
489 * Reload certificates from database
490 */
491 void ReloadCertificates()
492 {
493 s_certificateStoreLock.lock();
494
495 if (s_trustedCertificateStore != NULL)
496 X509_STORE_free(s_trustedCertificateStore);
497
498 s_trustedCertificateStore = X509_STORE_new();
499 if (s_trustedCertificateStore != NULL)
500 {
501 // Add server's certificate as trusted
502 if (s_serverCertificate != NULL)
503 X509_STORE_add_cert(s_trustedCertificateStore, s_serverCertificate);
504
505 // Add server's CA certificate as trusted
506 for(int i = 0; i < s_serverCACertificates.size(); i++)
507 X509_STORE_add_cert(s_trustedCertificateStore, s_serverCACertificates.get(i));
508
509 TCHAR szBuffer[256];
510 _sntprintf(szBuffer, 256, _T("SELECT cert_data,subject FROM certificates WHERE cert_type=%d"), CERT_TYPE_TRUSTED_CA);
511 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
512 DB_RESULT hResult = DBSelect(hdb, szBuffer);
513 if (hResult != NULL)
514 {
515 int loaded = 0;
516 int count = DBGetNumRows(hResult);
517 for(int i = 0; i < count; i++)
518 {
519 TCHAR *certData = DBGetField(hResult, i, 0, NULL, 0);
520 if (certData != NULL)
521 {
522 size_t len = _tcslen(certData);
523 BYTE *binCert = (BYTE *)malloc(len);
524 StrToBin(certData, binCert, len);
525 free(certData);
526 OPENSSL_CONST BYTE *p = binCert;
527 X509 *cert = d2i_X509(NULL, &p, (long)len);
528 free(binCert);
529 if (cert != NULL)
530 {
531 if (X509_STORE_add_cert(s_trustedCertificateStore, cert))
532 {
533 loaded++;
534 }
535 else
536 {
537 TCHAR subject[256];
538 nxlog_write(MSG_CANNOT_ADD_CERT, EVENTLOG_ERROR_TYPE,
539 "ss", DBGetField(hResult, i, 1, subject, 256),
540 _ERR_error_tstring(ERR_get_error(), szBuffer));
541 }
542 X509_free(cert); // X509_STORE_add_cert increments reference count
543 }
544 else
545 {
546 TCHAR subject[256];
547 nxlog_write(MSG_CANNOT_LOAD_CERT, EVENTLOG_ERROR_TYPE,
548 "ss", DBGetField(hResult, i, 1, subject, 256),
549 _ERR_error_tstring(ERR_get_error(), szBuffer));
550 }
551 }
552 }
553 DBFreeResult(hResult);
554
555 if (loaded > 0)
556 nxlog_write(MSG_CA_CERTIFICATES_LOADED, EVENTLOG_INFORMATION_TYPE, "d", loaded);
557 }
558 DBConnectionPoolReleaseConnection(hdb);
559 }
560 else
561 {
562 TCHAR buffer[256];
563 nxlog_write(MSG_CANNOT_INIT_CERT_STORE, EVENTLOG_ERROR_TYPE, "s", _ERR_error_tstring(ERR_get_error(), buffer));
564 }
565
566 s_certificateStoreLock.unlock();
567 }
568
569 /**
570 * Certificate stuff initialization
571 */
572 void InitCertificates()
573 {
574 ReloadCertificates();
575 }
576
577 /**
578 * Load server certificate
579 */
580 bool LoadServerCertificate(RSA **serverKey)
581 {
582 if (g_serverCertificatePath[0] == 0)
583 {
584 nxlog_write(MSG_SERVER_CERT_NOT_SET, NXLOG_INFO, NULL);
585 return false;
586 }
587
588 // Load server CA certificates
589 TCHAR *curr = g_serverCACertificatesPath;
590 TCHAR *next = _tcschr(curr, _T('\n'));
591 while(next != NULL)
592 {
593 *next = 0;
594
595 FILE *f = _tfopen(curr, _T("r"));
596 if (f == NULL)
597 {
598 nxlog_write(MSG_CANNOT_LOAD_SERVER_CERT, NXLOG_ERROR, "ss", curr, _tcserror(errno));
599 return false;
600 }
601 X509 *cert = PEM_read_X509(f, NULL, NULL, NULL);
602 fclose(f);
603 if (cert == NULL)
604 {
605 TCHAR buffer[1024];
606 nxlog_write(MSG_CANNOT_LOAD_SERVER_CERT, NXLOG_ERROR, "ss", curr, _ERR_error_tstring(ERR_get_error(), buffer));
607 return false;
608 }
609 s_serverCACertificates.add(cert);
610
611 curr = next + 1;
612 next = _tcschr(curr, _T('\n'));
613 }
614
615 // Load server certificate and private key
616 FILE *f = _tfopen(g_serverCertificatePath, _T("r"));
617 if (f == NULL)
618 {
619 nxlog_write(MSG_CANNOT_LOAD_SERVER_CERT, NXLOG_ERROR, "ss", g_serverCertificatePath, _tcserror(errno));
620 return false;
621 }
622
623 DecryptPasswordA("system", g_serverCertificatePassword, g_serverCertificatePassword, MAX_PASSWORD);
624 s_serverCertificate = PEM_read_X509(f, NULL, NULL, g_serverCertificatePassword);
625 if (g_serverCertificateKeyPath[0] != 0)
626 {
627 // Server key is in separate file
628 fclose(f);
629 f = _tfopen(g_serverCertificateKeyPath, _T("r"));
630 if (f == NULL)
631 {
632 nxlog_write(MSG_CANNOT_LOAD_SERVER_CERT, NXLOG_ERROR, "ss", g_serverCertificateKeyPath, _tcserror(errno));
633 return false;
634 }
635 }
636 s_serverCertificateKey = PEM_read_PrivateKey(f, NULL, NULL, g_serverCertificatePassword);
637 fclose(f);
638
639 if ((s_serverCertificate == NULL) || (s_serverCertificateKey == NULL))
640 {
641 TCHAR buffer[1024];
642 nxlog_write(MSG_CANNOT_LOAD_SERVER_CERT, NXLOG_ERROR, "ss", g_serverCertificatePath, _ERR_error_tstring(ERR_get_error(), buffer));
643 return false;
644 }
645
646 RSA *privKey = EVP_PKEY_get1_RSA(s_serverCertificateKey);
647 RSA *pubKey = EVP_PKEY_get1_RSA(X509_get_pubkey(s_serverCertificate));
648 if ((privKey != NULL) && (pubKey != NULL))
649 {
650 // Combine into one key
651 int len = i2d_RSAPublicKey(pubKey, NULL);
652 len += i2d_RSAPrivateKey(privKey, NULL);
653 BYTE *buffer = (BYTE *)malloc(len);
654
655 BYTE *pos = buffer;
656 i2d_RSAPublicKey(pubKey, &pos);
657 i2d_RSAPrivateKey(privKey, &pos);
658
659 *serverKey = RSAKeyFromData(buffer, len, true);
660 free(buffer);
661 }
662
663 return true;
664 }
665
666 #if HAVE_X509_STORE_SET_VERIFY_CB
667
668 /**
669 * Certificate verification callback
670 */
671 static int CertVerifyCallback(int success, X509_STORE_CTX *ctx)
672 {
673 if (!success)
674 {
675 X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
676 int error = X509_STORE_CTX_get_error(ctx);
677 int depth = X509_STORE_CTX_get_error_depth(ctx);
678 char subjectName[1024];
679 X509_NAME_oneline(X509_get_subject_name(cert), subjectName, 1024);
680 nxlog_debug(4, _T("Certificate \"%hs\" verification error %d (%hs) at depth %d"),
681 subjectName, error, X509_verify_cert_error_string(error), depth);
682 }
683 return success;
684 }
685
686 #endif /* HAVE_X509_STORE_SET_VERIFY_CB */
687
688 /**
689 * Setup server-side TLS context
690 */
691 bool SetupServerTlsContext(SSL_CTX *context)
692 {
693 if ((s_serverCertificate == NULL) || (s_serverCertificateKey == NULL))
694 return false;
695
696 X509_STORE *store = X509_STORE_new();
697 if (store == NULL)
698 {
699 nxlog_debug(3, _T("SetupServerTlsContext: cannot create certificate store"));
700 return false;
701 }
702 #if HAVE_X509_STORE_SET_VERIFY_CB
703 X509_STORE_set_verify_cb(store, CertVerifyCallback);
704 #endif
705 X509_STORE_add_cert(store, s_serverCertificate);
706 for(int i = 0; i < s_serverCACertificates.size(); i++)
707 X509_STORE_add_cert(store, s_serverCACertificates.get(i));
708 SSL_CTX_set_cert_store(context, store);
709 SSL_CTX_use_certificate(context, s_serverCertificate);
710 SSL_CTX_use_PrivateKey(context, s_serverCertificateKey);
711 SSL_CTX_set_verify(context, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL);
712 return true;
713 }
714
715 #else /* _WITH_ENCRYPTION */
716
717 /**
718 * Stub for certificate initialization
719 */
720 void InitCertificates()
721 {
722 }
723
724 #endif /* _WITH_ENCRYPTION */