-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathtcp.c
1898 lines (1701 loc) · 54.7 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-2016 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 sales@adiscon.com 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
#ifndef SOL_TCP
# define SOL_TCP (getprotobyname("tcp")->p_proto)
#endif
#ifdef ENABLE_TLS
/* forward definitions */
#ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION
static int relpTcpVerifyCertificateCallback(gnutls_session_t session);
#endif /* #ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION */
static relpRetVal relpTcpPermittedPeerWildcardCompile(tcpPermittedPeerEntry_t *pEtry);
/* helper to free permittedPeer structure */
static inline void
relpTcpFreePermittedPeers(relpTcp_t *pThis)
{
int i;
for(i = 0 ; i < pThis->permittedPeers.nmemb ; ++i)
free(pThis->permittedPeers.peer[i].name);
pThis->permittedPeers.nmemb = 0;
}
#endif /* #ifdef ENABLE_TLS */
/** 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 *pEngine, int connType, void *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->pUsr = NULL;
pThis->permittedPeers.nmemb = 0;
*ppThis = pThis;
finalize_it:
LEAVE_RELPFUNC;
}
/** Destruct a RELP tcp instance
*/
relpRetVal
relpTcpDestruct(relpTcp_t **ppThis)
{
relpTcp_t *pThis;
int i;
#ifdef ENABLE_TLS
int gnuRet;
#endif /* #ifdef ENABLE_TLS */
ENTER_RELPFUNC;
assert(ppThis != NULL);
pThis = *ppThis;
RELPOBJ_assert(pThis, Tcp);
if(pThis->sock != -1) {
close(pThis->sock);
pThis->sock = -1;
}
if(pThis->socks != NULL) {
/* if we have some sockets at this stage, we need to close them */
for(i = 1 ; i <= pThis->socks[0] ; ++i)
close(pThis->socks[i]);
free(pThis->socks);
}
#ifdef ENABLE_TLS
if(pThis->bTLSActive) {
gnuRet = gnutls_bye(pThis->session, GNUTLS_SHUT_RDWR);
while(gnuRet == GNUTLS_E_INTERRUPTED || gnuRet == GNUTLS_E_AGAIN) {
gnuRet = gnutls_bye(pThis->session, GNUTLS_SHUT_RDWR);
}
gnutls_deinit(pThis->session);
}
relpTcpFreePermittedPeers(pThis);
#endif /* #ifdef ENABLE_TLS */
free(pThis->pRemHostIP);
free(pThis->pRemHostName);
free(pThis->pristring);
free(pThis->caCertFile);
free(pThis->ownCertFile);
free(pThis->privKeyFile);
/* done with de-init work, now free tcp object itself */
free(pThis);
*ppThis = NULL;
LEAVE_RELPFUNC;
}
/* 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("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);
}
}
#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 *pThis, char *emsg, relpRetVal ecode, int gnuRet)
{
char msgbuf[4096];
int r;
if(gnuRet == GNUTLS_E_SUCCESS) {
r = 0;
} else {
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;
}
/* helper to call onAuthErr if set */
static inline void
callOnAuthErr(relpTcp_t *pThis, char *authdata, char *emsg, relpRetVal ecode)
{
pThis->pEngine->dbgprint("librelp: auth error: authdata:'%s', ecode %d, "
"emsg '%s'\n", authdata, ecode, emsg);
if(pThis->pEngine->onAuthErr != NULL) {
pThis->pEngine->onAuthErr(pThis->pUsr, authdata, emsg, ecode);
}
}
#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("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 *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 *pThis, struct sockaddr *pAddr)
{
relpEngine_t *pEngine;
int error;
unsigned char szIP[NI_MAXHOST] = "";
unsigned char szHname[NI_MAXHOST] = "";
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("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, NI_MAXHOST, "[MALICIOUS:IP=%s]", szIP);
pEngine->dbgprint("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 __attribute__((unused)) *pThis,
relpPermittedPeers_t __attribute__((unused)) *pPeers)
{
ENTER_RELPFUNC;
#ifdef ENABLE_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 ENABLE_TLS */
finalize_it:
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetUsrPtr(relpTcp_t *pThis, void *pUsr)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
pThis->pUsr = pUsr;
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetAuthMode(relpTcp_t *pThis, relpAuthMode_t authmode)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
pThis->authmode = authmode;
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetConnTimeout(relpTcp_t *pThis, int connTimeout)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
pThis->connTimeout = connTimeout;
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetGnuTLSPriString(relpTcp_t *pThis, char *pristr)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
free(pThis->pristring);
if(pristr == NULL) {
pThis->pristring = NULL;
} else {
if((pThis->pristring = strdup(pristr)) == NULL)
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
finalize_it:
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetCACert(relpTcp_t *pThis, char *cert)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
free(pThis->caCertFile);
if(cert == NULL) {
pThis->caCertFile = NULL;
} else {
if((pThis->caCertFile = strdup(cert)) == NULL)
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
finalize_it:
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetOwnCert(relpTcp_t *pThis, char *cert)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
free(pThis->ownCertFile);
if(cert == NULL) {
pThis->ownCertFile = NULL;
} else {
if((pThis->ownCertFile = strdup(cert)) == NULL)
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
finalize_it:
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetPrivKey(relpTcp_t *pThis, char *cert)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
free(pThis->privKeyFile);
if(cert == NULL) {
pThis->privKeyFile = NULL;
} else {
# ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION
if((pThis->privKeyFile = strdup(cert)) == NULL)
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
# else
ABORT_FINALIZE(RELP_RET_ERR_NO_TLS_AUTH);
# endif
}
finalize_it:
LEAVE_RELPFUNC;
}
/* Enable TLS mode. */
relpRetVal
relpTcpEnableTLS(relpTcp_t __attribute__((unused)) *pThis)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
#ifdef ENABLE_TLS
pThis->bEnableTLS = 1;
#else
iRet = RELP_RET_ERR_NO_TLS;
#endif /* #ifdef ENABLE_TLS */
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpEnableTLSZip(relpTcp_t __attribute__((unused)) *pThis)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
#ifdef ENABLE_TLS
pThis->bEnableTLSZip = 1;
#else
iRet = RELP_RET_ERR_NO_TLS;
#endif /* #ifdef ENABLE_TLS */
LEAVE_RELPFUNC;
}
relpRetVal
relpTcpSetDHBits(relpTcp_t *pThis, int bits)
{
ENTER_RELPFUNC;
RELPOBJ_assert(pThis, Tcp);
pThis->dhBits = bits;
LEAVE_RELPFUNC;
}
#ifdef ENABLE_TLS
/* set TLS priority string, common code both for client and server */
static relpRetVal
relpTcpTLSSetPrio(relpTcp_t *pThis)
{
int r;
char pristringBuf[4096];
char *pristring;
ENTER_RELPFUNC;
/* Compute priority string (in simple cases where the user does not care...) */
if(pThis->pristring == NULL) {
if(pThis->bEnableTLSZip) {
strncpy(pristringBuf, "NORMAL:+ANON-DH:+COMP-ALL", sizeof(pristringBuf));
} else {
strncpy(pristringBuf, "NORMAL:+ANON-DH:+COMP-NULL", sizeof(pristringBuf));
}
pristringBuf[sizeof(pristringBuf)-1] = '\0';
pristring = pristringBuf;
} else {
pristring = pThis->pristring;
}
r = gnutls_priority_set_direct(pThis->session, pristring, NULL);
if(r == GNUTLS_E_INVALID_REQUEST) {
ABORT_FINALIZE(RELP_RET_INVLD_TLS_PRIO);
} else if(r != GNUTLS_E_SUCCESS) {
ABORT_FINALIZE(RELP_RET_ERR_TLS_SETUP);
}
finalize_it:
if(iRet != RELP_RET_OK)
chkGnutlsCode(pThis, "Failed to set GnuTLS priority", iRet, r);
LEAVE_RELPFUNC;
}
#pragma GCC diagnostic push
/* per https://lists.gnupg.org/pipermail/gnutls-help/2004-August/000154.html This is expected */
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
static relpRetVal
relpTcpAcceptConnReqInitTLS(relpTcp_t *pThis, relpSrv_t *pSrv)
{
int r;
ENTER_RELPFUNC;
r = gnutls_init(&pThis->session, GNUTLS_SERVER);
if(chkGnutlsCode(pThis, "Failed to initialize GnuTLS", RELP_RET_ERR_TLS_SETUP, r)) {
ABORT_FINALIZE(RELP_RET_ERR_TLS_SETUP);
}
gnutls_session_set_ptr(pThis->session, pThis);
if(pSrv->pTcp->pristring != NULL)
pThis->pristring = strdup(pSrv->pTcp->pristring);
pThis->authmode = pSrv->pTcp->authmode;
pThis->pUsr = pSrv->pUsr;
CHKRet(relpTcpTLSSetPrio(pThis));
if(isAnonAuth(pSrv->pTcp)) {
r = gnutls_credentials_set(pThis->session, GNUTLS_CRD_ANON, pSrv->pTcp->anoncredSrv);
if(chkGnutlsCode(pThis, "Failed setting anonymous credentials", RELP_RET_ERR_TLS_SETUP, r)) {
ABORT_FINALIZE(RELP_RET_ERR_TLS_SETUP);
}
} else { /* cert-based auth */
if(pSrv->pTcp->caCertFile == NULL) {
gnutls_certificate_send_x509_rdn_sequence(pThis->session, 0);
}
r = gnutls_credentials_set(pThis->session, GNUTLS_CRD_CERTIFICATE, pSrv->pTcp->xcred);
if(chkGnutlsCode(pThis, "Failed setting certificate credentials", RELP_RET_ERR_TLS_SETUP, r)) {
ABORT_FINALIZE(RELP_RET_ERR_TLS_SETUP);
}
}
gnutls_dh_set_prime_bits(pThis->session, pThis->dhBits);
gnutls_certificate_server_set_request(pThis->session, GNUTLS_CERT_REQUEST);
gnutls_transport_set_ptr(pThis->session, (gnutls_transport_ptr_t) pThis->sock);
r = gnutls_handshake(pThis->session);
if(r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN) {
pThis->pEngine->dbgprint("librelp: gnutls_handshake retry necessary (this is OK and expected)\n");
pThis->rtryOp = relpTCP_RETRY_handshake;
} else if(r != GNUTLS_E_SUCCESS) {
chkGnutlsCode(pThis, "TLS handshake failed", RELP_RET_ERR_TLS_HANDS, r);
ABORT_FINALIZE(RELP_RET_ERR_TLS_HANDS);
}
pThis->bTLSActive = 1;
finalize_it:
LEAVE_RELPFUNC;
}
#pragma GCC diagnostic pop
#endif /* #ifdef ENABLE_TLS */
/* Enable KEEPALIVE handling on the socket. */
static void
EnableKeepAlive(const relpTcp_t *__restrict__ const pThis,
const relpSrv_t *__restrict__ const pSrv,
const int sock)
{
int ret;
int optval;
socklen_t optlen;
optval = 1;
optlen = sizeof(optval);
ret = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen);
if(ret < 0) {
pThis->pEngine->dbgprint("librelp: EnableKeepAlive socket call "
"returns error %d\n", ret);
goto done;
}
# if defined(TCP_KEEPCNT)
if(pSrv->iKeepAliveProbes > 0) {
optval = pSrv->iKeepAliveProbes;
optlen = sizeof(optval);
ret = setsockopt(sock, SOL_TCP, TCP_KEEPCNT, &optval, optlen);
} else {
ret = 0;
}
# else
ret = -1;
# endif
if(ret < 0) {
callOnErr(pThis, "librelp cannot set keepalive probes - ignored",
RELP_RET_WRN_NO_KEEPALIVE);
}
# if defined(TCP_KEEPCNT)
if(pSrv->iKeepAliveTime > 0) {
optval = pSrv->iKeepAliveTime;
optlen = sizeof(optval);
ret = setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, &optval, optlen);
} else {
ret = 0;
}
# else
ret = -1;
# endif
if(ret < 0) {
callOnErr(pThis, "librelp cannot set keepalive time - ignored",
RELP_RET_WRN_NO_KEEPALIVE);
}
# if defined(TCP_KEEPCNT)
if(pSrv->iKeepAliveIntvl > 0) {
optval = pSrv->iKeepAliveIntvl;
optlen = sizeof(optval);
ret = setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &optval, optlen);
} else {
ret = 0;
}
# else
ret = -1;
# endif
if(ret < 0) {
callOnErr(pThis, "librelp cannot set keepalive intvl - ignored",
RELP_RET_WRN_NO_KEEPALIVE);
}
// pThis->pEngine->dbgprint("KEEPALIVE enabled for socket %d\n", sock);
done:
return;
}
/* a portable way to put the current thread asleep. Note that
* using the sleep() API family may result in the whole process
* to be put asleep on some platforms.
*/
static void
doSleep(int iSeconds, int iuSeconds)
{
struct timeval tvSelectTimeout;
tvSelectTimeout.tv_sec = iSeconds;
tvSelectTimeout.tv_usec = iuSeconds; /* micro seconds */
select(0, NULL, NULL, NULL, &tvSelectTimeout);
}
/* accept an incoming connection request, sock provides the socket on which we can
* accept the new session.
* rgerhards, 2008-03-17
*/
relpRetVal
relpTcpAcceptConnReq(relpTcp_t **ppThis, int sock, relpSrv_t *pSrv)
{
relpTcp_t *pThis = NULL;
int sockflags;
struct sockaddr_storage addr;
socklen_t addrlen = sizeof(addr);
int iNewSock = -1;
relpEngine_t *pEngine = pSrv->pEngine;
ENTER_RELPFUNC;
assert(ppThis != NULL);
iNewSock = accept(sock, (struct sockaddr*) &addr, &addrlen);
int errnosave = errno;
if(iNewSock < 0) {
pSrv->pEngine->dbgprint("error during accept, sleeping 20ms: %s\n",
strerror(errnosave));
doSleep(0, 20000);
pSrv->pEngine->dbgprint("END SLEEP\n");
ABORT_FINALIZE(RELP_RET_ACCEPT_ERR);
}
/* construct our object so that we can use it... */
CHKRet(relpTcpConstruct(&pThis, pEngine, RELP_SRV_CONN, pSrv));
if(pSrv->bKeepAlive)
EnableKeepAlive(pThis, pSrv, iNewSock);
/* TODO: obtain hostname, normalize (callback?), save it */
CHKRet(relpTcpSetRemHost(pThis, (struct sockaddr*) &addr));
pThis->pEngine->dbgprint("remote host is '%s', ip '%s'\n", pThis->pRemHostName, pThis->pRemHostIP);
/* set the new socket to non-blocking IO */
if((sockflags = fcntl(iNewSock, F_GETFL)) != -1) {
sockflags |= O_NONBLOCK;
/* SETFL could fail too, so get it caught by the subsequent
* error check.
*/
sockflags = fcntl(iNewSock, F_SETFL, sockflags);
}
if(sockflags == -1) {
pThis->pEngine->dbgprint("error %d setting fcntl(O_NONBLOCK) on relp socket %d", errno, iNewSock);
ABORT_FINALIZE(RELP_RET_IO_ERR);
}
pThis->sock = iNewSock;
#ifdef ENABLE_TLS
if(pSrv->pTcp->bEnableTLS) {
pThis->bEnableTLS = 1;
pThis->pSrv = pSrv;
CHKRet(relpTcpSetPermittedPeers(pThis, &(pSrv->permittedPeers)));
CHKRet(relpTcpAcceptConnReqInitTLS(pThis, pSrv));
}
#endif /* #ifdef ENABLE_TLS */
*ppThis = pThis;
finalize_it:
if(iRet != RELP_RET_OK) {
if(pThis != NULL)
relpTcpDestruct(&pThis);
/* the close may be redundant, but that doesn't hurt... */
if(iNewSock >= 0)
close(iNewSock);
}
LEAVE_RELPFUNC;
}
#ifdef ENABLE_TLS
#ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION
/* Convert a fingerprint to printable data. The function must be provided a
* sufficiently large buffer. 512 bytes shall always do.
*/
static void
GenFingerprintStr(char *pFingerprint, int sizeFingerprint, char *fpBuf)
{
int iSrc, iDst;
fpBuf[0] = 'S', fpBuf[1] = 'H', fpBuf[2] = 'A'; fpBuf[3] = '1';
// TODO: length check fo fpBuf (but far from being urgent...)
for(iSrc = 0, iDst = 4 ; iSrc < sizeFingerprint ; ++iSrc, iDst += 3) {
sprintf(fpBuf+iDst, ":%2.2X", (unsigned char) pFingerprint[iSrc]);
}
}
/* Check the peer's ID in fingerprint auth mode. */
static int
relpTcpChkPeerFingerprint(relpTcp_t *pThis, gnutls_x509_crt_t cert)
{
int r = 0;
int i;
char fingerprint[20];
char fpPrintable[512];
size_t size;
int8_t found;
/* obtain the SHA1 fingerprint */
size = sizeof(fingerprint);
r = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, fingerprint, &size);
if(chkGnutlsCode(pThis, "Failed to obtain fingerprint from certificate", RELP_RET_ERR_TLS, r)) {
r = GNUTLS_E_CERTIFICATE_ERROR; goto done;
}
GenFingerprintStr(fingerprint, (int) size, fpPrintable);
pThis->pEngine->dbgprint("DDDD: peer's certificate SHA1 fingerprint: %s\n", fpPrintable);
/* now search through the permitted peers to see if we can find a permitted one */
found = 0;
pThis->pEngine->dbgprint("DDDD: n peers %d\n", pThis->permittedPeers.nmemb);
for(i = 0 ; i < pThis->permittedPeers.nmemb ; ++i) {
pThis->pEngine->dbgprint("DDDD: checking peer '%s','%s'\n", fpPrintable, pThis->permittedPeers.peer[i].name);
if(!strcmp(fpPrintable, pThis->permittedPeers.peer[i].name)) {
found = 1;
break;
}
}
if(!found) {
r = GNUTLS_E_CERTIFICATE_ERROR; goto done;
}
done:
if(r != 0) {
callOnAuthErr(pThis, fpPrintable, "non-permited fingerprint", RELP_RET_AUTH_ERR_FP);
}
return r;
}
#endif /* #ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION */
/* add a wildcard entry to this permitted peer. Entries are always
* added at the tail of the list. pszStr and lenStr identify the wildcard
* entry to be added. Note that the string is NOT \0 terminated, so
* we must rely on lenStr for when it is finished.
* rgerhards, 2008-05-27
*/
static relpRetVal
AddPermittedPeerWildcard(tcpPermittedPeerEntry_t *pEtry, char* pszStr, int lenStr)
{
tcpPermittedPeerWildcardComp_t *pNew = NULL;
int iSrc;
int iDst;
ENTER_RELPFUNC;
if((pNew = calloc(1, sizeof(tcpPermittedPeerWildcardComp_t))) == NULL) {
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
if(lenStr == 0) {
pNew->wildcardType = tcpPEER_WILDCARD_EMPTY_COMPONENT;
FINALIZE;
} else {
/* alloc memory for the domain component. We may waste a byte or
* two, but that's ok.
*/
if((pNew->pszDomainPart = malloc(lenStr +1 )) == NULL) {
ABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);
}
}
if(pszStr[0] == '*') {
pNew->wildcardType = tcpPEER_WILDCARD_AT_START;
iSrc = 1; /* skip '*' */
} else {
iSrc = 0;
}
for(iDst = 0 ; iSrc < lenStr && pszStr[iSrc] != '*' ; ++iSrc, ++iDst) {
pNew->pszDomainPart[iDst] = pszStr[iSrc];
}
if(iSrc < lenStr) {
if(iSrc + 1 == lenStr && pszStr[iSrc] == '*') {
if(pNew->wildcardType == tcpPEER_WILDCARD_AT_START) {
ABORT_FINALIZE(RELP_RET_INVLD_WILDCARD);
} else {
pNew->wildcardType = tcpPEER_WILDCARD_AT_END;
}
} else {
/* we have an invalid wildcard, something follows the asterisk! */
ABORT_FINALIZE(RELP_RET_INVLD_WILDCARD);
}
}
if(lenStr == 1 && pNew->wildcardType == tcpPEER_WILDCARD_AT_START) {
pNew->wildcardType = tcpPEER_WILDCARD_MATCH_ALL;
}
/* if we reach this point, we had a valid wildcard. We now need to
* properly terminate the domain component string.
*/
pNew->pszDomainPart[iDst] = '\0';
pNew->lenDomainPart = strlen((char*)pNew->pszDomainPart);
finalize_it:
if(iRet != RELP_RET_OK) {
if(pNew != NULL) {
if(pNew->pszDomainPart != NULL)
free(pNew->pszDomainPart);
free(pNew);
}
} else {
/* add the element to linked list */
if(pEtry->wildcardRoot == NULL) {
pEtry->wildcardRoot = pNew;
pEtry->wildcardLast = pNew;
} else {
pEtry->wildcardLast->pNext = pNew;
}
pEtry->wildcardLast = pNew;
}
LEAVE_RELPFUNC;
}
/* Compile a wildcard - must not yet be compiled */
static relpRetVal
relpTcpPermittedPeerWildcardCompile(tcpPermittedPeerEntry_t *pEtry)
{
char *pC;
char *pStart;
ENTER_RELPFUNC;
/* first check if we have a wildcard */
for(pC = pEtry->name ; *pC != '\0' && *pC != '*' ; ++pC)
/*EMPTY, just skip*/;
if(*pC == '\0') { /* no wildcard found, we are done */
FINALIZE;
}
/* if we reach this point, the string contains wildcards. So let's
* compile the structure. To do so, we must parse from dot to dot
* and create a wildcard entry for each domain component we find.
* We must also flag problems if we have an asterisk in the middle
* of the text (it is supported at the start or end only).
*/
pC = pEtry->name;
while(*pC) {
pStart = pC;
/* find end of domain component */
for( ; *pC != '\0' && *pC != '.' ; ++pC)
/*EMPTY, just skip*/;
CHKRet(AddPermittedPeerWildcard(pEtry, pStart, pC - pStart));
/* now check if we have an empty component at end of string */
if(*pC == '.' && *(pC + 1) == '\0') {
/* pStart is a dummy, it is not used if length is 0 */
CHKRet(AddPermittedPeerWildcard(pEtry, pStart, 0));
}
if(*pC != '\0')
++pC;
}
finalize_it:
LEAVE_RELPFUNC;
}
#ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION
/* check a peer against a wildcard entry. This is a more lengthy
* operation.
*/
static void
relpTcpChkOnePeerWildcard(tcpPermittedPeerWildcardComp_t *pRoot, char *peername, int *pbFoundPositiveMatch)
{
tcpPermittedPeerWildcardComp_t *pWildcard;
char *pC;
char *pStart; /* start of current domain component */
int iWildcard, iName; /* work indexes for backward comparisons */
*pbFoundPositiveMatch = 0;
pWildcard = pRoot;
pC = peername;
while(*pC != '\0') {
if(pWildcard == NULL) {
/* we have more domain components than we have wildcards --> no match */
goto done;
}
pStart = pC;