-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathtcp.c
3753 lines (3349 loc) · 113 KB
/
tcp.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
/* This implements the relp mapping onto TCP.
*
* Copyright 2008-2018 by Rainer Gerhards and Adiscon GmbH.
*
* This file is part of librelp.
*
* Note: gnutls_certificate_set_verify_function is problematic, as it
* is not available in old GnuTLS versions, but rather important
* for verifying certificates correctly.
*
* Librelp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Librelp 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Librelp. If not, see <http://www.gnu.org/licenses/>.
*
* A copy of the GPL can be found in the file "COPYING" in this distribution.
*
* If the terms of the GPL are unsuitable for your needs, you may obtain
* a commercial license from Adiscon. Contact [email protected] for further
* details.
*
* ALL CONTRIBUTORS PLEASE NOTE that by sending contributions, you assign
* your copyright to Adiscon GmbH, Germany. This is necessary to permit the
* dual-licensing set forth here. Our apologies for this inconvenience, but
* we sincerely believe that the dual-licensing model helps us provide great
* free software while at the same time obtaining some funding for further
* development.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <poll.h>
#include <assert.h>
#include "relp.h"
#include "relpsrv.h"
#include "relpclt.h"
#include "relpsess.h"
#include "tcp.h"
#ifdef ENABLE_TLS
# include <gnutls/gnutls.h>
# include <gnutls/x509.h>
# if GNUTLS_VERSION_NUMBER <= 0x020b00
# include <gcrypt.h>
GCRY_THREAD_OPTION_PTHREAD_IMPL;
# endif
static int called_gnutls_global_init = 0;
#endif
#ifdef ENABLE_TLS_OPENSSL
# include <openssl/ssl.h>
# include <openssl/x509v3.h>
# include <openssl/err.h>
# include <openssl/engine.h>
/* 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
#endif /* #ifdef ENABLE_TLS_OPENSSL */
#ifndef SOL_TCP
# define SOL_TCP (getprotobyname("tcp")->p_proto)
#endif
/* AIX: MSG_DONTWAIT not supported */
#if defined(_AIX) && !defined(MSG_DONTWAIT)
#define MSG_DONTWAIT MSG_NONBLOCK
#endif
static relpRetVal LIBRELP_ATTR_NONNULL() relpTcpAcceptConnReqInitTLS(NOTLS_UNUSED relpTcp_t *const pThis,
NOTLS_UNUSED relpSrv_t *const pSrv);
static relpRetVal relpTcpPermittedPeerWildcardCompile(tcpPermittedPeerEntry_t *pEtry);
static relpRetVal LIBRELP_ATTR_NONNULL() relpTcpLstnInitTLS(relpTcp_t *const pThis);
static relpRetVal LIBRELP_ATTR_NONNULL() relpTcpTLSSetPrio(relpTcp_t *const pThis);
/* helper to call onErr if set */
static void
callOnErr(const relpTcp_t *__restrict__ const pThis,
char *__restrict__ const emsg,
const relpRetVal ecode)
{
char objinfo[1024];
pThis->pEngine->dbgprint((char*)"librelp: generic error: ecode %d, "
"emsg '%s'\n", ecode, emsg);
if(pThis->pEngine->onErr != NULL) {
if(pThis->pSrv == NULL) { /* client */
snprintf(objinfo, sizeof(objinfo), "conn to srvr %s:%s",
pThis->pClt->pSess->srvAddr,
pThis->pClt->pSess->srvPort);
} else if(pThis->pRemHostIP == NULL) { /* server listener */
snprintf(objinfo, sizeof(objinfo), "lstn %s",
pThis->pSrv->pLstnPort);
} else { /* server connection to client */
snprintf(objinfo, sizeof(objinfo), "lstn %s: conn to clt %s/%s",
pThis->pSrv->pLstnPort, pThis->pRemHostIP,
pThis->pRemHostName);
}
objinfo[sizeof(objinfo)-1] = '\0';
pThis->pEngine->onErr(pThis->pUsr, objinfo, emsg, ecode);
}
}
#if defined(WITH_TLS)
/* forward definitions */
static int LIBRELP_ATTR_NONNULL() relpTcpGetCN(char *const namebuf, const size_t lenNamebuf, const char *const szDN);
#ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION
static int relpTcpVerifyCertificateCallback(gnutls_session_t session);
#endif /* #ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION */
#if defined(HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION) || defined(ENABLE_TLS_OPENSSL)
static void relpTcpChkOnePeerName(relpTcp_t *const pThis, char *peername, int *pbFoundPositiveMatch);
static int relpTcpAddToCertNamesBuffer(relpTcp_t *const pThis, char *const buf,
const size_t buflen, int *p_currIdx, const char *const certName);
static int relpTcpChkPeerName(relpTcp_t *const pThis, void* cert);
#endif /* defined(HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION) || defined(ENABLE_TLS_OPENSSL) */
/* helper to free permittedPeer structure */
static inline void
relpTcpFreePermittedPeers(relpTcp_t *const pThis)
{
int i;
for(i = 0 ; i < pThis->permittedPeers.nmemb ; ++i)
free(pThis->permittedPeers.peer[i].name);
pThis->permittedPeers.nmemb = 0;
if(pThis->permittedPeers.peer != NULL)
free(pThis->permittedPeers.peer);
}
/* helper to call onAuthErr if set */
static inline void
callOnAuthErr(relpTcp_t *const pThis, const char *authdata, const char *emsg, relpRetVal ecode)
{
pThis->pEngine->dbgprint((char*)"librelp: auth error: authdata:'%s', ecode %d, "
"emsg '%s'\n", authdata, ecode, emsg);
if(pThis->pEngine->onAuthErr != NULL) {
pThis->pEngine->onAuthErr(pThis->pUsr, (char*)authdata, (char*)emsg, ecode);
}
}
#endif /* #ifdef WITH_TLS */
#ifdef ENABLE_TLS_OPENSSL
/* Helper to detect when OpenSSL is initialized */
static int called_openssl_global_init = 0;
/* Main OpenSSL CTX pointer */
static SSL_CTX *ctx = NULL;
/*--------------------------------------MT OpenSSL helpers ------------------------------------------*/
static MUTEX_TYPE *mutex_buf = NULL;
void locking_function(int mode, int n,
LIBRELP_ATTR_UNUSED const char * file, LIBRELP_ATTR_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(
LIBRELP_ATTR_UNUSED const char *file, LIBRELP_ATTR_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,
LIBRELP_ATTR_UNUSED const char *file, LIBRELP_ATTR_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,
LIBRELP_ATTR_UNUSED const char *file, LIBRELP_ATTR_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);
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;
return 1;
}
/*--------------------------------------MT OpenSSL helpers ------------------------------------------*/
/* OpenSSL Helper functions */
/* OpenSSL implementation of TLS funtions.
* alorbach, 2018-06-11
*/
long BIO_debug_callback(BIO *bio, int cmd, const char LIBRELP_ATTR_UNUSED *argp,
int argi, long LIBRELP_ATTR_UNUSED argl, long ret)
{
long r = 1;
relpTcp_t* pThis = (relpTcp_t*) (void *) BIO_get_callback_arg(bio);
if (BIO_CB_RETURN & cmd)
r = ret;
switch (cmd) {
case BIO_CB_FREE:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: Free - %s\n",
(void *)bio, 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)
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: read(%d,%lu) - %s fd=%d\n",
(void *)bio,
RSYSLOG_BIO_number_read(bio), (unsigned long)argi,
RSYSLOG_BIO_method_name(bio), RSYSLOG_BIO_number_read(bio));
else
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: read(%d,%lu) - %s\n",
(void *)bio,
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)
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: write(%d,%lu) - %s fd=%d\n",
(void *)bio,
RSYSLOG_BIO_number_written(bio), (unsigned long)argi,
RSYSLOG_BIO_method_name(bio), RSYSLOG_BIO_number_written(bio));
else
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: write(%d,%lu) - %s\n",
(void *)bio,
RSYSLOG_BIO_number_written(bio), (unsigned long)argi, RSYSLOG_BIO_method_name(bio));
break;
#else
case BIO_CB_READ:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: read %s\n",
(void *)bio,
RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_WRITE:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: write %s\n",
(void *)bio,
RSYSLOG_BIO_method_name(bio));
break;
#endif
case BIO_CB_PUTS:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: puts() - %s\n",
(void *)bio,
RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_GETS:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: gets(%lu) - %s\n",
(void *)bio,
(unsigned long)argi,
RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_CTRL:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: ctrl(%lu) - %s\n",
(void *)bio,
(unsigned long)argi,
RSYSLOG_BIO_method_name(bio));
break;
case BIO_CB_RETURN | BIO_CB_READ:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: read return %ld\n",
(void *)bio,
ret);
break;
case BIO_CB_RETURN | BIO_CB_WRITE:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: write return %ld\n",
(void *)bio,
ret);
break;
case BIO_CB_RETURN | BIO_CB_GETS:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: gets return %ld\n",
(void *)bio,
ret);
break;
case BIO_CB_RETURN | BIO_CB_PUTS:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: puts return %ld\n",
(void *)bio,
ret);
break;
case BIO_CB_RETURN | BIO_CB_CTRL:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: ctrl return %ld\n",
(void *)bio,
ret);
break;
default:
pThis->pEngine->dbgprint((char*)"openssl debugmsg: BIO[%p]: bio callback - unknown type (%d)\n",
(void *)bio,
cmd);
break;
}
return (r);
}
void relpTcpLastSSLErrorMsg(int ret, relpTcp_t *const pThis, const char* pszCallSource)
{
unsigned long un_error = 0;
char psz[256];
char errstr[512];
char errmsg[1024];
/* Save errno */
int org_errno = errno;
if (pThis->ssl == NULL) {
/* Output Error Info*/
pThis->pEngine->dbgprint((char*)"relpTcpLastSSLErrorMsg: %s Error %d\n", pszCallSource, ret);
} else {
// Get Error details
long iSSLErr = SSL_get_error(pThis->ssl, ret);
ERR_error_string_n(iSSLErr, errstr, sizeof(errstr));
/* Output error message */
pThis->pEngine->dbgprint((char*)"relpTcpLastSSLErrorMsg: %s Error %s: %s(%ld) (ret=%d, errno=%d)\n",
pszCallSource,
(iSSLErr == SSL_ERROR_SSL ? "SSL_ERROR_SSL" :
(iSSLErr == SSL_ERROR_SYSCALL ? "SSL_ERROR_SYSCALL" : "SSL_ERROR_UNKNOWN")),
errstr, iSSLErr, ret, org_errno);
}
/* Loop through errors */
while ((un_error = ERR_get_error()) > 0){
ERR_error_string_n(un_error, psz, 256);
snprintf(errmsg, sizeof(errmsg),"relpTcpLastSSLErrorMsg: OpenSSL Error Stack: %s\n", psz);
callOnErr(pThis, errmsg, RELP_RET_ERR_TLS);
}
}
// TODO: openssl vs. gnutls?
/* Convert a fingerprint to printable data. The conversion is carried out
* according IETF I-D syslog-transport-tls-12. The fingerprint string is
*/
static relpRetVal
GenFingerprintStr_ossl(unsigned char *pFingerprint, size_t sizeFingerprint,
char * fpBuf,const size_t bufLen)
{
size_t iSrc, iDst;
ENTER_RELPFUNC;
if (bufLen <= 5) {
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
strncpy(fpBuf,"SHA1", bufLen);
iDst=4;
for(iSrc = 0; iSrc < sizeFingerprint && iSrc < bufLen; ++iSrc, iDst += 3) {
sprintf(fpBuf+iDst, ":%2.2X", (unsigned char) pFingerprint[iSrc]);
}
finalize_it:
LEAVE_RELPFUNC;
}
/* Check the peer's ID in fingerprint auth mode. */
static int
relpTcpChkPeerFingerprint_ossl(relpTcp_t *const pThis, X509* cert)
{
int i;
unsigned int n;
unsigned char fingerprint[20 /*EVP_MAX_MD_SIZE*/];
char fpPrintable[256];
size_t size;
int bFoundPositiveMatch;
const EVP_MD *fdig = EVP_sha1();
ENTER_RELPFUNC;
/* obtain the SHA1 fingerprint */
size = sizeof(fingerprint);
if (!X509_digest(cert,fdig,fingerprint,&n)) {
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerFingerprint: error X509cert is not valid!\n");
ABORT_FINALIZE(RELP_RET_ERR_TLS);
}
// TODO: fingerprint gtls vs ossl
GenFingerprintStr_ossl(fingerprint, size, fpPrintable,sizeof(fpPrintable));
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerFingerprint: "
"peer's certificate SHA1 fingerprint: %s\n", fpPrintable);
/* now search through the permitted peers to see if we can find a permitted one */
bFoundPositiveMatch = 0;
for(i = 0 ; i < pThis->permittedPeers.nmemb ; ++i)
{
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerFingerprint: checking peer '%s','%s'\n",
fpPrintable, pThis->permittedPeers.peer[i].name);
if(!strcmp(fpPrintable, pThis->permittedPeers.peer[i].name)) {
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerFingerprint: "
"peer's certificate MATCH found: %s\n",
pThis->permittedPeers.peer[i].name);
bFoundPositiveMatch = 1;
break;
}
}
if(!bFoundPositiveMatch) {
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerFingerprint: invalid peer fingerprint, "
"not permitted to talk to it\n");
callOnAuthErr(pThis, fpPrintable, "non-permited fingerprint", RELP_RET_AUTH_ERR_FP);
ABORT_FINALIZE(RELP_RET_AUTH_ERR_FP);
}
finalize_it:
LEAVE_RELPFUNC;
}
/* Check the peer's ID in name auth mode. */
static int
relpTcpChkPeerName_ossl(relpTcp_t *const pThis, void *vcert)
{
int r;
int bFoundPositiveMatch = 0;
char *x509name = NULL;
char allNames[32*1024]; /* work buffer */
int iAllNames = 0;
X509 *cert = (X509*)vcert;
/* Helpers for altName */
int iLoop;
int san_names_nb = -1;
GENERAL_NAMES *san_names = NULL;
GENERAL_NAME *gnDnsName;
int gtype;
ASN1_STRING *asDnsName;
const char *szAltName;
ENTER_RELPFUNC;
bFoundPositiveMatch = 0;
/* Obtain Namex509 name from subject */
x509name = X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(cert), NULL, 0);
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerName_ossl: checking - peername '%s'\n", x509name);
if((r = relpTcpGetCN(allNames, sizeof(allNames), x509name)) == 0) {
relpTcpChkOnePeerName(pThis, allNames, &bFoundPositiveMatch);
} else {
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerName_ossl: error %d extracting CN\n", r);
}
if(!bFoundPositiveMatch) {
/* Try to extract altname within the SAN extension from the certificate */
san_names = X509_get_ext_d2i((X509 *) cert, NID_subject_alt_name, NULL, NULL);
if (san_names == NULL) {
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerName_ossl: "
"X509_get_ext_d2i returned no ALTNAMES\n");
} else {
/* Loop through each name within the extension */
san_names_nb = sk_GENERAL_NAME_num(san_names);
for (iLoop=0; iLoop<san_names_nb; iLoop++) {
/* Get DNSName from san_names */
gnDnsName = sk_GENERAL_NAME_value(san_names, iLoop);
asDnsName = GENERAL_NAME_get0_value(gnDnsName, >ype);
# if OPENSSL_VERSION_NUMBER >= 0x10100000L
szAltName = (const char *)ASN1_STRING_get0_data(asDnsName);
# else
szAltName = (const char *)ASN1_STRING_data(asDnsName);
# endif
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerName_ossl: checking - "
"altName: '%s'\n", szAltName);
/* Add to Names Buffer first */
if (relpTcpAddToCertNamesBuffer(pThis, allNames, sizeof(allNames),
&iAllNames, (char *)szAltName) != 0)
ABORT_FINALIZE(RELP_RET_AUTH_CERT_INVL);
/* Perform PeerName check on AltName */
relpTcpChkOnePeerName(pThis, (char *)szAltName, &bFoundPositiveMatch);
/* Stop if match was found */
if (bFoundPositiveMatch)
break;
}
}
}
if(!bFoundPositiveMatch) {
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerName_ossl: invalid peername, "
"not permitted to talk to it\n");
callOnAuthErr(pThis, allNames, "no permited name found", RELP_RET_AUTH_ERR_NAME);
ABORT_FINALIZE(RELP_RET_AUTH_ERR_NAME);
} else {
pThis->pEngine->dbgprint((char*)"relpTcpChkPeerName_ossl: permitted to talk!\n");
}
finalize_it:
/* Free mem */
if (x509name != NULL){
OPENSSL_free(x509name);
}
if (san_names != NULL){
GENERAL_NAMES_free(san_names);
}
LEAVE_RELPFUNC;
}
int verify_callback(int status, X509_STORE_CTX *store)
{
char szdbgdata1[256];
char szdbgdata2[256];
char szdberrmsg[1024];
/* Get current SSL object in order to obtain relpTcp_t obj */
SSL* ssl = X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx());
relpTcp_t *pThis = (relpTcp_t *) SSL_get_ex_data(ssl, 0);
assert(pThis != NULL);
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);
/* Already failed ? */
if(status == 0) {
pThis->pEngine->dbgprint((char*)"verify_callback: certificate validation failed!\n");
X509_NAME_oneline(X509_get_issuer_name(cert), szdbgdata1, sizeof(szdbgdata1));
X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(cert), szdbgdata2, sizeof(szdbgdata2));
/* Log Warning only on EXPIRED */
if (err == X509_V_OK || err == X509_V_ERR_CERT_HAS_EXPIRED) {
snprintf(szdberrmsg, sizeof(szdberrmsg),
"Certificate expired in verify_callback 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));
pThis->pEngine->dbgprint((char*)"verify_callback: %s", szdberrmsg);
callOnAuthErr(pThis, (char*)X509_verify_cert_error_string(err),
szdberrmsg, RELP_RET_AUTH_CERT_INVL);
/* Set Status to OK ?!*/
status = 1;
} else {
snprintf(szdberrmsg, sizeof(szdberrmsg),
"Certificate error in verify_callback 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));
pThis->pEngine->dbgprint((char*)"verify_callback: %s", szdberrmsg);
callOnAuthErr(pThis, (char*)X509_verify_cert_error_string(err),
szdberrmsg, RELP_RET_AUTH_CERT_INVL);
}
} else {
pThis->pEngine->dbgprint((char*)"verify_callback: certificate validation success!\n");
}
return status;
}
#endif /* #ifdef ENABLE_TLS_OPENSSL */
/** Construct a RELP tcp instance
* This is the first thing that a caller must do before calling any
* RELP function. The relp tcp must only destructed after all RELP
* operations have been finished. Parameter pParent contains a pointer
* to the "parent" client or server object, depending on connType.
*/
relpRetVal
relpTcpConstruct(relpTcp_t **ppThis, relpEngine_t *const pEngine,
const int connType,
void *const pParent)
{
relpTcp_t *pThis;
ENTER_RELPFUNC;
assert(ppThis != NULL);
if((pThis = calloc(1, sizeof(relpTcp_t))) == NULL) {
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
RELP_CORE_CONSTRUCTOR(pThis, Tcp);
if(connType == RELP_SRV_CONN) {
pThis->pSrv = (relpSrv_t*) pParent;
} else {
pThis->pClt = (relpClt_t*) pParent;
}
pThis->sock = -1;
pThis->pEngine = pEngine;
pThis->iSessMax = 500; /* default max nbr of sessions - TODO: make configurable -- rgerhards, 2008-03-17*/
pThis->bTLSActive = 0;
pThis->dhBits = DEFAULT_DH_BITS;
pThis->pristring = NULL;
pThis->authmode = eRelpAuthMode_None;
pThis->caCertFile = NULL;
pThis->ownCertFile = NULL;
pThis->privKeyFile = NULL;
pThis->tlsConfigCmd = NULL;
pThis->pUsr = NULL;
pThis->permittedPeers.nmemb = 0;
pThis->permittedPeers.peer = NULL;
#ifdef ENABLE_TLS
pThis->xcred = NULL;
#endif
*ppThis = pThis;
finalize_it:
LEAVE_RELPFUNC;
}
#if defined(ENABLE_TLS)
static relpRetVal LIBRELP_ATTR_NONNULL()
relpTcpDestructTLS_gtls(relpTcp_t *pThis)
{
int sslRet;
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
sslRet = gnutls_bye(pThis->session, GNUTLS_SHUT_WR);
while(sslRet == GNUTLS_E_INTERRUPTED || sslRet == GNUTLS_E_AGAIN) {
sslRet = gnutls_bye(pThis->session, GNUTLS_SHUT_WR);
}
gnutls_deinit(pThis->session);
if (pThis->xcred != NULL) {
gnutls_certificate_free_credentials(pThis->xcred);
}
LEAVE_RELPFUNC;
}
#else
static relpRetVal LIBRELP_ATTR_NONNULL()
relpTcpDestructTLS_gtls(LIBRELP_ATTR_UNUSED relpTcp_t *pThis)
{
return RELP_RET_ERR_INTERNAL;
}
#endif /* defined(ENABLE_TLS) */
#if defined(ENABLE_TLS_OPENSSL)
static relpRetVal LIBRELP_ATTR_NONNULL()
relpTcpDestructTLS_ossl(relpTcp_t *pThis)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
if(pThis->ssl != NULL) {
pThis->pEngine->dbgprint((char*)"relpTcpDestruct_ossl: try "
"shutdown #1 for [%p]\n", (void *) pThis->ssl);
const int sslRet = SSL_shutdown(pThis->ssl);
if (sslRet <= 0) {
const int sslErr = SSL_get_error(pThis->ssl, sslRet);
pThis->pEngine->dbgprint((char*)"relpTcpDestruct_ossl: shutdown failed with err = %d, "
"forcing ssl shutdown!\n", sslErr);
/* ignore those SSL Errors on shutdown */
if( sslErr != SSL_ERROR_SYSCALL &&
sslErr != SSL_ERROR_ZERO_RETURN &&
sslErr != SSL_ERROR_WANT_READ &&
sslErr != SSL_ERROR_WANT_WRITE) {
/* Output Warning only */
relpTcpLastSSLErrorMsg(sslRet, pThis, "relpTcpDestruct_ossl");
}
pThis->pEngine->dbgprint((char*)"relpTcpDestruct_ossl: session closed (un)successfully \n");
} else {
pThis->pEngine->dbgprint((char*)"relpTcpDestruct_ossl: session closed successfully \n");
}
pThis->bTLSActive = 0;
SSL_free(pThis->ssl);
pThis->ssl = NULL;
}
LEAVE_RELPFUNC;
}
#else
static relpRetVal LIBRELP_ATTR_NONNULL()
relpTcpDestructTLS_ossl(LIBRELP_ATTR_UNUSED relpTcp_t *pThis)
{
return RELP_RET_ERR_INTERNAL;
}
#endif /* defined(ENABLE_TLS_OPENSSL) */
/* TLS-part of RELP tcp instance destruction - brought to its own function
* to make things easier.
*/
static relpRetVal LIBRELP_ATTR_NONNULL()
relpTcpDestructTLS(NOTLS_UNUSED relpTcp_t *pThis)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
#if defined(WITH_TLS)
if(pThis->bTLSActive) {
if(pThis->pEngine->tls_lib == 0) {
relpTcpDestructTLS_gtls(pThis);
} else {
relpTcpDestructTLS_ossl(pThis);
}
relpTcpFreePermittedPeers(pThis);
}
#endif /* #ifdef WITH_TLS */
LEAVE_RELPFUNC;
}
/** Destruct a RELP tcp instance */
relpRetVal
relpTcpDestruct(relpTcp_t **ppThis)
{
relpTcp_t *pThis;
ENTER_RELPFUNC;
assert(ppThis != NULL);
pThis = *ppThis;
RELPOBJ_assert(pThis, Tcp);
if(pThis->sock != -1) {
shutdown(pThis->sock, SHUT_RDWR);
close(pThis->sock);
pThis->sock = -1;
}
if(pThis->socks != NULL) {
/* if we have some sockets at this stage, we need to close them */
for(int i = 1 ; i <= pThis->socks[0] ; ++i) {
shutdown(pThis->socks[i], SHUT_RDWR);
close(pThis->socks[i]);
}
free(pThis->socks);
}
relpTcpDestructTLS(pThis);
free(pThis->pRemHostIP);
free(pThis->pRemHostName);
free(pThis->pristring);
free(pThis->caCertFile);
free(pThis->ownCertFile);
free(pThis->privKeyFile);
free(pThis->tlsConfigCmd);
/* done with de-init work, now free tcp object itself */
free(pThis);
*ppThis = NULL;
LEAVE_RELPFUNC;
}
#ifdef ENABLE_TLS
/* helper to call an error code handler if gnutls failed. If there is a failure,
* an error message is pulled form gnutls and the error message properly
* populated.
* Returns 1 if an error was detected, 0 otherwise. This can be used as a
* shortcut for error handling (safes doing it twice).
*/
static int
chkGnutlsCode(relpTcp_t *const pThis, const char *emsg, relpRetVal ecode, const int gnuRet)
{
int r;
if(gnuRet == GNUTLS_E_SUCCESS) {
r = 0;
} else {
char msgbuf[4096];
r = 1;
snprintf(msgbuf, sizeof(msgbuf), "%s [gnutls error %d: %s]",
emsg, gnuRet, gnutls_strerror(gnuRet));
msgbuf[sizeof(msgbuf)-1] = '\0';
callOnErr(pThis, msgbuf, ecode);
}
return r;
}
#endif /* #ifdef ENABLE_TLS */
/* abort a tcp connection. This is much like relpTcpDestruct(), but tries
* to discard any unsent data. -- rgerhards, 2008-03-24
*/
relpRetVal
relpTcpAbortDestruct(relpTcp_t **ppThis)
{
struct linger ling;
ENTER_RELPFUNC;
assert(ppThis != NULL);
RELPOBJ_assert((*ppThis), Tcp);
if((*ppThis)->sock != -1) {
ling.l_onoff = 1;
ling.l_linger = 0;
if(setsockopt((*ppThis)->sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0 ) {
(*ppThis)->pEngine->dbgprint((char*)"could not set SO_LINGER, errno %d\n", errno);
}
}
iRet = relpTcpDestruct(ppThis);
LEAVE_RELPFUNC;
}
#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
# define SALEN(sa) ((sa)->sa_len)
#else
static inline size_t SALEN(struct sockaddr *sa) {
switch (sa->sa_family) {
case AF_INET: return (sizeof(struct sockaddr_in));
case AF_INET6: return (sizeof(struct sockaddr_in6));
default: return 0;
}
}
#endif
/* we may later change the criteria, thus we encapsulate it
* into a function.
*/
static inline int8_t
isAnonAuth(relpTcp_t *const pThis)
{
return pThis->ownCertFile == NULL;
}
/* Set pRemHost based on the address provided. This is to be called upon accept()ing
* a connection request. It must be provided by the socket we received the
* message on as well as a NI_MAXHOST size large character buffer for the FQDN.
* Please see http://www.hmug.org/man/3/getnameinfo.php (under Caveats)
* for some explanation of the code found below. If we detect a malicious
* hostname, we return RELP_RET_MALICIOUS_HNAME and let the caller decide
* on how to deal with that.
* rgerhards, 2008-03-31
*/
static relpRetVal
relpTcpSetRemHost(relpTcp_t *const pThis, struct sockaddr *pAddr)
{
relpEngine_t *pEngine;
int error;
unsigned char szIP[NI_MAXHOST] = "";
unsigned char szHname[NI_MAXHOST+64] = ""; /* 64 extra bytes for message text */
struct addrinfo hints, *res;
size_t len;
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
pEngine = pThis->pEngine;
assert(pAddr != NULL);
error = getnameinfo(pAddr, SALEN(pAddr), (char*)szIP, sizeof(szIP), NULL, 0, NI_NUMERICHOST);
if(error) {
pThis->pEngine->dbgprint((char*)"Malformed from address %s\n", gai_strerror(error));
strcpy((char*)szHname, "???");
strcpy((char*)szIP, "???");
ABORT_FINALIZE(RELP_RET_INVALID_HNAME);
}
if(pEngine->bEnableDns) {
error = getnameinfo(pAddr, SALEN(pAddr), (char*)szHname, sizeof(szHname), NULL, 0, NI_NAMEREQD);
if(error == 0) {
memset (&hints, 0, sizeof (struct addrinfo));
hints.ai_flags = AI_NUMERICHOST;
hints.ai_socktype = SOCK_STREAM;
/* we now do a lookup once again. This one should fail,
* because we should not have obtained a non-numeric address. If
* we got a numeric one, someone messed with DNS!
*/
if(getaddrinfo((char*)szHname, NULL, &hints, &res) == 0) {
freeaddrinfo (res);
/* OK, we know we have evil, so let's indicate this to our caller */
snprintf((char*)szHname, sizeof(szHname), "[MALICIOUS:IP=%s]", szIP);
pEngine->dbgprint((char*)"Malicious PTR record, "
"IP = \"%s\" HOST = \"%s\"", szIP, szHname);
iRet = RELP_RET_MALICIOUS_HNAME;
}
} else {
strcpy((char*)szHname, (char*)szIP);
}
} else {
strcpy((char*)szHname, (char*)szIP);
}
/* We now have the names, so now let's allocate memory and store them permanently.
* (side note: we may hold on to these values for quite a while, thus we trim their
* memory consumption)
*/
len = strlen((char*)szIP) + 1; /* +1 for \0 byte */
if((pThis->pRemHostIP = malloc(len)) == NULL)
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
memcpy(pThis->pRemHostIP, szIP, len);
len = strlen((char*)szHname) + 1; /* +1 for \0 byte */
if((pThis->pRemHostName = malloc(len)) == NULL) {
free(pThis->pRemHostIP); /* prevent leak */
pThis->pRemHostIP = NULL;
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
memcpy(pThis->pRemHostName, szHname, len);
finalize_it:
LEAVE_RELPFUNC;
}
/* this copies a *complete* permitted peers structure into the
* tcp object.
*/
relpRetVal
relpTcpSetPermittedPeers(relpTcp_t LIBRELP_ATTR_UNUSED *pThis,
relpPermittedPeers_t LIBRELP_ATTR_UNUSED *pPeers)
{
ENTER_RELPFUNC;
#if defined(WITH_TLS)
int i;
relpTcpFreePermittedPeers(pThis);
if(pPeers->nmemb != 0) {
if((pThis->permittedPeers.peer =
malloc(sizeof(tcpPermittedPeerEntry_t) * pPeers->nmemb)) == NULL) {
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
for(i = 0 ; i < pPeers->nmemb ; ++i) {
if((pThis->permittedPeers.peer[i].name = strdup(pPeers->name[i])) == NULL) {
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
pThis->permittedPeers.peer[i].wildcardRoot = NULL;
pThis->permittedPeers.peer[i].wildcardLast = NULL;
CHKRet(relpTcpPermittedPeerWildcardCompile(&(pThis->permittedPeers.peer[i])));
}
}
pThis->permittedPeers.nmemb = pPeers->nmemb;
#else
ABORT_FINALIZE(RELP_RET_ERR_NO_TLS);
#endif /* #ifdef WITH_TLS */
finalize_it:
LEAVE_RELPFUNC;
}
relpRetVal