forked from rsyslog/rsyslog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsd_ossl.c
2002 lines (1717 loc) · 58.7 KB
/
nsd_ossl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* nsd_ossl.c
*
* An implementation of the nsd interface for OpenSSL.
*
* Copyright 2018-2019 Adiscon GmbH.
* Author: Andre Lorbach
*
* This file is part of the rsyslog runtime library.
*
* The rsyslog runtime library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The rsyslog runtime library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the rsyslog runtime library. If not, see <http://www.gnu.org/licenses/>.
*
* A copy of the GPL can be found in the file "COPYING" in this distribution.
* A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include <openssl/engine.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include "rsyslog.h"
#include "syslogd-types.h"
#include "module-template.h"
#include "cfsysline.h"
#include "obj.h"
#include "stringbuf.h"
#include "errmsg.h"
#include "net.h"
#include "datetime.h"
#include "nsd_ptcp.h"
#include "nsdsel_ossl.h"
#include "nsd_ossl.h"
#include "unicode-helper.h"
/* things to move to some better place/functionality - TODO */
// #define CRLFILE "crl.pem"
MODULE_TYPE_LIB
MODULE_TYPE_KEEP
/* static data */
DEFobjStaticHelpers
DEFobjCurrIf(glbl)
DEFobjCurrIf(net)
DEFobjCurrIf(datetime)
DEFobjCurrIf(nsd_ptcp)
/* OpenSSL API differences */
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
#define RSYSLOG_X509_NAME_oneline(X509CERT) X509_get_subject_name(X509CERT)
#define RSYSLOG_BIO_method_name(SSLBIO) BIO_method_name(SSLBIO)
#define RSYSLOG_BIO_number_read(SSLBIO) BIO_number_read(SSLBIO)
#define RSYSLOG_BIO_number_written(SSLBIO) BIO_number_written(SSLBIO)
#else
#define RSYSLOG_X509_NAME_oneline(X509CERT) (X509CERT != NULL ? X509CERT->cert_info->subject : NULL)
#define RSYSLOG_BIO_method_name(SSLBIO) SSLBIO->method->name
#define RSYSLOG_BIO_number_read(SSLBIO) SSLBIO->num
#define RSYSLOG_BIO_number_written(SSLBIO) SSLBIO->num
#endif
static int bGlblSrvrInitDone = 0; /**< 0 - server global init not yet done, 1 - already done */
/* Main OpenSSL CTX pointer */
static SSL_CTX *ctx;
/* Static Helper variables for CERT status */
static short bHaveCA;
static short bHaveCert;
static short bHaveKey;
static int bAnonInit;
static MUTEX_TYPE anonInit_mut = PTHREAD_MUTEX_INITIALIZER;
/*--------------------------------------MT OpenSSL helpers ------------------------------------------*/
static MUTEX_TYPE *mutex_buf = NULL;
void locking_function(int mode, int n,
__attribute__((unused)) const char * file, __attribute__((unused)) int line)
{
if (mode & CRYPTO_LOCK)
MUTEX_LOCK(mutex_buf[n]);
else
MUTEX_UNLOCK(mutex_buf[n]);
}
unsigned long id_function(void)
{
return ((unsigned long)THREAD_ID);
}
struct CRYPTO_dynlock_value * dyn_create_function(
__attribute__((unused)) const char *file, __attribute__((unused)) int line)
{
struct CRYPTO_dynlock_value *value;
value = (struct CRYPTO_dynlock_value *)malloc(sizeof(struct CRYPTO_dynlock_value));
if (!value)
return NULL;
MUTEX_SETUP(value->mutex);
return value;
}
void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l,
__attribute__((unused)) const char *file, __attribute__((unused)) int line)
{
if (mode & CRYPTO_LOCK)
MUTEX_LOCK(l->mutex);
else
MUTEX_UNLOCK(l->mutex);
}
void dyn_destroy_function(struct CRYPTO_dynlock_value *l,
__attribute__((unused)) const char *file, __attribute__((unused)) int line)
{
MUTEX_CLEANUP(l->mutex);
free(l);
}
/* set up support functions for openssl multi-threading. This must
* be done at library initialisation. If the function fails,
* processing can not continue normally. On failure, 0 is
* returned, on success 1.
*/
int opensslh_THREAD_setup(void)
{
int i;
mutex_buf = (MUTEX_TYPE *)malloc(CRYPTO_num_locks( ) * sizeof(MUTEX_TYPE));
if (mutex_buf == NULL)
return 0;
for (i = 0; i < CRYPTO_num_locks( ); i++)
MUTEX_SETUP(mutex_buf[i]);
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
/* The following three CRYPTO_... functions are the OpenSSL functions
for registering the callbacks we implemented above */
CRYPTO_set_dynlock_create_callback(dyn_create_function);
CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
DBGPRINTF("openssl: multithread setup finished\n");
return 1;
}
/* shut down openssl - do this only when you are totally done
* with openssl.
*/
int opensslh_THREAD_cleanup(void)
{
int i;
if (!mutex_buf)
return 0;
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
CRYPTO_set_dynlock_create_callback(NULL);
CRYPTO_set_dynlock_lock_callback(NULL);
CRYPTO_set_dynlock_destroy_callback(NULL);
for (i = 0; i < CRYPTO_num_locks( ); i++)
MUTEX_CLEANUP(mutex_buf[i]);
free(mutex_buf);
mutex_buf = NULL;
DBGPRINTF("openssl: multithread cleanup finished\n");
return 1;
}
/*-------------------------------------- MT OpenSSL helpers -----------------------------------------*/
/*--------------------------------------OpenSSL helpers ------------------------------------------*/
void osslLastSSLErrorMsg(int ret, SSL *ssl, int severity, const char* pszCallSource)
{
unsigned long un_error = 0;
int iSSLErr = 0;
if (ssl == NULL) {
/* Output Error Info*/
dbgprintf("osslLastSSLErrorMsg: Error in '%s' with ret=%d\n", pszCallSource, ret);
} else {
/* if object is set, get error code */
iSSLErr = SSL_get_error(ssl, ret);
/* Output error message */
dbgprintf("osslLastSSLErrorMsg: Error '%s(%d)' in '%s' with ret=%d\n",
ERR_error_string(iSSLErr, NULL), iSSLErr, pszCallSource, ret);
if(iSSLErr == SSL_ERROR_SSL) {
LogMsg(0, RS_RET_NO_ERRCODE, severity, "SSL_ERROR_SSL in '%s'", pszCallSource);
} else if(iSSLErr == SSL_ERROR_SYSCALL){
/* SSL doc says: For socket I/O on Unix systems, consult errno for details, so it
* is save to use errno in this case */
LogMsg(errno, RS_RET_NO_ERRCODE, severity, "SSL_ERROR_SYSCALL in '%s'", pszCallSource);
} else {
LogMsg(0, RS_RET_NO_ERRCODE, severity, "SSL_ERROR_UNKNOWN in '%s', SSL_get_error: '%s(%d)'",
pszCallSource, ERR_error_string(iSSLErr, NULL), iSSLErr);
}
}
/* Loop through ERR_get_error */
while ((un_error = ERR_get_error()) > 0){
LogMsg(0, RS_RET_NO_ERRCODE, severity, "OpenSSL Error Stack: %s", ERR_error_string(un_error, NULL) );
}
}
int verify_callback(int status, X509_STORE_CTX *store)
{
char szdbgdata1[256];
char szdbgdata2[256];
dbgprintf("verify_callback: status %d\n", status);
if(status == 0) {
/* Retrieve all needed pointers */
X509 *cert = X509_STORE_CTX_get_current_cert(store);
int depth = X509_STORE_CTX_get_error_depth(store);
int err = X509_STORE_CTX_get_error(store);
SSL* ssl = X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx());
int iVerifyMode = SSL_get_verify_mode(ssl);
nsd_ossl_t *pThis = (nsd_ossl_t*) SSL_get_ex_data(ssl, 0);
assert(pThis != NULL);
dbgprintf("verify_callback: Certificate validation failed, Mode (%d)!\n", iVerifyMode);
X509_NAME_oneline(X509_get_issuer_name(cert), szdbgdata1, sizeof(szdbgdata1));
X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(cert), szdbgdata2, sizeof(szdbgdata2));
if (iVerifyMode != SSL_VERIFY_NONE) {
/* Handle expired Certificates **/
if (err == X509_V_OK || err == X509_V_ERR_CERT_HAS_EXPIRED) {
if (pThis->permitExpiredCerts == OSSL_EXPIRED_PERMIT) {
dbgprintf("verify_callback: EXPIRED cert but PERMITTED at depth: %d \n\t"
"issuer = %s\n\t"
"subject = %s\n\t"
"err %d:%s\n", depth, szdbgdata1, szdbgdata2,
err, X509_verify_cert_error_string(err));
/* Set Status to OK*/
status = 1;
}
else if (pThis->permitExpiredCerts == OSSL_EXPIRED_WARN) {
LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
"Certificate EXPIRED warning at depth: %d \n\t"
"issuer = %s\n\t"
"subject = %s\n\t"
"err %d:%s",
depth, szdbgdata1, szdbgdata2,
err, X509_verify_cert_error_string(err));
/* Set Status to OK*/
status = 1;
}
else /* also default - if (pThis->permitExpiredCerts == OSSL_EXPIRED_DENY)*/ {
LogError(0, RS_RET_NO_ERRCODE,
"Certificate EXPIRED at depth: %d \n\t"
"issuer = %s\n\t"
"subject = %s\n\t"
"err %d:%s",
depth, szdbgdata1, szdbgdata2,
err, X509_verify_cert_error_string(err));
}
} else {
/* all other error codes cause failure */
LogError(0, RS_RET_NO_ERRCODE,
"Certificate error at depth: %d \n\t"
"issuer = %s\n\t"
"subject = %s\n\t"
"err %d:%s",
depth, szdbgdata1, szdbgdata2, err, X509_verify_cert_error_string(err));
}
} else {
/* do not verify certs in ANON mode, just log into debug */
dbgprintf("verify_callback: Certificate validation DISABLED but Error at depth: %d \n\t"
"issuer = %s\n\t"
"subject = %s\n\t"
"err %d:%s\n", depth, szdbgdata1, szdbgdata2,
err, X509_verify_cert_error_string(err));
/* Set Status to OK*/
status = 1;
}
}
return status;
}
long BIO_debug_callback(BIO *bio, int cmd, const char __attribute__((unused)) *argp,
int argi, long __attribute__((unused)) argl, long ret)
{
long r = 1;
if (BIO_CB_RETURN & cmd)
r = ret;
dbgprintf("openssl debugmsg: BIO[%p]: ", (void *)bio);
switch (cmd) {
case BIO_CB_FREE:
dbgprintf("Free - %s\n", RSYSLOG_BIO_method_name(bio));
break;
/* Disabled due API changes for OpenSSL 1.1.0+ */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
case BIO_CB_READ:
if (bio->method->type & BIO_TYPE_DESCRIPTOR)
dbgprintf("read(%d,%lu) - %s fd=%d\n",
RSYSLOG_BIO_number_read(bio), (unsigned long)argi,
RSYSLOG_BIO_method_name(bio), RSYSLOG_BIO_number_read(bio));
else
dbgprintf("read(%d,%lu) - %s\n", RSYSLOG_BIO_number_read(bio),
(unsigned long)argi, RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_WRITE:
if (bio->method->type & BIO_TYPE_DESCRIPTOR)
dbgprintf("write(%d,%lu) - %s fd=%d\n",
RSYSLOG_BIO_number_written(bio), (unsigned long)argi,
RSYSLOG_BIO_method_name(bio), RSYSLOG_BIO_number_written(bio));
else
dbgprintf("write(%d,%lu) - %s\n",
RSYSLOG_BIO_number_written(bio),
(unsigned long)argi,
RSYSLOG_BIO_method_name(bio));
break;
#else
case BIO_CB_READ:
dbgprintf("read %s\n", RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_WRITE:
dbgprintf("write %s\n", RSYSLOG_BIO_method_name(bio));
break;
#endif
case BIO_CB_PUTS:
dbgprintf("puts() - %s\n", RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_GETS:
dbgprintf("gets(%lu) - %s\n", (unsigned long)argi,
RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_CTRL:
dbgprintf("ctrl(%lu) - %s\n", (unsigned long)argi,
RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_RETURN | BIO_CB_READ:
dbgprintf("read return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_WRITE:
dbgprintf("write return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_GETS:
dbgprintf("gets return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_PUTS:
dbgprintf("puts return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_CTRL:
dbgprintf("ctrl return %ld\n", ret);
break;
default:
dbgprintf("bio callback - unknown type (%d)\n", cmd);
break;
}
return (r);
}
/* Convert a fingerprint to printable data. The conversion is carried out
* according IETF I-D syslog-transport-tls-12. The fingerprint string is
* returned in a new cstr object. It is the caller's responsibility to
* destruct that object.
* rgerhards, 2008-05-08
*/
static rsRetVal
GenFingerprintStr(uchar *pFingerprint, size_t sizeFingerprint, cstr_t **ppStr)
{
cstr_t *pStr = NULL;
uchar buf[4];
size_t i;
DEFiRet;
CHKiRet(rsCStrConstruct(&pStr));
CHKiRet(rsCStrAppendStrWithLen(pStr, (uchar*)"SHA1", 4));
for(i = 0 ; i < sizeFingerprint ; ++i) {
snprintf((char*)buf, sizeof(buf), ":%2.2X", pFingerprint[i]);
CHKiRet(rsCStrAppendStrWithLen(pStr, buf, 3));
}
cstrFinalize(pStr);
*ppStr = pStr;
finalize_it:
if(iRet != RS_RET_OK) {
if(pStr != NULL)
rsCStrDestruct(&pStr);
}
RETiRet;
}
/* globally initialize OpenSSL */
static rsRetVal
osslGlblInit(void)
{
DEFiRet;
DBGPRINTF("openssl: entering osslGlblInit\n");
const char *caFile, *certFile, *keyFile;
/* Setup OpenSSL library */
if((opensslh_THREAD_setup() == 0) || !SSL_library_init()) {
LogError(0, RS_RET_NO_ERRCODE, "Error: OpenSSL initialization failed!");
}
/* Load readable error strings */
SSL_load_error_strings();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
/* Setup certificates */
caFile = (const char *) glbl.GetDfltNetstrmDrvrCAF();
if(caFile == NULL) {
LogMsg(0, RS_RET_CA_CERT_MISSING, LOG_WARNING,
"Warning: CA certificate is not set");
bHaveCA = 0;
} else {
bHaveCA = 1;
}
certFile = (const char *) glbl.GetDfltNetstrmDrvrCertFile();
if(certFile == NULL) {
LogMsg(0, RS_RET_CERT_MISSING, LOG_WARNING,
"Warning: Certificate file is not set");
bHaveCert = 0;
} else {
bHaveCert = 1;
}
keyFile = (const char *) glbl.GetDfltNetstrmDrvrKeyFile();
if(keyFile == NULL) {
LogMsg(0, RS_RET_CERTKEY_MISSING, LOG_WARNING,
"Warning: Key file is not set");
bHaveKey = 0;
} else {
bHaveKey = 1;
}
/* Create main CTX Object */
ctx = SSL_CTX_new(SSLv23_method());
if(bHaveCA == 1 && SSL_CTX_load_verify_locations(ctx, caFile, NULL) != 1) {
LogError(0, RS_RET_TLS_CERT_ERR, "Error: CA certificate could not be accessed. "
"Check at least: 1) file path is correct, 2) file exist, "
"3) permissions are correct, 4) file content is correct. "
"Open ssl error info may follow in next messages");
osslLastSSLErrorMsg(0, NULL, LOG_ERR, "osslGlblInit");
ABORT_FINALIZE(RS_RET_TLS_CERT_ERR);
}
if(bHaveCert == 1 && SSL_CTX_use_certificate_file(ctx, certFile, SSL_FILETYPE_PEM) != 1) {
LogError(0, RS_RET_TLS_CERT_ERR, "Error: Certificate could not be accessed. "
"Check at least: 1) file path is correct, 2) file exist, "
"3) permissions are correct, 4) file content is correct. "
"Open ssl error info may follow in next messages");
osslLastSSLErrorMsg(0, NULL, LOG_ERR, "osslGlblInit");
ABORT_FINALIZE(RS_RET_TLS_CERT_ERR);
}
if(bHaveKey == 1 && SSL_CTX_use_PrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM) != 1) {
LogError(0, RS_RET_TLS_KEY_ERR , "Error: Key could not be accessed. "
"Check at least: 1) file path is correct, 2) file exist, "
"3) permissions are correct, 4) file content is correct. "
"Open ssl error info may follow in next messages");
osslLastSSLErrorMsg(0, NULL, LOG_ERR, "osslGlblInit");
ABORT_FINALIZE(RS_RET_TLS_KEY_ERR);
}
/* Set CTX Options */
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); /* Disable insecure SSLv2 Protocol */
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3); /* Disable insecure SSLv3 Protocol */
SSL_CTX_sess_set_cache_size(ctx,1024); /* TODO: make configurable? */
/* Set default VERIFY Options for OpenSSL CTX - and CALLBACK */
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
SSL_CTX_set_timeout(ctx, 30); /* Default Session Timeout, TODO: Make configureable */
SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
bGlblSrvrInitDone = 1;
/* Anon Ciphers will only be initialized when Authmode is set to ANON later */
bAnonInit = 0;
finalize_it:
RETiRet;
}
/* Init Anon OpenSSL helpers */
static rsRetVal
osslAnonInit(void)
{
DEFiRet;
pthread_mutex_lock(&anonInit_mut);
if (bAnonInit == 1) {
/* we are done */
FINALIZE;
}
dbgprintf("osslAnonInit Init Anon OpenSSL helpers\n");
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
/* Enable Support for automatic EC temporary key parameter selection. */
SSL_CTX_set_ecdh_auto(ctx, 1);
#else
dbgprintf("osslAnonInit: openssl to old, cannot use SSL_CTX_set_ecdh_auto."
"Using SSL_CTX_set_tmp_ecdh with NID_X9_62_prime256v1/() instead.\n");
SSL_CTX_set_tmp_ecdh(ctx, EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
#endif
bAnonInit = 1;
finalize_it:
pthread_mutex_unlock(&anonInit_mut);
RETiRet;
}
/* try to receive a record from the remote peer. This works with
* our own abstraction and handles local buffering and EAGAIN.
* See details on local buffering in Rcv(9 header-comment.
* This function MUST only be called when the local buffer is
* empty. Calling it otherwise will cause losss of current buffer
* data.
* rgerhards, 2008-06-24
*/
rsRetVal
osslRecordRecv(nsd_ossl_t *pThis)
{
ssize_t lenRcvd;
DEFiRet;
int err;
int local_errno;
ISOBJ_TYPE_assert(pThis, nsd_ossl);
DBGPRINTF("osslRecordRecv: start\n");
lenRcvd = SSL_read(pThis->ssl, pThis->pszRcvBuf, NSD_OSSL_MAX_RCVBUF);
if(lenRcvd > 0) {
DBGPRINTF("osslRecordRecv: SSL_read received %zd bytes\n", lenRcvd);
pThis->lenRcvBuf = lenRcvd;
pThis->ptrRcvBuf = 0;
/* Check for additional data in SSL buffer */
int iBytesLeft = SSL_pending(pThis->ssl);
if (iBytesLeft > 0 ){
DBGPRINTF("osslRecordRecv: %d Bytes pending after SSL_Read, expand buffer.\n", iBytesLeft);
/* realloc buffer size and preserve char content */
char *const newbuf = realloc(pThis->pszRcvBuf, NSD_OSSL_MAX_RCVBUF+iBytesLeft);
CHKmalloc(newbuf);
pThis->pszRcvBuf = newbuf;
/* 2nd read will read missing bytes from the current SSL Packet */
lenRcvd = SSL_read(pThis->ssl, pThis->pszRcvBuf+NSD_OSSL_MAX_RCVBUF, iBytesLeft);
if(lenRcvd > 0) {
DBGPRINTF("osslRecordRecv: 2nd SSL_read received %zd bytes\n",
(NSD_OSSL_MAX_RCVBUF+lenRcvd));
pThis->lenRcvBuf = NSD_OSSL_MAX_RCVBUF+lenRcvd;
} else {
goto sslerr;
}
}
} else {
sslerr:
err = SSL_get_error(pThis->ssl, lenRcvd);
if( err == SSL_ERROR_ZERO_RETURN ) {
DBGPRINTF("osslRecordRecv: SSL_ERROR_ZERO_RETURN received, connection may closed already\n");
ABORT_FINALIZE(RS_RET_RETRY);
}
else if(err != SSL_ERROR_WANT_READ &&
err != SSL_ERROR_WANT_WRITE) {
DBGPRINTF("osslRecordRecv: SSL_get_error = %d\n", err);
/* Save errno */
local_errno = errno;
/* Output OpenSSL error*/
osslLastSSLErrorMsg(lenRcvd, pThis->ssl, LOG_ERR, "osslRecordRecv");
/* Check for underlaying socket errors **/
if (local_errno == ECONNRESET) {
DBGPRINTF("osslRecordRecv: Errno %d, connection resetted by peer\n", local_errno);
ABORT_FINALIZE(RS_RET_CLOSED);
} else {
DBGPRINTF("osslRecordRecv: Errno %d\n", local_errno);
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
} else {
DBGPRINTF("osslRecordRecv: SSL_get_error = %d\n", err);
pThis->rtryCall = osslRtry_recv;
pThis->rtryOsslErr = err; /* Store SSL ErrorCode into*/
ABORT_FINALIZE(RS_RET_RETRY);
}
}
// TODO: Check if MORE retry logic needed?
finalize_it:
dbgprintf("osslRecordRecv return. nsd %p, iRet %d, lenRcvd %d, lenRcvBuf %d, ptrRcvBuf %d\n",
pThis, iRet, (int) lenRcvd, pThis->lenRcvBuf, pThis->ptrRcvBuf);
RETiRet;
}
static rsRetVal
osslInitSession(nsd_ossl_t *pThis) /* , nsd_ossl_t *pServer) */
{
DEFiRet;
BIO *client;
char pristringBuf[4096];
nsd_ptcp_t *pPtcp = (nsd_ptcp_t*) pThis->pTcp;
if(!(pThis->ssl = SSL_new(ctx))) {
pThis->ssl = NULL;
osslLastSSLErrorMsg(0, pThis->ssl, LOG_ERR, "osslInitSession");
}
if (pThis->authMode != OSSL_AUTH_CERTANON) {
dbgprintf("osslInitSession: enable certificate checking (Mode=%d)\n", pThis->authMode);
/* Enable certificate valid checking */
SSL_set_verify(pThis->ssl, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback);
SSL_set_verify_depth(pThis->ssl, 2);
}
if (bAnonInit == 1) { /* no mutex needed, read-only after init */
/* Allow ANON Ciphers */
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
/* NOTE: do never use: +eNULL, it DISABLES encryption! */
strncpy(pristringBuf, "ALL:+COMPLEMENTOFDEFAULT:+ADH:+ECDH:+aNULL@SECLEVEL=0",
sizeof(pristringBuf));
#else
strncpy(pristringBuf, "ALL:+COMPLEMENTOFDEFAULT:+ADH:+ECDH:+aNULL",
sizeof(pristringBuf));
#endif
dbgprintf("osslInitSession: setting anon ciphers: %s\n", pristringBuf);
if ( SSL_set_cipher_list(pThis->ssl, pristringBuf) == 0 ){
dbgprintf("osslInitSession: Error setting ciphers '%s'\n", pristringBuf);
ABORT_FINALIZE(RS_RET_SYS_ERR);
}
}
/* Create BIO from ptcp socket! */
client = BIO_new_socket(pPtcp->sock, BIO_CLOSE /*BIO_NOCLOSE*/);
dbgprintf("osslInitSession: Init client BIO[%p] done\n", (void *)client);
/* Set debug Callback for client BIO as well! */
BIO_set_callback(client, BIO_debug_callback);
/* TODO: still needed? Set to NON blocking ! */
BIO_set_nbio( client, 1 );
SSL_set_bio(pThis->ssl, client, client);
SSL_set_accept_state(pThis->ssl); /* sets ssl to work in server mode. */
pThis->bHaveSess = 1;
pThis->sslState = osslServer; /*set Server state */
/* we are done */
FINALIZE;
finalize_it:
RETiRet;
}
/* Check the peer's ID in fingerprint auth mode.
* rgerhards, 2008-05-22
*/
static rsRetVal
osslChkPeerFingerprint(nsd_ossl_t *pThis, X509 *pCert)
{
unsigned int n;
uchar fingerprint[20 /*EVP_MAX_MD_SIZE**/];
size_t size;
cstr_t *pstrFingerprint = NULL;
int bFoundPositiveMatch;
permittedPeers_t *pPeer;
const EVP_MD *fdig = EVP_sha1();
DEFiRet;
ISOBJ_TYPE_assert(pThis, nsd_ossl);
/* obtain the SHA1 fingerprint */
size = sizeof(fingerprint);
if (!X509_digest(pCert,fdig,fingerprint,&n)) {
dbgprintf("osslChkPeerFingerprint: error X509cert is not valid!\n");
ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
}
CHKiRet(GenFingerprintStr(fingerprint, size, &pstrFingerprint));
dbgprintf("osslChkPeerFingerprint: peer's certificate SHA1 fingerprint: %s\n",
cstrGetSzStrNoNULL(pstrFingerprint));
/* now search through the permitted peers to see if we can find a permitted one */
bFoundPositiveMatch = 0;
pPeer = pThis->pPermPeers;
while(pPeer != NULL && !bFoundPositiveMatch) {
if(!rsCStrSzStrCmp(pstrFingerprint, pPeer->pszID, strlen((char*) pPeer->pszID))) {
dbgprintf("osslChkPeerFingerprint: peer's certificate MATCH found: %s\n", pPeer->pszID);
bFoundPositiveMatch = 1;
} else {
pPeer = pPeer->pNext;
}
}
if(!bFoundPositiveMatch) {
dbgprintf("osslChkPeerFingerprint: invalid peer fingerprint, not permitted to talk to it\n");
if(pThis->bReportAuthErr == 1) {
errno = 0;
LogError(0, RS_RET_INVALID_FINGERPRINT, "error: peer fingerprint '%s' unknown - we are "
"not permitted to talk to it", cstrGetSzStrNoNULL(pstrFingerprint));
pThis->bReportAuthErr = 0;
}
ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
}
finalize_it:
if(pstrFingerprint != NULL)
cstrDestruct(&pstrFingerprint);
RETiRet;
}
/* Perform a match on ONE peer name obtained from the certificate. This name
* is checked against the set of configured credentials. *pbFoundPositiveMatch is
* set to 1 if the ID matches. *pbFoundPositiveMatch must have been initialized
* to 0 by the caller (this is a performance enhancement as we expect to be
* called multiple times).
* TODO: implemet wildcards?
* rgerhards, 2008-05-26
*/
static rsRetVal
osslChkOnePeerName(nsd_ossl_t *pThis, X509 *pCert, uchar *pszPeerID, int *pbFoundPositiveMatch)
{
permittedPeers_t *pPeer;
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
int osslRet;
#endif
char *x509name = NULL;
DEFiRet;
ISOBJ_TYPE_assert(pThis, nsd_ossl);
assert(pszPeerID != NULL);
assert(pbFoundPositiveMatch != NULL);
/* Obtain Namex509 name from subject */
x509name = X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(pCert), NULL, 0);
if(pThis->pPermPeers) { /* do we have configured peer IDs? */
pPeer = pThis->pPermPeers;
while(pPeer != NULL) {
CHKiRet(net.PermittedPeerWildcardMatch(pPeer, pszPeerID, pbFoundPositiveMatch));
if(*pbFoundPositiveMatch)
break;
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
/* if we did not succeed so far, try ossl X509_check_host
* ( Includes check against SubjectAlternativeName )
*/
osslRet = X509_check_host( pCert, (const char*)pPeer->pszID,
strlen((const char*)pPeer->pszID), 0, NULL);
if ( osslRet == 1 ) {
/* Found Peer cert in allowed Peerslist */
dbgprintf("osslChkOnePeerName: Client ('%s') is allowed (X509_check_host)\n",
x509name);
*pbFoundPositiveMatch = 1;
break;
} else if ( osslRet < 0 ) {
osslLastSSLErrorMsg(osslRet, pThis->ssl, LOG_ERR, "osslChkOnePeerName");
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
#endif
/* Check next peer */
pPeer = pPeer->pNext;
}
} else {
/* we do not have configured peer IDs, so we use defaults */
if( pThis->pszConnectHost
&& !strcmp((char*)pszPeerID, (char*)pThis->pszConnectHost)) {
*pbFoundPositiveMatch = 1;
}
}
finalize_it:
if (x509name != NULL){
OPENSSL_free(x509name);
}
RETiRet;
}
/* Check the peer's ID in name auth mode.
*/
static rsRetVal
osslChkPeerName(nsd_ossl_t *pThis, X509 *pCert)
{
uchar lnBuf[256];
int bFoundPositiveMatch;
cstr_t *pStr = NULL;
char *x509name = NULL;
DEFiRet;
ISOBJ_TYPE_assert(pThis, nsd_ossl);
bFoundPositiveMatch = 0;
CHKiRet(rsCStrConstruct(&pStr));
/* Obtain Namex509 name from subject */
x509name = X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(pCert), NULL, 0);
dbgprintf("osslChkPeerName: checking - peername '%s'\n", x509name);
snprintf((char*)lnBuf, sizeof(lnBuf), "name: %s; ", x509name);
CHKiRet(rsCStrAppendStr(pStr, lnBuf));
CHKiRet(osslChkOnePeerName(pThis, pCert, (uchar*)x509name, &bFoundPositiveMatch));
if(!bFoundPositiveMatch) {
dbgprintf("osslChkPeerName: invalid peername, not permitted to talk to it\n");
if(pThis->bReportAuthErr == 1) {
cstrFinalize(pStr);
errno = 0;
LogError(0, RS_RET_INVALID_FINGERPRINT, "error: peer name not authorized - "
"not permitted to talk to it. Names: %s",
cstrGetSzStrNoNULL(pStr));
pThis->bReportAuthErr = 0;
}
ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
} else {
dbgprintf("osslChkPeerName: permitted to talk!\n");
}
finalize_it:
if (x509name != NULL){
OPENSSL_free(x509name);
}
if(pStr != NULL)
rsCStrDestruct(&pStr);
RETiRet;
}
/* check the ID of the remote peer - used for both fingerprint and
* name authentication.
*/
static rsRetVal
osslChkPeerID(nsd_ossl_t *pThis)
{
X509* certpeer;
DEFiRet;
ISOBJ_TYPE_assert(pThis, nsd_ossl);
/* Get peer certificate from SSL */
certpeer = SSL_get_peer_certificate(pThis->ssl);
if ( certpeer == NULL ) {
if(pThis->bReportAuthErr == 1) {
errno = 0;
LogError(0, RS_RET_TLS_NO_CERT, "error: peer did not provide a certificate, "
"not permitted to talk to it");
pThis->bReportAuthErr = 0;
}
ABORT_FINALIZE(RS_RET_TLS_NO_CERT);
}
/* Now we see which actual authentication code we must call. */
if(pThis->authMode == OSSL_AUTH_CERTFINGERPRINT) {
CHKiRet(osslChkPeerFingerprint(pThis, certpeer));
} else {
assert(pThis->authMode == OSSL_AUTH_CERTNAME);
CHKiRet(osslChkPeerName(pThis, certpeer));
}
finalize_it:
RETiRet;
}
/* Verify the validity of the remote peer's certificate.
*/
static rsRetVal
osslChkPeerCertValidity(nsd_ossl_t *pThis)
{
DEFiRet;
int iVerErr = X509_V_OK;
ISOBJ_TYPE_assert(pThis, nsd_ossl);
iVerErr = SSL_get_verify_result(pThis->ssl);
if (iVerErr != X509_V_OK) {
if (iVerErr == X509_V_ERR_CERT_HAS_EXPIRED) {
if (pThis->permitExpiredCerts == OSSL_EXPIRED_DENY) {
LogError(0, RS_RET_CERT_EXPIRED,
"CertValidity check - not permitted to talk to peer: certificate expired: %s",
X509_verify_cert_error_string(iVerErr));
ABORT_FINALIZE(RS_RET_CERT_EXPIRED);
} else if (pThis->permitExpiredCerts == OSSL_EXPIRED_WARN) {
LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
"CertValidity check - warning talking to peer: certificate expired: %s",
X509_verify_cert_error_string(iVerErr));
} else {
dbgprintf("osslChkPeerCertValidity: talking to peer: certificate expired: %s\n",
X509_verify_cert_error_string(iVerErr));
}/* Else do nothing */
} else {
LogError(0, RS_RET_CERT_INVALID, "not permitted to talk to peer: "
"certificate validation failed: %s", X509_verify_cert_error_string(iVerErr));
ABORT_FINALIZE(RS_RET_CERT_INVALID);
}
} else {
dbgprintf("osslChkPeerCertValidity: client certificate validation success: %s\n",
X509_verify_cert_error_string(iVerErr));
}
finalize_it:
RETiRet;
}
/* check if it is OK to talk to the remote peer
* rgerhards, 2008-05-21
*/
rsRetVal
osslChkPeerAuth(nsd_ossl_t *pThis)
{
DEFiRet;
ISOBJ_TYPE_assert(pThis, nsd_ossl);
/* call the actual function based on current auth mode */
switch(pThis->authMode) {
case OSSL_AUTH_CERTNAME:
/* if we check the name, we must ensure the cert is valid */
dbgprintf("osslChkPeerAuth: Check peer certname[%p]\n", (void *)pThis->ssl);
CHKiRet(osslChkPeerCertValidity(pThis));
CHKiRet(osslChkPeerID(pThis));
break;
case OSSL_AUTH_CERTFINGERPRINT:
dbgprintf("osslChkPeerAuth: Check peer fingerprint[%p]\n", (void *)pThis->ssl);
CHKiRet(osslChkPeerID(pThis));
break;
case OSSL_AUTH_CERTVALID:
dbgprintf("osslChkPeerAuth: Check peer valid[%p]\n", (void *)pThis->ssl);
CHKiRet(osslChkPeerCertValidity(pThis));
break;
case OSSL_AUTH_CERTANON:
FINALIZE;
break;
}
finalize_it:
RETiRet;
}
/* globally de-initialize OpenSSL */
static rsRetVal
osslGlblExit(void)
{
DEFiRet;
DBGPRINTF("openssl: entering osslGlblExit\n");
ENGINE_cleanup();
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
RETiRet;
}
/* end a OpenSSL session
* The function checks if we have a session and ends it only if so. So it can
* always be called, even if there currently is no session.
*/
static rsRetVal
osslEndSess(nsd_ossl_t *pThis)
{
DEFiRet;
int ret;
int err;
/* try closing SSL Connection */
if(pThis->bHaveSess) {
DBGPRINTF("osslEndSess: closing SSL Session ...\n");
ret = SSL_shutdown(pThis->ssl);