-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathdtls_udp_chargen.c
1222 lines (1077 loc) · 31.5 KB
/
dtls_udp_chargen.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
/*
* Copyright (C) 2009 - 2012 Robin Seggelmann, [email protected],
* Michael Tuexen, [email protected]
* 2019 Felix Weinrank, [email protected]
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifdef WIN32
#include <winsock2.h>
#include <Ws2tcpip.h>
#define in_port_t u_short
#define ssize_t int
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#endif
#include <signal.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#define BUFFER_SIZE (1<<16)
#define MAX_STACK (1<<16)
#define COOKIE_SECRET_LENGTH 16
int verbose = 0;
int veryverbose = 0;
int length = 100;
int done = 0;
unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
int cookie_initialized=0;
char Usage[] =
"Usage: dtls_udp_chargen [options] [address]\n"
"Options:\n"
" -l message length (Default: 100 Bytes)\n"
" -L local address\n"
" -p port (Default: 23232)\n"
" -t time to send (Default: 10 sec)\n"
" -v verbose\n"
" -V very verbose\n";
#if WIN32
static HANDLE* mutex_buf = NULL;
#else
static pthread_mutex_t* mutex_buf = NULL;
#endif
static void locking_function(int mode, int n, const char *file, int line) {
if (mode & CRYPTO_LOCK)
#ifdef WIN32
WaitForSingleObject(mutex_buf[n], INFINITE);
else
ReleaseMutex(mutex_buf[n]);
#else
pthread_mutex_lock(&mutex_buf[n]);
else
pthread_mutex_unlock(&mutex_buf[n]);
#endif
}
static unsigned long id_function(void) {
#ifdef WIN32
return (unsigned long) GetCurrentThreadId();
#else
return (unsigned long) pthread_self();
#endif
}
int THREAD_setup() {
int i;
#ifdef WIN32
mutex_buf = (HANDLE*) malloc(CRYPTO_num_locks() * sizeof(HANDLE));
#else
mutex_buf = (pthread_mutex_t*) malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
#endif
if (!mutex_buf)
return 0;
for (i = 0; i < CRYPTO_num_locks(); i++)
#ifdef WIN32
mutex_buf[i] = CreateMutex(NULL, FALSE, NULL);
#else
pthread_mutex_init(&mutex_buf[i], NULL);
#endif
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int THREAD_cleanup() {
int i;
if (!mutex_buf)
return 0;
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks(); i++)
#ifdef WIN32
CloseHandle(mutex_buf[i]);
#else
pthread_mutex_destroy(&mutex_buf[i]);
#endif
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
int handle_socket_error() {
switch (errno) {
case EINTR:
/* Interrupted system call.
* Just ignore.
*/
printf("Interrupted system call!\n");
return 1;
case EBADF:
/* Invalid socket.
* Must close connection.
*/
printf("Invalid socket!\n");
return 0;
break;
#ifdef EHOSTDOWN
case EHOSTDOWN:
/* Host is down.
* Just ignore, might be an attacker
* sending fake ICMP messages.
*/
printf("Host is down!\n");
return 1;
#endif
#ifdef ECONNRESET
case ECONNRESET:
/* Connection reset by peer.
* Just ignore, might be an attacker
* sending fake ICMP messages.
*/
printf("Connection reset by peer!\n");
return 1;
break;
#endif
case ENOMEM:
/* Out of memory.
* Must close connection.
*/
printf("Out of memory!\n");
return 0;
break;
case EACCES:
/* Permission denied.
* Just ignore, we might be blocked
* by some firewall policy. Try again
* and hope for the best.
*/
printf("Permission denied!\n");
return 1;
break;
default:
/* Something unexpected happened */
printf("Unexpected error! (errno = %d)\n", errno);
return 0;
break;
}
return 0;
}
void stop_sender(int sig) {
done = 1;
}
void stack_sort(int* stack, int* stackindex) {
int pointer, save, counter = *stackindex - 1;
while (counter--) {
pointer = 0;
while (pointer++ < *stackindex) {
if (stack[pointer] < stack[pointer + 1]) {
save = stack[pointer];
stack[pointer] = stack[pointer + 1];
stack[pointer + 1] = save;
}
}
}
}
void stack_update(int* stack, int* stackindex, int* maxrecvnum) {
while (stack[*stackindex] == *maxrecvnum + 1) {
(*maxrecvnum)++;
(*stackindex)--;
}
}
void stack_insert(int* stack, int* stackindex, int value) {
if (*stackindex == MAX_STACK) {
printf("stack exceeded!\n");
return;
}
(*stackindex)++;
stack[*stackindex] = value;
stack_sort(stack, stackindex);
}
int lost_messages(int* stack, int stackindex, int maxrecvnum) {
int ret = 0;
if (stackindex == 0)
return 0;
if (stackindex == 1)
return stack[stackindex] - maxrecvnum;
ret = stack[stackindex] - maxrecvnum - 1;
while (--stackindex)
ret += stack[stackindex] - stack[stackindex + 1] - 1;
return ret;
}
int generate_cookie(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)
{
unsigned char *buffer, result[EVP_MAX_MD_SIZE];
unsigned int length = 0, resultlength;
union {
struct sockaddr_storage ss;
struct sockaddr_in6 s6;
struct sockaddr_in s4;
} peer;
/* Initialize a random secret */
if (!cookie_initialized)
{
if (!RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH))
{
printf("error setting random cookie secret\n");
return 0;
}
cookie_initialized = 1;
}
/* Read peer information */
(void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
/* Create buffer with peer's address and port */
length = 0;
switch (peer.ss.ss_family) {
case AF_INET:
length += sizeof(struct in_addr);
break;
case AF_INET6:
length += sizeof(struct in6_addr);
break;
default:
OPENSSL_assert(0);
break;
}
length += sizeof(in_port_t);
buffer = (unsigned char*) OPENSSL_malloc(length);
if (buffer == NULL)
{
printf("out of memory\n");
return 0;
}
switch (peer.ss.ss_family) {
case AF_INET:
memcpy(buffer,
&peer.s4.sin_port,
sizeof(in_port_t));
memcpy(buffer + sizeof(peer.s4.sin_port),
&peer.s4.sin_addr,
sizeof(struct in_addr));
break;
case AF_INET6:
memcpy(buffer,
&peer.s6.sin6_port,
sizeof(in_port_t));
memcpy(buffer + sizeof(in_port_t),
&peer.s6.sin6_addr,
sizeof(struct in6_addr));
break;
default:
OPENSSL_assert(0);
break;
}
/* Calculate HMAC of buffer using the secret */
HMAC(EVP_sha1(), (const void*) cookie_secret, COOKIE_SECRET_LENGTH,
(const unsigned char*) buffer, length, result, &resultlength);
OPENSSL_free(buffer);
memcpy(cookie, result, resultlength);
*cookie_len = resultlength;
return 1;
}
int verify_cookie(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len)
{
unsigned char *buffer, result[EVP_MAX_MD_SIZE];
unsigned int length = 0, resultlength;
union {
struct sockaddr_storage ss;
struct sockaddr_in6 s6;
struct sockaddr_in s4;
} peer;
/* If secret isn't initialized yet, the cookie can't be valid */
if (!cookie_initialized)
return 0;
/* Read peer information */
(void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
/* Create buffer with peer's address and port */
length = 0;
switch (peer.ss.ss_family) {
case AF_INET:
length += sizeof(struct in_addr);
break;
case AF_INET6:
length += sizeof(struct in6_addr);
break;
default:
OPENSSL_assert(0);
break;
}
length += sizeof(in_port_t);
buffer = (unsigned char*) OPENSSL_malloc(length);
if (buffer == NULL)
{
printf("out of memory\n");
return 0;
}
switch (peer.ss.ss_family) {
case AF_INET:
memcpy(buffer,
&peer.s4.sin_port,
sizeof(in_port_t));
memcpy(buffer + sizeof(in_port_t),
&peer.s4.sin_addr,
sizeof(struct in_addr));
break;
case AF_INET6:
memcpy(buffer,
&peer.s6.sin6_port,
sizeof(in_port_t));
memcpy(buffer + sizeof(in_port_t),
&peer.s6.sin6_addr,
sizeof(struct in6_addr));
break;
default:
OPENSSL_assert(0);
break;
}
/* Calculate HMAC of buffer using the secret */
HMAC(EVP_sha1(), (const void*) cookie_secret, COOKIE_SECRET_LENGTH,
(const unsigned char*) buffer, length, result, &resultlength);
OPENSSL_free(buffer);
if (cookie_len == resultlength && memcmp(result, cookie, resultlength) == 0)
return 1;
return 0;
}
struct pass_info {
union {
struct sockaddr_storage ss;
struct sockaddr_in6 s6;
struct sockaddr_in s4;
} server_addr, client_addr;
SSL *ssl;
};
int dtls_verify_callback (int ok, X509_STORE_CTX *ctx) {
/* This function should ask the user
* if he trusts the received certificate.
* Here we always trust.
*/
return 1;
}
#ifdef WIN32
DWORD WINAPI connection_handle(LPVOID *info) {
#else
void* connection_handle(void *info) {
#endif
ssize_t len;
char buf[BUFFER_SIZE];
char addrbuf[INET6_ADDRSTRLEN];
struct pass_info *pinfo = (struct pass_info*) info;
SSL *ssl = pinfo->ssl;
int fd, reading = 0, rcvnum, count = 0, rcvcount, activesocks;
fd_set readsocks;
struct timeval timeout;
int ret, maxrecvnum = -1, stackindex = 0;
int recvstack[MAX_STACK];
const int on = 1, off = 0;
int num_timeouts = 0, max_timeouts = 5;
#ifndef WIN32
pthread_detach(pthread_self());
#endif
OPENSSL_assert(pinfo->client_addr.ss.ss_family == pinfo->server_addr.ss.ss_family);
fd = socket(pinfo->client_addr.ss.ss_family, SOCK_DGRAM, 0);
if (fd < 0) {
perror("socket");
goto cleanup;
}
#ifdef WIN32
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, (socklen_t) sizeof(on));
#else
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*) &on, (socklen_t) sizeof(on));
#if defined(SO_REUSEPORT) && !defined(__linux__)
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (const void*) &on, (socklen_t) sizeof(on));
#endif
#endif
switch (pinfo->client_addr.ss.ss_family) {
case AF_INET:
if (bind(fd, (const struct sockaddr *) &pinfo->server_addr, sizeof(struct sockaddr_in))) {
perror("bind");
goto cleanup;
}
if (connect(fd, (struct sockaddr *) &pinfo->client_addr, sizeof(struct sockaddr_in))) {
perror("connect");
goto cleanup;
}
break;
case AF_INET6:
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&off, sizeof(off));
if (bind(fd, (const struct sockaddr *) &pinfo->server_addr, sizeof(struct sockaddr_in6))) {
perror("bind");
goto cleanup;
}
if (connect(fd, (struct sockaddr *) &pinfo->client_addr, sizeof(struct sockaddr_in6))) {
perror("connect");
goto cleanup;
}
break;
default:
OPENSSL_assert(0);
break;
}
/* Set new fd and set BIO to connected */
BIO_set_fd(SSL_get_rbio(ssl), fd, BIO_NOCLOSE);
BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_SET_CONNECTED, 0, &pinfo->client_addr.ss);
/* Finish handshake */
do { ret = SSL_accept(ssl); }
while (ret == 0);
if (ret < 0) {
perror("SSL_accept");
printf("%s\n", ERR_error_string(ERR_get_error(), buf));
goto cleanup;
}
/* Set and activate timeouts */
timeout.tv_sec = 5;
timeout.tv_usec = 0;
BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
if (verbose) {
if (pinfo->client_addr.ss.ss_family == AF_INET) {
printf ("\nThread %lx: accepted connection from %s:%d\n",
(long) pthread_self(),
inet_ntop(AF_INET, &pinfo->client_addr.s4.sin_addr, addrbuf, INET6_ADDRSTRLEN),
ntohs(pinfo->client_addr.s4.sin_port));
} else {
printf ("\nThread %lx: accepted connection from %s:%d\n",
(long) pthread_self(),
inet_ntop(AF_INET6, &pinfo->client_addr.s6.sin6_addr, addrbuf, INET6_ADDRSTRLEN),
ntohs(pinfo->client_addr.s6.sin6_port));
}
}
if (veryverbose && SSL_get_peer_certificate(ssl)) {
printf ("------------------------------------------------------------\n");
X509_NAME_print_ex_fp(stdout, X509_get_subject_name(SSL_get_peer_certificate(ssl)),
1, XN_FLAG_MULTILINE);
printf("\n\n Cipher: %s", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl)));
printf ("\n------------------------------------------------------------\n\n");
}
count = 0;
rcvcount = 0;
while (!(SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) && num_timeouts < max_timeouts) {
timeout.tv_sec = 0;
timeout.tv_usec = 1;
FD_ZERO(&readsocks);
FD_SET(fd,&readsocks);
while ((activesocks = select(FD_SETSIZE, &readsocks, NULL, NULL, &timeout)) < 0) {
if (errno != EINTR) {
perror("select");
exit(EXIT_FAILURE);
}
}
count = htonl(count);
memcpy(buf, &count, sizeof(int));
count = ntohl(count);
len = SSL_write(ssl, buf, length);
switch (SSL_get_error(ssl, len)) {
case SSL_ERROR_NONE:
if (verbose) {
printf("Thread %lx: wrote num %d with %d bytes\n", (long) pthread_self(),
count, (int) len);
}
count++;
break;
case SSL_ERROR_WANT_WRITE:
/* Just try again later */
break;
case SSL_ERROR_WANT_READ:
/* continue with reading */
break;
case SSL_ERROR_SYSCALL:
printf("Socket write error: ");
if (!handle_socket_error()) goto cleanup;
//reading = 0;
break;
case SSL_ERROR_SSL:
printf("SSL write error: ");
printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len));
goto cleanup;
break;
default:
printf("Unexpected error while writing!\n");
goto cleanup;
break;
}
if (activesocks > 0) {
if (FD_ISSET(fd,&readsocks)) {
reading = 1;
while (reading) {
len = SSL_read(ssl, buf, sizeof(buf));
switch (SSL_get_error(ssl, len)) {
case SSL_ERROR_NONE:
memcpy(&rcvnum, buf, sizeof(int));
rcvnum = ntohl(rcvnum);
if (verbose) {
printf("Thread %lx: read num %d with %d bytes\n", (long) pthread_self(), rcvnum, (int) len);
}
if (rcvnum == maxrecvnum + 1)
maxrecvnum++;
else {
stack_insert(recvstack, &stackindex, rcvnum);
stack_update(recvstack, &stackindex, &maxrecvnum);
}
rcvcount++;
reading = 0;
break;
case SSL_ERROR_WANT_READ:
/* Handle socket timeouts */
if (BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)) {
num_timeouts++;
reading = 0;
}
/* Just try again */
break;
case SSL_ERROR_ZERO_RETURN:
reading = 0;
break;
case SSL_ERROR_SYSCALL:
printf("Socket read error: ");
if (!handle_socket_error()) goto cleanup;
reading = 0;
break;
case SSL_ERROR_SSL:
printf("SSL read error: ");
printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len));
goto cleanup;
break;
default:
printf("Unexpected error while reading!\n");
goto cleanup;
break;
}
}
}
}
}
SSL_shutdown(ssl);
if (pinfo->client_addr.ss.ss_family == AF_INET) {
printf("\nThread %lx: Statistics for %s:\n=========================================================\n",
(long) pthread_self(), inet_ntop(AF_INET, &pinfo->client_addr.s4.sin_addr, addrbuf, INET6_ADDRSTRLEN));
} else {
printf("\nThread %lx: Statistics for %s:\n=========================================================\n",
(long) pthread_self(), inet_ntop(AF_INET6, &pinfo->client_addr.s6.sin6_addr, addrbuf, INET6_ADDRSTRLEN));
}
printf("Thread %lx: Sent messages: %6d\n", (long) pthread_self(), count);
printf("Thread %lx: Received messages: %6d\n\n", (long) pthread_self(), rcvcount);
printf("Thread %lx: Messages lost: %6d\n", (long) pthread_self(), lost_messages(recvstack, stackindex, maxrecvnum));
cleanup:
#ifdef WIN32
closesocket(fd);
#else
close(fd);
#endif
free(info);
SSL_free(ssl);
if (verbose)
printf("Thread %lx: done, connection closed.\n", (long) pthread_self());
#if WIN32
ExitThread(0);
#else
pthread_exit( (void *) NULL );
#endif
}
void start_server(int port, char *local_address) {
int fd, pid;
union {
struct sockaddr_storage ss;
struct sockaddr_in s4;
struct sockaddr_in6 s6;
} server_addr, client_addr;
#if WIN32
WSADATA wsaData;
DWORD tid;
#else
pthread_t tid;
#endif
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
struct timeval timeout;
struct pass_info *info;
const int on = 1, off = 0;
memset(&server_addr, 0, sizeof(struct sockaddr_storage));
if (strlen(local_address) == 0) {
server_addr.s6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
server_addr.s6.sin6_len = sizeof(struct sockaddr_in6);
#endif
server_addr.s6.sin6_addr = in6addr_any;
server_addr.s6.sin6_port = htons(port);
} else {
if (inet_pton(AF_INET, local_address, &server_addr.s4.sin_addr) == 1) {
server_addr.s4.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
server_addr.s4.sin_len = sizeof(struct sockaddr_in);
#endif
server_addr.s4.sin_port = htons(port);
} else if (inet_pton(AF_INET6, local_address, &server_addr.s6.sin6_addr) == 1) {
server_addr.s6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
server_addr.s6.sin6_len = sizeof(struct sockaddr_in6);
#endif
server_addr.s6.sin6_port = htons(port);
} else {
return;
}
}
THREAD_setup();
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(DTLS_server_method());
/* We accept all ciphers, including NULL.
* Not recommended beyond testing and debugging
*/
//SSL_CTX_set_cipher_list(ctx, "ALL:NULL:eNULL:aNULL");
pid = getpid();
if (!SSL_CTX_set_session_id_context(ctx, (void*)&pid, sizeof pid)) {
perror("SSL_CTX_set_session_id_context");
exit(EXIT_FAILURE);
}
if (!SSL_CTX_use_certificate_file(ctx, "certs/server-cert.pem", SSL_FILETYPE_PEM)) {
printf("\n[%d] ERROR: no certificate found!", __LINE__);
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
if (!SSL_CTX_use_PrivateKey_file(ctx, "certs/server-key.pem", SSL_FILETYPE_PEM))
printf("\n[%d] ERROR: no private key found!", __LINE__);
if (!SSL_CTX_check_private_key (ctx))
printf("\n[%d] ERROR: invalid private key!", __LINE__);
/* Client has to authenticate */
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, dtls_verify_callback);
SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);
SSL_CTX_set_cookie_verify_cb(ctx, &verify_cookie);
#ifdef WIN32
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
fd = socket(server_addr.ss.ss_family, SOCK_DGRAM, 0);
if (fd < 0) {
perror("socket");
exit(-1);
}
#ifdef WIN32
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, (socklen_t) sizeof(on));
#else
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*) &on, (socklen_t) sizeof(on));
#if defined(SO_REUSEPORT) && !defined(__linux__)
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (const void*) &on, (socklen_t) sizeof(on));
#endif
#endif
if (server_addr.ss.ss_family == AF_INET) {
if (bind(fd, (const struct sockaddr *) &server_addr, sizeof(struct sockaddr_in))) {
perror("bind");
exit(EXIT_FAILURE);
}
} else {
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&off, sizeof(off));
if (bind(fd, (const struct sockaddr *) &server_addr, sizeof(struct sockaddr_in6))) {
perror("bind");
exit(EXIT_FAILURE);
}
}
while (1) {
memset(&client_addr, 0, sizeof(struct sockaddr_storage));
/* Create BIO */
bio = BIO_new_dgram(fd, BIO_NOCLOSE);
/* Set and activate timeouts */
timeout.tv_sec = 5;
timeout.tv_usec = 0;
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
ssl = SSL_new(ctx);
SSL_set_bio(ssl, bio, bio);
SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
while (DTLSv1_listen(ssl, (BIO_ADDR *) &client_addr) <= 0);
info = (struct pass_info*) malloc (sizeof(struct pass_info));
memcpy(&info->server_addr, &server_addr, sizeof(struct sockaddr_storage));
memcpy(&info->client_addr, &client_addr, sizeof(struct sockaddr_storage));
info->ssl = ssl;
#ifdef WIN32
if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) connection_handle, info, 0, &tid) == NULL) {
exit(-1);
}
#else
if (pthread_create( &tid, NULL, connection_handle, info) != 0) {
perror("pthread_create");
exit(-1);
}
#endif
}
THREAD_cleanup();
#ifdef WIN32
WSACleanup();
#endif
}
void start_client(char *remote_address, char *local_address, int port, int timetosend) {
int fd, rcvnum, count = 0, rcvcount, retval;
union {
struct sockaddr_storage ss;
struct sockaddr_in s4;
struct sockaddr_in6 s6;
} remote_addr, local_addr;
char buf[BUFFER_SIZE];
char addrbuf[INET6_ADDRSTRLEN];
socklen_t len;
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
int reading = 0, activesocks, renegs = 0;
fd_set readsocks;
struct timeval timeout;
int maxrecvnum = -1, stackindex = 0;
int recvstack[MAX_STACK];
#if WIN32
WSADATA wsaData;
#endif
memset((void *) &remote_addr, 0, sizeof(struct sockaddr_storage));
memset((void *) &local_addr, 0, sizeof(struct sockaddr_storage));
if (inet_pton(AF_INET, remote_address, &remote_addr.s4.sin_addr) == 1) {
remote_addr.s4.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
remote_addr.s4.sin_len = sizeof(struct sockaddr_in);
#endif
remote_addr.s4.sin_port = htons(port);
} else if (inet_pton(AF_INET6, remote_address, &remote_addr.s6.sin6_addr) == 1) {
remote_addr.s6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
remote_addr.s6.sin6_len = sizeof(struct sockaddr_in6);
#endif
remote_addr.s6.sin6_port = htons(port);
} else {
return;
}
#ifdef WIN32
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
fd = socket(remote_addr.ss.ss_family, SOCK_DGRAM, 0);
if (fd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
if (strlen(local_address) > 0) {
if (inet_pton(AF_INET, local_address, &local_addr.s4.sin_addr) == 1) {
local_addr.s4.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
local_addr.s4.sin_len = sizeof(struct sockaddr_in);
#endif
local_addr.s4.sin_port = htons(0);
} else if (inet_pton(AF_INET6, local_address, &local_addr.s6.sin6_addr) == 1) {
local_addr.s6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
local_addr.s6.sin6_len = sizeof(struct sockaddr_in6);
#endif
local_addr.s6.sin6_port = htons(0);
} else {
return;
}
OPENSSL_assert(remote_addr.ss.ss_family == local_addr.ss.ss_family);
if (local_addr.ss.ss_family == AF_INET) {
if (bind(fd, (const struct sockaddr *) &local_addr, sizeof(struct sockaddr_in))) {
perror("bind");
exit(EXIT_FAILURE);
}
} else {
if (bind(fd, (const struct sockaddr *) &local_addr, sizeof(struct sockaddr_in6))) {
perror("bind");
exit(EXIT_FAILURE);
}
}
}
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(DTLS_client_method());
//SSL_CTX_set_cipher_list(ctx, "eNULL:!MD5");
if (!SSL_CTX_use_certificate_file(ctx, "certs/client-cert.pem", SSL_FILETYPE_PEM)) {
printf("\n[%d] ERROR: no certificate found!", __LINE__);
exit(EXIT_FAILURE);
}
if (!SSL_CTX_use_PrivateKey_file(ctx, "certs/client-key.pem", SSL_FILETYPE_PEM)) {
printf("\n[%d] ERROR: no private key found!", __LINE__);
exit(EXIT_FAILURE);
}
if (!SSL_CTX_check_private_key (ctx)) {
printf("\n[%d] ERROR: invalid private key!", __LINE__);
exit(EXIT_FAILURE);
}
SSL_CTX_set_verify_depth (ctx, 2);
SSL_CTX_set_read_ahead(ctx, 1);
ssl = SSL_new(ctx);
/* Create BIO, connect and set to already connected */
bio = BIO_new_dgram(fd, BIO_CLOSE);
if (remote_addr.ss.ss_family == AF_INET) {
if (connect(fd, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr_in))) {
perror("connect");
exit(EXIT_FAILURE);
}
} else {
if (connect(fd, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr_in6))) {
perror("connect");
exit(EXIT_FAILURE);
}
}
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &remote_addr.ss);
SSL_set_bio(ssl, bio, bio);
retval = SSL_connect(ssl);
if (retval <= 0) {
switch (SSL_get_error(ssl, retval)) {
case SSL_ERROR_ZERO_RETURN:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_ZERO_RETURN\n");
break;
case SSL_ERROR_WANT_READ:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_READ\n");
break;
case SSL_ERROR_WANT_WRITE:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_WRITE\n");
break;
case SSL_ERROR_WANT_CONNECT:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_CONNECT\n");
break;
case SSL_ERROR_WANT_ACCEPT:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_ACCEPT\n");
break;
case SSL_ERROR_WANT_X509_LOOKUP:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_X509_LOOKUP\n");
break;
case SSL_ERROR_SYSCALL:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_SYSCALL\n");
break;
case SSL_ERROR_SSL:
fprintf(stderr, "SSL_connect failed with SSL_ERROR_SSL\n");
break;
default:
fprintf(stderr, "SSL_connect failed with unknown error\n");
break;
}
exit(EXIT_FAILURE);
}
/* Set and activate timeouts */
timeout.tv_sec = 3;
timeout.tv_usec = 0;
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
if (verbose) {
if (remote_addr.ss.ss_family == AF_INET) {
printf ("\nConnected to %s\n",
inet_ntop(AF_INET, &remote_addr.s4.sin_addr, addrbuf, INET6_ADDRSTRLEN));
} else {
printf ("\nConnected to %s\n",
inet_ntop(AF_INET6, &remote_addr.s6.sin6_addr, addrbuf, INET6_ADDRSTRLEN));
}
}
if (veryverbose && SSL_get_peer_certificate(ssl)) {
printf ("------------------------------------------------------------\n");
X509_NAME_print_ex_fp(stdout, X509_get_subject_name(SSL_get_peer_certificate(ssl)),
1, XN_FLAG_MULTILINE);
printf("\n\n Cipher: %s", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl)));
printf ("\n------------------------------------------------------------\n\n");
}