source: UsbWattMeter/trunk/wolfssl-3.7.0/wolfssl/test.h@ 164

Last change on this file since 164 was 164, checked in by coas-nagasima, 6 years ago

TOPPERS/ECNLサンプルアプリ「USB充電器電力計」を追加

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
  • Property svn:mime-type set to text/x-chdr
File size: 54.7 KB
Line 
1/* test.h */
2
3#ifndef wolfSSL_TEST_H
4#define wolfSSL_TEST_H
5
6#include <stdio.h>
7#include <stdlib.h>
8#include <assert.h>
9#include <ctype.h>
10#include <wolfssl/wolfcrypt/types.h>
11#include <wolfssl/wolfcrypt/error-crypt.h>
12#include <wolfssl/wolfcrypt/random.h>
13
14#ifdef ATOMIC_USER
15 #include <wolfssl/wolfcrypt/aes.h>
16 #include <wolfssl/wolfcrypt/arc4.h>
17 #include <wolfssl/wolfcrypt/hmac.h>
18#endif
19#ifdef HAVE_PK_CALLBACKS
20 #include <wolfssl/wolfcrypt/asn.h>
21 #ifdef HAVE_ECC
22 #include <wolfssl/wolfcrypt/ecc.h>
23 #endif /* HAVE_ECC */
24#endif /*HAVE_PK_CALLBACKS */
25
26#ifdef USE_WINDOWS_API
27 #include <winsock2.h>
28 #include <process.h>
29 #ifdef TEST_IPV6 /* don't require newer SDK for IPV4 */
30 #include <ws2tcpip.h>
31 #include <wspiapi.h>
32 #endif
33 #define SOCKET_T SOCKET
34 #define SNPRINTF _snprintf
35#elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
36 #include <string.h>
37 #include "rl_net.h"
38 #define SOCKET_T int
39 typedef int socklen_t ;
40 static unsigned long inet_addr(const char *cp)
41 {
42 unsigned int a[4] ; unsigned long ret ;
43 sscanf(cp, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]) ;
44 ret = ((a[3]<<24) + (a[2]<<16) + (a[1]<<8) + a[0]) ;
45 return(ret) ;
46 }
47 #if defined(HAVE_KEIL_RTX)
48 #define sleep(t) os_dly_wait(t/1000+1) ;
49 #elif defined (WOLFSSL_CMSIS_RTOS)
50 #define sleep(t) osDelay(t/1000+1) ;
51 #endif
52
53 static int wolfssl_tcp_select(int sd, int timeout)
54 { return 0 ; }
55 #define tcp_select(sd,t) wolfssl_tcp_select(sd, t) /* avoid conflicting Keil TCP tcp_select */
56#elif defined(WOLFSSL_TIRTOS)
57 #include <string.h>
58 #include <netdb.h>
59 #include <sys/types.h>
60 #include <arpa/inet.h>
61 #include <sys/socket.h>
62 #include <ti/sysbios/knl/Task.h>
63 struct hostent {
64 char *h_name; /* official name of host */
65 char **h_aliases; /* alias list */
66 int h_addrtype; /* host address type */
67 int h_length; /* length of address */
68 char **h_addr_list; /* list of addresses from name server */
69 };
70 #define SOCKET_T int
71#elif defined(WOLFSSL_VXWORKS)
72 #include <hostLib.h>
73 #include <sockLib.h>
74 #include <arpa/inet.h>
75 #include <string.h>
76 #include <selectLib.h>
77 #include <sys/types.h>
78 #include <netinet/in.h>
79 #include <fcntl.h>
80 #include <sys/time.h>
81 #include <netdb.h>
82 #include <pthread.h>
83 #define SOCKET_T int
84#else
85 #include <string.h>
86 #include <sys/types.h>
87#if 0//ndef WOLFSSL_LEANPSK
88 #include <unistd.h>
89 #include <netdb.h>
90 #include <netinet/in.h>
91 #include <netinet/tcp.h>
92 #include <arpa/inet.h>
93 #include <sys/ioctl.h>
94 #include <sys/time.h>
95 #include <sys/socket.h>
96 #include <pthread.h>
97 #include <fcntl.h>
98 #ifdef TEST_IPV6
99 #include <netdb.h>
100 #endif
101#endif
102 #define SOCKET_T int
103 #ifndef SO_NOSIGPIPE
104 #include <signal.h> /* ignore SIGPIPE */
105 #endif
106 #define SNPRINTF snprintf
107#endif /* USE_WINDOWS_API */
108
109#ifdef HAVE_CAVIUM
110 #include "cavium_sysdep.h"
111 #include "cavium_common.h"
112 #include "cavium_ioctl.h"
113#endif
114
115#ifdef _MSC_VER
116 /* disable conversion warning */
117 /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
118 #pragma warning(disable:4244 4996)
119#endif
120
121/* Buffer for benchmark tests */
122#ifndef TEST_BUFFER_SIZE
123#define TEST_BUFFER_SIZE 16384
124#endif
125
126#ifndef min
127 #define WOLFSSL_HAVE_MIN
128 static INLINE word32 min(word32 a, word32 b)
129 {
130 return a > b ? b : a;
131 }
132#endif /* WOLFSSL_HAVE_MIN */
133
134/* Socket Handling */
135#ifndef WOLFSSL_SOCKET_INVALID
136#ifdef USE_WINDOWS_API
137 #define WOLFSSL_SOCKET_INVALID INVALID_SOCKET
138#elif defined(WOLFSSL_TIRTOS)
139 #define WOLFSSL_SOCKET_INVALID -1
140#else
141 #define WOLFSSL_SOCKET_INVALID 0
142#endif
143#endif /* WOLFSSL_SOCKET_INVALID */
144
145#ifndef WOLFSSL_SOCKET_IS_INVALID
146#ifdef USE_WINDOWS_API
147 #define WOLFSSL_SOCKET_IS_INVALID(s) ((s) == WOLFSSL_SOCKET_INVALID)
148#elif defined(WOLFSSL_TIRTOS)
149 #define WOLFSSL_SOCKET_IS_INVALID(s) ((s) == WOLFSSL_SOCKET_INVALID)
150#else
151 #define WOLFSSL_SOCKET_IS_INVALID(s) ((s) < WOLFSSL_SOCKET_INVALID)
152#endif
153#endif /* WOLFSSL_SOCKET_IS_INVALID */
154
155#if defined(__MACH__) || defined(USE_WINDOWS_API)
156 #ifndef _SOCKLEN_T
157 typedef int socklen_t;
158 #endif
159#endif
160
161#ifdef WOLFSSL_LWIP
162 /* lwIP needs to be configured to use sockets API in this mode */
163 /* LWIP_SOCKET 1 in lwip/opt.h or in build */
164#pragma warning(disable : 4005)
165#include <lwip/sockets.h>
166#include <lwip/netdb.h>
167#pragma warning(default : 4005)
168 //#include <errno.h>
169#ifndef LWIP_PROVIDE_ERRNO
170#define LWIP_PROVIDE_ERRNO 1
171#endif
172#endif
173
174/* HPUX doesn't use socklent_t for third parameter to accept, unless
175 _XOPEN_SOURCE_EXTENDED is defined */
176#if !defined(__hpux__) && !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_IAR_ARM)\
177 && !defined(WOLFSSL_ROWLEY_ARM) && !defined(WOLFSSL_KEIL_TCP_NET)
178 typedef socklen_t* ACCEPT_THIRD_T;
179#else
180 #if defined _XOPEN_SOURCE_EXTENDED
181 typedef socklen_t* ACCEPT_THIRD_T;
182 #else
183 typedef int* ACCEPT_THIRD_T;
184 #endif
185#endif
186
187
188#ifdef USE_WINDOWS_API
189 #define CloseSocket(s) closesocket(s)
190 #define StartTCP() { WSADATA wsd; WSAStartup(0x0002, &wsd); }
191#elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
192 #define CloseSocket(s) closesocket(s)
193 #define StartTCP()
194#else
195 #define CloseSocket(s) close(s)
196 #define StartTCP()
197#endif
198
199
200#ifdef SINGLE_THREADED
201 typedef unsigned int THREAD_RETURN;
202 typedef void* THREAD_TYPE;
203 #define WOLFSSL_THREAD
204#else
205 #if defined(_POSIX_THREADS) && !defined(__MINGW32__)
206 typedef void* THREAD_RETURN;
207 typedef pthread_t THREAD_TYPE;
208 #define WOLFSSL_THREAD
209 #define INFINITE -1
210 #define WAIT_OBJECT_0 0L
211 #elif defined(WOLFSSL_MDK_ARM)|| defined(WOLFSSL_KEIL_TCP_NET)
212 typedef unsigned int THREAD_RETURN;
213 typedef int THREAD_TYPE;
214 #define WOLFSSL_THREAD
215 #elif defined(WOLFSSL_TIRTOS)
216 typedef void THREAD_RETURN;
217 typedef Task_Handle THREAD_TYPE;
218 #define WOLFSSL_THREAD
219 #else
220 typedef unsigned int THREAD_RETURN;
221 typedef intptr_t THREAD_TYPE;
222 #define WOLFSSL_THREAD __stdcall
223 #endif
224#endif
225
226
227#ifdef TEST_IPV6
228 typedef struct sockaddr_in6 SOCKADDR_IN_T;
229 #define AF_INET_V AF_INET6
230#else
231 typedef struct sockaddr_in SOCKADDR_IN_T;
232 #define AF_INET_V AF_INET
233#endif
234
235
236#define SERVER_DEFAULT_VERSION 3
237#define SERVER_DTLS_DEFAULT_VERSION (-2)
238#define SERVER_INVALID_VERSION (-99)
239#define CLIENT_DEFAULT_VERSION 3
240#define CLIENT_DTLS_DEFAULT_VERSION (-2)
241#define CLIENT_INVALID_VERSION (-99)
242#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
243 #define DEFAULT_MIN_DHKEY_BITS 2048
244#else
245 #define DEFAULT_MIN_DHKEY_BITS 1024
246#endif
247
248/* all certs relative to wolfSSL home directory now */
249#if defined(WOLFSSL_NO_CURRDIR) || defined(WOLFSSL_MDK_SHELL)
250#define caCert "certs/ca-cert.pem"
251#define eccCert "certs/server-ecc.pem"
252#define eccKey "certs/ecc-key.pem"
253#define svrCert "certs/server-cert.pem"
254#define svrKey "certs/server-key.pem"
255#define cliCert "certs/client-cert.pem"
256#define cliKey "certs/client-key.pem"
257#define ntruCert "certs/ntru-cert.pem"
258#define ntruKey "certs/ntru-key.raw"
259#define dhParam "certs/dh2048.pem"
260#define cliEccKey "certs/ecc-client-key.pem"
261#define cliEccCert "certs/client-ecc-cert.pem"
262#define crlPemDir "certs/crl"
263#else
264#define caCert "./certs/ca-cert.pem"
265#define eccCert "./certs/server-ecc.pem"
266#define eccKey "./certs/ecc-key.pem"
267#define svrCert "./certs/server-cert.pem"
268#define svrKey "./certs/server-key.pem"
269#define cliCert "./certs/client-cert.pem"
270#define cliKey "./certs/client-key.pem"
271#define ntruCert "./certs/ntru-cert.pem"
272#define ntruKey "./certs/ntru-key.raw"
273#define dhParam "./certs/dh2048.pem"
274#define cliEccKey "./certs/ecc-client-key.pem"
275#define cliEccCert "./certs/client-ecc-cert.pem"
276#define crlPemDir "./certs/crl"
277#endif
278
279typedef struct tcp_ready {
280 word16 ready; /* predicate */
281 word16 port;
282#if defined(_POSIX_THREADS) && !defined(__MINGW32__)
283 pthread_mutex_t mutex;
284 pthread_cond_t cond;
285#endif
286} tcp_ready;
287
288
289void InitTcpReady(tcp_ready*);
290void FreeTcpReady(tcp_ready*);
291
292typedef WOLFSSL_METHOD* (*method_provider)(void);
293typedef void (*ctx_callback)(WOLFSSL_CTX* ctx);
294typedef void (*ssl_callback)(WOLFSSL* ssl);
295
296typedef struct callback_functions {
297 method_provider method;
298 ctx_callback ctx_ready;
299 ssl_callback ssl_ready;
300 ssl_callback on_result;
301} callback_functions;
302
303typedef struct func_args {
304 int argc;
305 char** argv;
306 int return_code;
307 tcp_ready* signal;
308 callback_functions *callbacks;
309} func_args;
310
311void wait_tcp_ready(func_args*);
312
313typedef THREAD_RETURN WOLFSSL_THREAD THREAD_FUNC(void*);
314
315void start_thread(THREAD_FUNC, func_args*, THREAD_TYPE*);
316void join_thread(THREAD_TYPE);
317
318#undef INADDR_ANY
319static const char* const INADDR_ANY = "0.0.0.0";
320
321/* wolfSSL */
322#ifndef TEST_IPV6
323 static const char* const wolfSSLIP = "127.0.0.1";
324#else
325 static const char* const wolfSSLIP = "::1";
326#endif
327static const word16 wolfSSLPort = 11111;
328
329static INLINE void err_sys(const char* msg)
330{
331 printf("wolfSSL error: %s\n", msg);
332 if (msg)
333 exit(EXIT_FAILURE);
334}
335
336
337#define MY_EX_USAGE 2
338
339extern int myoptind;
340extern char* myoptarg;
341
342static INLINE int mygetopt(int argc, char** argv, const char* optstring)
343{
344 static char* next = NULL;
345
346 char c;
347 char* cp;
348
349 if (myoptind == 0)
350 next = NULL; /* we're starting new/over */
351
352 if (next == NULL || *next == '\0') {
353 if (myoptind == 0)
354 myoptind++;
355
356 if (myoptind >= argc || argv[myoptind][0] != '-' ||
357 argv[myoptind][1] == '\0') {
358 myoptarg = NULL;
359 if (myoptind < argc)
360 myoptarg = argv[myoptind];
361
362 return -1;
363 }
364
365 if (strcmp(argv[myoptind], "--") == 0) {
366 myoptind++;
367 myoptarg = NULL;
368
369 if (myoptind < argc)
370 myoptarg = argv[myoptind];
371
372 return -1;
373 }
374
375 next = argv[myoptind];
376 next++; /* skip - */
377 myoptind++;
378 }
379
380 c = *next++;
381 /* The C++ strchr can return a different value */
382 cp = (char*)strchr(optstring, c);
383
384 if (cp == NULL || c == ':')
385 return '?';
386
387 cp++;
388
389 if (*cp == ':') {
390 if (*next != '\0') {
391 myoptarg = next;
392 next = NULL;
393 }
394 else if (myoptind < argc) {
395 myoptarg = argv[myoptind];
396 myoptind++;
397 }
398 else
399 return '?';
400 }
401
402 return c;
403}
404
405
406#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
407
408static INLINE int PasswordCallBack(char* passwd, int sz, int rw, void* userdata)
409{
410 (void)rw;
411 (void)userdata;
412 strncpy(passwd, "yassl123", sz);
413 return 8;
414}
415
416#endif
417
418
419#if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS)
420
421static INLINE void ShowX509(WOLFSSL_X509* x509, const char* hdr)
422{
423 char* altName;
424 char* issuer = wolfSSL_X509_NAME_oneline(
425 wolfSSL_X509_get_issuer_name(x509), 0, 0);
426 char* subject = wolfSSL_X509_NAME_oneline(
427 wolfSSL_X509_get_subject_name(x509), 0, 0);
428 byte serial[32];
429 int ret;
430 int sz = sizeof(serial);
431
432 printf("%s\n issuer : %s\n subject: %s\n", hdr, issuer, subject);
433
434 while ( (altName = wolfSSL_X509_get_next_altname(x509)) != NULL)
435 printf(" altname = %s\n", altName);
436
437 ret = wolfSSL_X509_get_serial_number(x509, serial, &sz);
438 if (ret == SSL_SUCCESS) {
439 int i;
440 int strLen;
441 char serialMsg[80];
442
443 /* testsuite has multiple threads writing to stdout, get output
444 message ready to write once */
445 strLen = sprintf(serialMsg, " serial number");
446 for (i = 0; i < sz; i++)
447 sprintf(serialMsg + strLen + (i*3), ":%02x ", serial[i]);
448 printf("%s\n", serialMsg);
449 }
450
451 XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
452 XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
453}
454
455#endif /* KEEP_PEER_CERT || SESSION_CERTS */
456
457
458static INLINE void showPeer(WOLFSSL* ssl)
459{
460
461 WOLFSSL_CIPHER* cipher;
462#ifdef KEEP_PEER_CERT
463 WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl);
464 if (peer)
465 ShowX509(peer, "peer's cert info:");
466 else
467 printf("peer has no cert!\n");
468 wolfSSL_FreeX509(peer);
469#endif
470 printf("SSL version is %s\n", wolfSSL_get_version(ssl));
471
472 cipher = wolfSSL_get_current_cipher(ssl);
473 printf("SSL cipher suite is %s\n", wolfSSL_CIPHER_get_name(cipher));
474
475#if defined(SESSION_CERTS) && defined(SHOW_CERTS)
476 {
477 WOLFSSL_X509_CHAIN* chain = wolfSSL_get_peer_chain(ssl);
478 int count = wolfSSL_get_chain_count(chain);
479 int i;
480
481 for (i = 0; i < count; i++) {
482 int length;
483 unsigned char buffer[3072];
484 WOLFSSL_X509* chainX509;
485
486 wolfSSL_get_chain_cert_pem(chain,i,buffer, sizeof(buffer), &length);
487 buffer[length] = 0;
488 printf("cert %d has length %d data = \n%s\n", i, length, buffer);
489
490 chainX509 = wolfSSL_get_chain_X509(chain, i);
491 if (chainX509)
492 ShowX509(chainX509, "session cert info:");
493 else
494 printf("get_chain_X509 failed\n");
495 wolfSSL_FreeX509(chainX509);
496 }
497 }
498#endif
499 (void)ssl;
500}
501
502
503static INLINE void build_addr(SOCKADDR_IN_T* addr, const char* peer,
504 word16 port, int udp)
505{
506 int useLookup = 0;
507 (void)useLookup;
508 (void)udp;
509
510 memset(addr, 0, sizeof(SOCKADDR_IN_T));
511
512#ifndef TEST_IPV6
513 /* peer could be in human readable form */
514 if ( (peer != INADDR_ANY) && isalpha((int)peer[0])) {
515 #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
516 int err;
517 struct hostent* entry = gethostbyname(peer, &err);
518 #elif defined(WOLFSSL_TIRTOS)
519 struct hostent* entry = DNSGetHostByName(peer);
520 #elif defined(WOLFSSL_VXWORKS)
521 struct hostent* entry = (struct hostent*)hostGetByName(peer);
522 #else
523 struct hostent* entry = gethostbyname(peer);
524 #endif
525
526 if (entry) {
527 memcpy(&addr->sin_addr.s_addr, entry->h_addr_list[0],
528 entry->h_length);
529 useLookup = 1;
530 }
531 else
532 err_sys("no entry for host");
533 }
534#endif
535
536
537#ifndef TEST_IPV6
538 #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
539 addr->sin_family = PF_INET;
540 #else
541 addr->sin_family = AF_INET_V;
542 #endif
543 addr->sin_port = htons(port);
544 if (peer == INADDR_ANY)
545 addr->sin_addr.s_addr = IPADDR_ANY;
546 else {
547 if (!useLookup)
548 addr->sin_addr.s_addr = inet_addr(peer);
549 }
550#else
551 addr->sin6_family = AF_INET_V;
552 addr->sin6_port = htons(port);
553 if (peer == INADDR_ANY)
554 addr->sin6_addr = in6addr_any;
555 else {
556 #ifdef HAVE_GETADDRINFO
557 struct addrinfo hints;
558 struct addrinfo* answer = NULL;
559 int ret;
560 char strPort[80];
561
562 memset(&hints, 0, sizeof(hints));
563
564 hints.ai_family = AF_INET_V;
565 hints.ai_socktype = udp ? SOCK_DGRAM : SOCK_STREAM;
566 hints.ai_protocol = udp ? IPPROTO_UDP : IPPROTO_TCP;
567
568 SNPRINTF(strPort, sizeof(strPort), "%d", port);
569 strPort[79] = '\0';
570
571 ret = getaddrinfo(peer, strPort, &hints, &answer);
572 if (ret < 0 || answer == NULL)
573 err_sys("getaddrinfo failed");
574
575 memcpy(addr, answer->ai_addr, answer->ai_addrlen);
576 freeaddrinfo(answer);
577 #else
578 printf("no ipv6 getaddrinfo, loopback only tests/examples\n");
579 addr->sin6_addr = in6addr_loopback;
580 #endif
581 }
582#endif
583}
584
585
586static INLINE void tcp_socket(SOCKET_T* sockfd, int udp)
587{
588 if (udp)
589 *sockfd = socket(AF_INET_V, SOCK_DGRAM, 0);
590 else
591 *sockfd = socket(AF_INET_V, SOCK_STREAM, 0);
592
593 if(WOLFSSL_SOCKET_IS_INVALID(*sockfd)) {
594 err_sys("socket failed\n");
595 }
596
597#ifndef USE_WINDOWS_API
598#ifdef SO_NOSIGPIPE
599 {
600 int on = 1;
601 socklen_t len = sizeof(on);
602 int res = setsockopt(*sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, len);
603 if (res < 0)
604 err_sys("setsockopt SO_NOSIGPIPE failed\n");
605 }
606#elif defined(WOLFSSL_MDK_ARM) || defined (WOLFSSL_TIRTOS) ||\
607 defined(WOLFSSL_KEIL_TCP_NET)
608 /* nothing to define */
609#else /* no S_NOSIGPIPE */
610 //signal(SIGPIPE, SIG_IGN);
611#endif /* S_NOSIGPIPE */
612
613#if defined(TCP_NODELAY)
614 if (!udp)
615 {
616 int on = 1;
617 socklen_t len = sizeof(on);
618 int res = setsockopt(*sockfd, IPPROTO_TCP, TCP_NODELAY, &on, len);
619 if (res < 0)
620 err_sys("setsockopt TCP_NODELAY failed\n");
621 }
622#endif
623#endif /* USE_WINDOWS_API */
624}
625
626static INLINE void tcp_connect(SOCKET_T* sockfd, const char* ip, word16 port,
627 int udp, WOLFSSL* ssl)
628{
629 SOCKADDR_IN_T addr;
630 build_addr(&addr, ip, port, udp);
631 if(udp) {
632 wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
633 }
634 tcp_socket(sockfd, udp);
635
636 if (!udp) {
637 if (connect(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
638 err_sys("tcp connect failed");
639 }
640}
641
642
643static INLINE void udp_connect(SOCKET_T* sockfd, void* addr, int addrSz)
644{
645 if (connect(*sockfd, (const struct sockaddr*)addr, addrSz) != 0)
646 err_sys("tcp connect failed");
647}
648
649
650enum {
651 TEST_SELECT_FAIL,
652 TEST_TIMEOUT,
653 TEST_RECV_READY,
654 TEST_ERROR_READY
655};
656
657
658#if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET) && \
659 !defined(WOLFSSL_TIRTOS)
660static INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
661{
662 fd_set recvfds, errfds;
663 SOCKET_T nfds = socketfd + 1;
664 struct timeval timeout = { (to_sec > 0) ? to_sec : 0, 0};
665 int result;
666
667 FD_ZERO(&recvfds);
668 FD_SET(socketfd, &recvfds);
669 FD_ZERO(&errfds);
670 FD_SET(socketfd, &errfds);
671
672 result = select(nfds, &recvfds, NULL, &errfds, &timeout);
673
674 if (result == 0)
675 return TEST_TIMEOUT;
676 else if (result > 0) {
677 if (FD_ISSET(socketfd, &recvfds))
678 return TEST_RECV_READY;
679 else if(FD_ISSET(socketfd, &errfds))
680 return TEST_ERROR_READY;
681 }
682
683 return TEST_SELECT_FAIL;
684}
685#elif defined(WOLFSSL_TIRTOS)
686static INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
687{
688 return TEST_RECV_READY;
689}
690#endif /* !WOLFSSL_MDK_ARM */
691
692
693static INLINE void tcp_listen(SOCKET_T* sockfd, word16* port, int useAnyAddr,
694 int udp)
695{
696 SOCKADDR_IN_T addr;
697
698 /* don't use INADDR_ANY by default, firewall may block, make user switch
699 on */
700 build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), *port, udp);
701 tcp_socket(sockfd, udp);
702
703#if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\
704 && !defined(WOLFSSL_KEIL_TCP_NET)
705 {
706 int res, on = 1;
707 socklen_t len = sizeof(on);
708 res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
709 if (res < 0)
710 err_sys("setsockopt SO_REUSEADDR failed\n");
711 }
712#endif
713
714 if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
715 err_sys("tcp bind failed");
716 if (!udp) {
717 if (listen(*sockfd, 5) != 0)
718 err_sys("tcp listen failed");
719 }
720 #if (defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API)) && !defined(WOLFSSL_TIRTOS)
721 if (*port == 0) {
722 socklen_t len = sizeof(addr);
723 if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
724 #ifndef TEST_IPV6
725 *port = ntohs(addr.sin_port);
726 #else
727 *port = ntohs(addr.sin6_port);
728 #endif
729 }
730 }
731 #endif
732}
733
734
735#if 0
736static INLINE int udp_read_connect(SOCKET_T sockfd)
737{
738 SOCKADDR_IN_T cliaddr;
739 byte b[1500];
740 int n;
741 socklen_t len = sizeof(cliaddr);
742
743 n = (int)recvfrom(sockfd, (char*)b, sizeof(b), MSG_PEEK,
744 (struct sockaddr*)&cliaddr, &len);
745 if (n > 0) {
746 if (connect(sockfd, (const struct sockaddr*)&cliaddr,
747 sizeof(cliaddr)) != 0)
748 err_sys("udp connect failed");
749 }
750 else
751 err_sys("recvfrom failed");
752
753 return sockfd;
754}
755#endif
756
757static INLINE void udp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
758 int useAnyAddr, word16 port, func_args* args)
759{
760 SOCKADDR_IN_T addr;
761
762 (void)args;
763 build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), port, 1);
764 tcp_socket(sockfd, 1);
765
766
767#if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM) \
768 && !defined(WOLFSSL_KEIL_TCP_NET)
769 {
770 int res, on = 1;
771 socklen_t len = sizeof(on);
772 res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
773 if (res < 0)
774 err_sys("setsockopt SO_REUSEADDR failed\n");
775 }
776#endif
777
778 if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
779 err_sys("tcp bind failed");
780
781 #if (defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API)) && !defined(WOLFSSL_TIRTOS)
782 if (port == 0) {
783 socklen_t len = sizeof(addr);
784 if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
785 #ifndef TEST_IPV6
786 port = ntohs(addr.sin_port);
787 #else
788 port = ntohs(addr.sin6_port);
789 #endif
790 }
791 }
792 #endif
793
794#if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
795 /* signal ready to accept data */
796 {
797 tcp_ready* ready = args->signal;
798 pthread_mutex_lock(&ready->mutex);
799 ready->ready = 1;
800 ready->port = port;
801 pthread_cond_signal(&ready->cond);
802 pthread_mutex_unlock(&ready->mutex);
803 }
804#elif defined (WOLFSSL_TIRTOS)
805 /* Need mutex? */
806 tcp_ready* ready = args->signal;
807 ready->ready = 1;
808 ready->port = port;
809#endif
810
811 *clientfd = *sockfd;
812}
813
814static INLINE void tcp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
815 func_args* args, word16 port, int useAnyAddr,
816 int udp, int ready_file, int do_listen)
817{
818 SOCKADDR_IN_T client;
819 socklen_t client_len = sizeof(client);
820
821 if (udp) {
822 udp_accept(sockfd, clientfd, useAnyAddr, port, args);
823 return;
824 }
825
826 if(do_listen) {
827 tcp_listen(sockfd, &port, useAnyAddr, udp);
828
829 #if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
830 /* signal ready to tcp_accept */
831 {
832 tcp_ready* ready = args->signal;
833 pthread_mutex_lock(&ready->mutex);
834 ready->ready = 1;
835 ready->port = port;
836 pthread_cond_signal(&ready->cond);
837 pthread_mutex_unlock(&ready->mutex);
838 }
839 #elif defined (WOLFSSL_TIRTOS)
840 /* Need mutex? */
841 tcp_ready* ready = args->signal;
842 ready->ready = 1;
843 ready->port = port;
844 #endif
845
846 if (ready_file) {
847 #ifndef NO_FILESYSTEM
848 #ifndef USE_WINDOWS_API
849 FILE* srf = fopen("/tmp/wolfssl_server_ready", "w");
850 #else
851 FILE* srf = fopen("wolfssl_server_ready", "w");
852 #endif
853
854 if (srf) {
855 fputs("ready", srf);
856 fclose(srf);
857 }
858 #endif
859 }
860 }
861
862 *clientfd = accept(*sockfd, (struct sockaddr*)&client,
863 (ACCEPT_THIRD_T)&client_len);
864 if(WOLFSSL_SOCKET_IS_INVALID(*clientfd)) {
865 err_sys("tcp accept failed");
866 }
867}
868
869
870static INLINE void tcp_set_nonblocking(SOCKET_T* sockfd)
871{
872 #ifdef USE_WINDOWS_API
873 unsigned long blocking = 1;
874 int ret = ioctlsocket(*sockfd, FIONBIO, &blocking);
875 if (ret == SOCKET_ERROR)
876 err_sys("ioctlsocket failed");
877 #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) \
878 || defined (WOLFSSL_TIRTOS)|| defined(WOLFSSL_VXWORKS)
879 /* non blocking not suppported, for now */
880 #else
881 int flags = fcntl(*sockfd, F_GETFL, 0);
882 if (flags < 0)
883 err_sys("fcntl get failed");
884 flags = fcntl(*sockfd, F_SETFL, flags | O_NONBLOCK);
885 if (flags < 0)
886 err_sys("fcntl set failed");
887 #endif
888}
889
890
891#ifndef NO_PSK
892
893static INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint,
894 char* identity, unsigned int id_max_len, unsigned char* key,
895 unsigned int key_max_len)
896{
897 (void)ssl;
898 (void)hint;
899 (void)key_max_len;
900
901 /* identity is OpenSSL testing default for openssl s_client, keep same */
902 strncpy(identity, "Client_identity", id_max_len);
903
904
905 /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
906 unsigned binary */
907 key[0] = 26;
908 key[1] = 43;
909 key[2] = 60;
910 key[3] = 77;
911
912 return 4; /* length of key in octets or 0 for error */
913}
914
915
916static INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identity,
917 unsigned char* key, unsigned int key_max_len)
918{
919 (void)ssl;
920 (void)key_max_len;
921
922 /* identity is OpenSSL testing default for openssl s_client, keep same */
923 if (strncmp(identity, "Client_identity", 15) != 0)
924 return 0;
925
926 /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
927 unsigned binary */
928 key[0] = 26;
929 key[1] = 43;
930 key[2] = 60;
931 key[3] = 77;
932
933 return 4; /* length of key in octets or 0 for error */
934}
935
936#endif /* NO_PSK */
937
938
939#ifdef USE_WINDOWS_API
940
941 #define WIN32_LEAN_AND_MEAN
942 #include <windows.h>
943
944 static INLINE double current_time()
945 {
946 static int init = 0;
947 static LARGE_INTEGER freq;
948
949 LARGE_INTEGER count;
950
951 if (!init) {
952 QueryPerformanceFrequency(&freq);
953 init = 1;
954 }
955
956 QueryPerformanceCounter(&count);
957
958 return (double)count.QuadPart / freq.QuadPart;
959 }
960
961#elif defined(WOLFSSL_TIRTOS)
962 extern double current_time();
963#elif defined(WOLFSSL_uITRON4)
964 #include <kernel.h>
965 static INLINE double current_time()
966 {
967 SYSTIM time;
968 get_tim(&time);
969 return (double)time;
970 }
971#else
972
973#if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET)
974 #include <sys/time.h>
975
976 static INLINE double current_time(void)
977 {
978 struct timeval tv;
979 gettimeofday(&tv, 0);
980
981 return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
982 }
983
984#endif
985#endif /* USE_WINDOWS_API */
986
987
988#if defined(NO_FILESYSTEM) && !defined(NO_CERTS)
989
990 enum {
991 WOLFSSL_CA = 1,
992 WOLFSSL_CERT = 2,
993 WOLFSSL_KEY = 3
994 };
995
996 static INLINE void load_buffer(WOLFSSL_CTX* ctx, const char* fname, int type)
997 {
998 /* test buffer load */
999 long sz = 0;
1000 byte buff[10000];
1001 FILE* file = fopen(fname, "rb");
1002
1003 if (!file)
1004 err_sys("can't open file for buffer load "
1005 "Please run from wolfSSL home directory if not");
1006 fseek(file, 0, SEEK_END);
1007 sz = ftell(file);
1008 rewind(file);
1009 fread(buff, sizeof(buff), 1, file);
1010
1011 if (type == WOLFSSL_CA) {
1012 if (wolfSSL_CTX_load_verify_buffer(ctx, buff, sz, SSL_FILETYPE_PEM)
1013 != SSL_SUCCESS)
1014 err_sys("can't load buffer ca file");
1015 }
1016 else if (type == WOLFSSL_CERT) {
1017 if (wolfSSL_CTX_use_certificate_buffer(ctx, buff, sz,
1018 SSL_FILETYPE_PEM) != SSL_SUCCESS)
1019 err_sys("can't load buffer cert file");
1020 }
1021 else if (type == WOLFSSL_KEY) {
1022 if (wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, sz,
1023 SSL_FILETYPE_PEM) != SSL_SUCCESS)
1024 err_sys("can't load buffer key file");
1025 }
1026 fclose(file);
1027 }
1028
1029#endif /* NO_FILESYSTEM */
1030
1031#ifdef VERIFY_CALLBACK
1032
1033static INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store)
1034{
1035 (void)preverify;
1036 char buffer[WOLFSSL_MAX_ERROR_SZ];
1037
1038#ifdef OPENSSL_EXTRA
1039 WOLFSSL_X509* peer;
1040#endif
1041
1042 printf("In verification callback, error = %d, %s\n", store->error,
1043 wolfSSL_ERR_error_string(store->error, buffer));
1044#ifdef OPENSSL_EXTRA
1045 peer = store->current_cert;
1046 if (peer) {
1047 char* issuer = wolfSSL_X509_NAME_oneline(
1048 wolfSSL_X509_get_issuer_name(peer), 0, 0);
1049 char* subject = wolfSSL_X509_NAME_oneline(
1050 wolfSSL_X509_get_subject_name(peer), 0, 0);
1051 printf("peer's cert info:\n issuer : %s\n subject: %s\n", issuer,
1052 subject);
1053 XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
1054 XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
1055 }
1056 else
1057 printf("peer has no cert!\n");
1058#endif
1059 printf("Subject's domain name is %s\n", store->domain);
1060
1061 printf("Allowing to continue anyway (shouldn't do this, EVER!!!)\n");
1062 return 1;
1063}
1064
1065#endif /* VERIFY_CALLBACK */
1066
1067
1068static INLINE int myDateCb(int preverify, WOLFSSL_X509_STORE_CTX* store)
1069{
1070 char buffer[WOLFSSL_MAX_ERROR_SZ];
1071 (void)preverify;
1072
1073 printf("In verification callback, error = %d, %s\n", store->error,
1074 wolfSSL_ERR_error_string(store->error, buffer));
1075 printf("Subject's domain name is %s\n", store->domain);
1076
1077 if (store->error == ASN_BEFORE_DATE_E || store->error == ASN_AFTER_DATE_E) {
1078 printf("Overriding cert date error as example for bad clock testing\n");
1079 return 1;
1080 }
1081 printf("Cert error is not date error, not overriding\n");
1082
1083 return 0;
1084}
1085
1086
1087#ifdef HAVE_CRL
1088
1089static INLINE void CRL_CallBack(const char* url)
1090{
1091 printf("CRL callback url = %s\n", url);
1092}
1093
1094#endif
1095
1096#ifndef NO_DH
1097static INLINE void SetDH(WOLFSSL* ssl)
1098{
1099 /* dh1024 p */
1100 static unsigned char p[] =
1101 {
1102 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
1103 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
1104 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
1105 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
1106 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
1107 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
1108 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
1109 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
1110 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
1111 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
1112 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
1113 };
1114
1115 /* dh1024 g */
1116 static unsigned char g[] =
1117 {
1118 0x02,
1119 };
1120
1121 wolfSSL_SetTmpDH(ssl, p, sizeof(p), g, sizeof(g));
1122}
1123
1124static INLINE void SetDHCtx(WOLFSSL_CTX* ctx)
1125{
1126 /* dh1024 p */
1127 static unsigned char p[] =
1128 {
1129 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
1130 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
1131 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
1132 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
1133 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
1134 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
1135 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
1136 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
1137 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
1138 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
1139 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
1140 };
1141
1142 /* dh1024 g */
1143 static unsigned char g[] =
1144 {
1145 0x02,
1146 };
1147
1148 wolfSSL_CTX_SetTmpDH(ctx, p, sizeof(p), g, sizeof(g));
1149}
1150#endif /* NO_DH */
1151
1152#ifndef NO_CERTS
1153
1154static INLINE void CaCb(unsigned char* der, int sz, int type)
1155{
1156 (void)der;
1157 printf("Got CA cache add callback, derSz = %d, type = %d\n", sz, type);
1158}
1159
1160#endif /* !NO_CERTS */
1161
1162#ifdef HAVE_CAVIUM
1163
1164static INLINE int OpenNitroxDevice(int dma_mode,int dev_id)
1165{
1166 Csp1CoreAssignment core_assign;
1167 Uint32 device;
1168
1169 if (CspInitialize(CAVIUM_DIRECT,CAVIUM_DEV_ID))
1170 return -1;
1171 if (Csp1GetDevType(&device))
1172 return -1;
1173 if (device != NPX_DEVICE) {
1174 if (ioctl(gpkpdev_hdlr[CAVIUM_DEV_ID], IOCTL_CSP1_GET_CORE_ASSIGNMENT,
1175 (Uint32 *)&core_assign)!= 0)
1176 return -1;
1177 }
1178 CspShutdown(CAVIUM_DEV_ID);
1179
1180 return CspInitialize(dma_mode, dev_id);
1181}
1182
1183#endif /* HAVE_CAVIUM */
1184
1185
1186#ifdef USE_WINDOWS_API
1187
1188/* do back x number of directories */
1189static INLINE void ChangeDirBack(int x)
1190{
1191 char path[MAX_PATH];
1192 XMEMSET(path, 0, MAX_PATH);
1193 XSTRNCAT(path, ".\\", MAX_PATH);
1194 while (x-- > 0) {
1195 XSTRNCAT(path, "..\\", MAX_PATH);
1196 }
1197 SetCurrentDirectoryA(path);
1198}
1199
1200/* does current dir contain str */
1201static INLINE int CurrentDir(const char* str)
1202{
1203 char path[MAX_PATH];
1204 char* baseName;
1205
1206 GetCurrentDirectoryA(sizeof(path), path);
1207
1208 baseName = strrchr(path, '\\');
1209 if (baseName)
1210 baseName++;
1211 else
1212 baseName = path;
1213
1214 if (strstr(baseName, str))
1215 return 1;
1216
1217 return 0;
1218}
1219
1220#elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_FS)
1221 /* KEIL-RL File System does not support relative directry */
1222#elif defined(WOLFSSL_TIRTOS)
1223#else
1224
1225#ifndef MAX_PATH
1226 #define MAX_PATH 256
1227#endif
1228
1229/* do back x number of directories */
1230static INLINE void ChangeDirBack(int x)
1231{
1232 char path[MAX_PATH];
1233 XMEMSET(path, 0, MAX_PATH);
1234 XSTRNCAT(path, "./", MAX_PATH);
1235 while (x-- > 0) {
1236 XSTRNCAT(path, "../", MAX_PATH);
1237 }
1238 //if (chdir(path) < 0) {
1239 // printf("chdir to %s failed\n", path);
1240 //}
1241}
1242
1243/* does current dir contain str */
1244static INLINE int CurrentDir(const char* str)
1245{
1246 char path[MAX_PATH];
1247 char* baseName;
1248
1249 //if (getcwd(path, sizeof(path)) == NULL) {
1250 // printf("no current dir?\n");
1251 // return 0;
1252 //}
1253
1254 baseName = strrchr(path, '/');
1255 if (baseName)
1256 baseName++;
1257 else
1258 baseName = path;
1259
1260 if (strstr(baseName, str))
1261 return 1;
1262
1263 return 0;
1264}
1265
1266#endif /* USE_WINDOWS_API */
1267
1268
1269#ifdef USE_WOLFSSL_MEMORY
1270
1271 typedef struct memoryStats {
1272 size_t totalAllocs; /* number of allocations */
1273 size_t totalBytes; /* total number of bytes allocated */
1274 size_t peakBytes; /* concurrent max bytes */
1275 size_t currentBytes; /* total current bytes in use */
1276 } memoryStats;
1277
1278 typedef struct memHint {
1279 size_t thisSize; /* size of this memory */
1280 void* thisMemory; /* actual memory for user */
1281 } memHint;
1282
1283 typedef struct memoryTrack {
1284 union {
1285 memHint hint;
1286 byte alignit[16]; /* make sure we have strong alignment */
1287 } u;
1288 } memoryTrack;
1289
1290 #if defined(WOLFSSL_TRACK_MEMORY)
1291 #define DO_MEM_STATS
1292 static memoryStats ourMemStats;
1293 #endif
1294
1295 static INLINE void* TrackMalloc(size_t sz)
1296 {
1297 memoryTrack* mt;
1298
1299 if (sz == 0)
1300 return NULL;
1301
1302 mt = (memoryTrack*)malloc(sizeof(memoryTrack) + sz);
1303 if (mt == NULL)
1304 return NULL;
1305
1306 mt->u.hint.thisSize = sz;
1307 mt->u.hint.thisMemory = (byte*)mt + sizeof(memoryTrack);
1308
1309#ifdef DO_MEM_STATS
1310 ourMemStats.totalAllocs++;
1311 ourMemStats.totalBytes += sz;
1312 ourMemStats.currentBytes += sz;
1313 if (ourMemStats.currentBytes > ourMemStats.peakBytes)
1314 ourMemStats.peakBytes = ourMemStats.currentBytes;
1315#endif
1316
1317 return mt->u.hint.thisMemory;
1318 }
1319
1320
1321 static INLINE void TrackFree(void* ptr)
1322 {
1323 memoryTrack* mt;
1324
1325 if (ptr == NULL)
1326 return;
1327
1328 mt = (memoryTrack*)ptr;
1329 --mt; /* same as minus sizeof(memoryTrack), removes header */
1330
1331#ifdef DO_MEM_STATS
1332 ourMemStats.currentBytes -= mt->u.hint.thisSize;
1333#endif
1334
1335 free(mt);
1336 }
1337
1338
1339 static INLINE void* TrackRealloc(void* ptr, size_t sz)
1340 {
1341 void* ret = TrackMalloc(sz);
1342
1343 if (ptr) {
1344 /* if realloc is bigger, don't overread old ptr */
1345 memoryTrack* mt = (memoryTrack*)ptr;
1346 --mt; /* same as minus sizeof(memoryTrack), removes header */
1347
1348 if (mt->u.hint.thisSize < sz)
1349 sz = mt->u.hint.thisSize;
1350 }
1351
1352 if (ret && ptr)
1353 memcpy(ret, ptr, sz);
1354
1355 if (ret)
1356 TrackFree(ptr);
1357
1358 return ret;
1359 }
1360
1361 static INLINE void InitMemoryTracker(void)
1362 {
1363 if (wolfSSL_SetAllocators(TrackMalloc, TrackFree, TrackRealloc) != 0)
1364 err_sys("wolfSSL SetAllocators failed for track memory");
1365
1366 #ifdef DO_MEM_STATS
1367 ourMemStats.totalAllocs = 0;
1368 ourMemStats.totalBytes = 0;
1369 ourMemStats.peakBytes = 0;
1370 ourMemStats.currentBytes = 0;
1371 #endif
1372 }
1373
1374 static INLINE void ShowMemoryTracker(void)
1375 {
1376 #ifdef DO_MEM_STATS
1377 printf("total Allocs = %9lu\n",
1378 (unsigned long)ourMemStats.totalAllocs);
1379 printf("total Bytes = %9lu\n",
1380 (unsigned long)ourMemStats.totalBytes);
1381 printf("peak Bytes = %9lu\n",
1382 (unsigned long)ourMemStats.peakBytes);
1383 printf("current Bytes = %9lu\n",
1384 (unsigned long)ourMemStats.currentBytes);
1385 #endif
1386 }
1387
1388#endif /* USE_WOLFSSL_MEMORY */
1389
1390
1391#ifdef HAVE_STACK_SIZE
1392
1393typedef THREAD_RETURN WOLFSSL_THREAD (*thread_func)(void* args);
1394
1395
1396static INLINE void StackSizeCheck(func_args* args, thread_func tf)
1397{
1398 int ret, i, used;
1399 unsigned char* myStack;
1400 int stackSize = 1024*128;
1401 pthread_attr_t myAttr;
1402 pthread_t threadId;
1403
1404#ifdef PTHREAD_STACK_MIN
1405 if (stackSize < PTHREAD_STACK_MIN)
1406 stackSize = PTHREAD_STACK_MIN;
1407#endif
1408
1409 ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize);
1410 if (ret != 0)
1411 err_sys("posix_memalign failed\n");
1412
1413 memset(myStack, 0x01, stackSize);
1414
1415 ret = pthread_attr_init(&myAttr);
1416 if (ret != 0)
1417 err_sys("attr_init failed");
1418
1419 ret = pthread_attr_setstack(&myAttr, myStack, stackSize);
1420 if (ret != 0)
1421 err_sys("attr_setstackaddr failed");
1422
1423 ret = pthread_create(&threadId, &myAttr, tf, args);
1424 if (ret != 0) {
1425 perror("pthread_create failed");
1426 exit(EXIT_FAILURE);
1427 }
1428
1429 ret = pthread_join(threadId, NULL);
1430 if (ret != 0)
1431 err_sys("pthread_join failed");
1432
1433 for (i = 0; i < stackSize; i++) {
1434 if (myStack[i] != 0x01) {
1435 break;
1436 }
1437 }
1438
1439 used = stackSize - i;
1440 printf("stack used = %d\n", used);
1441}
1442
1443
1444#endif /* HAVE_STACK_SIZE */
1445
1446
1447#ifdef STACK_TRAP
1448
1449/* good settings
1450 --enable-debug --disable-shared C_EXTRA_FLAGS="-DUSER_TIME -DTFM_TIMING_RESISTANT -DPOSITIVE_EXP_ONLY -DSTACK_TRAP"
1451
1452*/
1453
1454#ifdef HAVE_STACK_SIZE
1455 /* client only for now, setrlimit will fail if pthread_create() called */
1456 /* STACK_SIZE does pthread_create() on client */
1457 #error "can't use STACK_TRAP with STACK_SIZE, setrlimit will fail"
1458#endif /* HAVE_STACK_SIZE */
1459
1460static INLINE void StackTrap(void)
1461{
1462 struct rlimit rl;
1463 if (getrlimit(RLIMIT_STACK, &rl) != 0)
1464 err_sys("getrlimit failed");
1465 printf("rlim_cur = %llu\n", rl.rlim_cur);
1466 rl.rlim_cur = 1024*21; /* adjust trap size here */
1467 if (setrlimit(RLIMIT_STACK, &rl) != 0) {
1468 perror("setrlimit");
1469 err_sys("setrlimit failed");
1470 }
1471}
1472
1473#else /* STACK_TRAP */
1474
1475static INLINE void StackTrap(void)
1476{
1477}
1478
1479#endif /* STACK_TRAP */
1480
1481
1482#ifdef ATOMIC_USER
1483
1484/* Atomic Encrypt Context example */
1485typedef struct AtomicEncCtx {
1486 int keySetup; /* have we done key setup yet */
1487 Aes aes; /* for aes example */
1488} AtomicEncCtx;
1489
1490
1491/* Atomic Decrypt Context example */
1492typedef struct AtomicDecCtx {
1493 int keySetup; /* have we done key setup yet */
1494 Aes aes; /* for aes example */
1495} AtomicDecCtx;
1496
1497
1498static INLINE int myMacEncryptCb(WOLFSSL* ssl, unsigned char* macOut,
1499 const unsigned char* macIn, unsigned int macInSz, int macContent,
1500 int macVerify, unsigned char* encOut, const unsigned char* encIn,
1501 unsigned int encSz, void* ctx)
1502{
1503 int ret;
1504 Hmac hmac;
1505 byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
1506 AtomicEncCtx* encCtx = (AtomicEncCtx*)ctx;
1507 const char* tlsStr = "TLS";
1508
1509 /* example supports (d)tls aes */
1510 if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
1511 printf("myMacEncryptCb not using AES\n");
1512 return -1;
1513 }
1514
1515 if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
1516 printf("myMacEncryptCb not using (D)TLS\n");
1517 return -1;
1518 }
1519
1520 /* hmac, not needed if aead mode */
1521 wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
1522
1523 ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
1524 wolfSSL_GetMacSecret(ssl, macVerify), wolfSSL_GetHmacSize(ssl));
1525 if (ret != 0)
1526 return ret;
1527 ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
1528 if (ret != 0)
1529 return ret;
1530 ret = wc_HmacUpdate(&hmac, macIn, macInSz);
1531 if (ret != 0)
1532 return ret;
1533 ret = wc_HmacFinal(&hmac, macOut);
1534 if (ret != 0)
1535 return ret;
1536
1537
1538 /* encrypt setup on first time */
1539 if (encCtx->keySetup == 0) {
1540 int keyLen = wolfSSL_GetKeySize(ssl);
1541 const byte* key;
1542 const byte* iv;
1543
1544 if (wolfSSL_GetSide(ssl) == WOLFSSL_CLIENT_END) {
1545 key = wolfSSL_GetClientWriteKey(ssl);
1546 iv = wolfSSL_GetClientWriteIV(ssl);
1547 }
1548 else {
1549 key = wolfSSL_GetServerWriteKey(ssl);
1550 iv = wolfSSL_GetServerWriteIV(ssl);
1551 }
1552
1553 ret = wc_AesSetKey(&encCtx->aes, key, keyLen, iv, AES_ENCRYPTION);
1554 if (ret != 0) {
1555 printf("AesSetKey failed in myMacEncryptCb\n");
1556 return ret;
1557 }
1558 encCtx->keySetup = 1;
1559 }
1560
1561 /* encrypt */
1562 return wc_AesCbcEncrypt(&encCtx->aes, encOut, encIn, encSz);
1563}
1564
1565
1566static INLINE int myDecryptVerifyCb(WOLFSSL* ssl,
1567 unsigned char* decOut, const unsigned char* decIn,
1568 unsigned int decSz, int macContent, int macVerify,
1569 unsigned int* padSz, void* ctx)
1570{
1571 AtomicDecCtx* decCtx = (AtomicDecCtx*)ctx;
1572 int ret = 0;
1573 int macInSz = 0;
1574 int ivExtra = 0;
1575 int digestSz = wolfSSL_GetHmacSize(ssl);
1576 unsigned int pad = 0;
1577 unsigned int padByte = 0;
1578 Hmac hmac;
1579 byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
1580 byte verify[MAX_DIGEST_SIZE];
1581 const char* tlsStr = "TLS";
1582
1583 /* example supports (d)tls aes */
1584 if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
1585 printf("myMacEncryptCb not using AES\n");
1586 return -1;
1587 }
1588
1589 if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
1590 printf("myMacEncryptCb not using (D)TLS\n");
1591 return -1;
1592 }
1593
1594 /*decrypt */
1595 if (decCtx->keySetup == 0) {
1596 int keyLen = wolfSSL_GetKeySize(ssl);
1597 const byte* key;
1598 const byte* iv;
1599
1600 /* decrypt is from other side (peer) */
1601 if (wolfSSL_GetSide(ssl) == WOLFSSL_SERVER_END) {
1602 key = wolfSSL_GetClientWriteKey(ssl);
1603 iv = wolfSSL_GetClientWriteIV(ssl);
1604 }
1605 else {
1606 key = wolfSSL_GetServerWriteKey(ssl);
1607 iv = wolfSSL_GetServerWriteIV(ssl);
1608 }
1609
1610 ret = wc_AesSetKey(&decCtx->aes, key, keyLen, iv, AES_DECRYPTION);
1611 if (ret != 0) {
1612 printf("AesSetKey failed in myDecryptVerifyCb\n");
1613 return ret;
1614 }
1615 decCtx->keySetup = 1;
1616 }
1617
1618 /* decrypt */
1619 ret = wc_AesCbcDecrypt(&decCtx->aes, decOut, decIn, decSz);
1620 if (ret != 0)
1621 return ret;
1622
1623 if (wolfSSL_GetCipherType(ssl) == WOLFSSL_AEAD_TYPE) {
1624 *padSz = wolfSSL_GetAeadMacSize(ssl);
1625 return 0; /* hmac, not needed if aead mode */
1626 }
1627
1628 if (wolfSSL_GetCipherType(ssl) == WOLFSSL_BLOCK_TYPE) {
1629 pad = *(decOut + decSz - 1);
1630 padByte = 1;
1631 if (wolfSSL_IsTLSv1_1(ssl))
1632 ivExtra = wolfSSL_GetCipherBlockSize(ssl);
1633 }
1634
1635 *padSz = wolfSSL_GetHmacSize(ssl) + pad + padByte;
1636 macInSz = decSz - ivExtra - digestSz - pad - padByte;
1637
1638 wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
1639
1640 ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
1641 wolfSSL_GetMacSecret(ssl, macVerify), digestSz);
1642 if (ret != 0)
1643 return ret;
1644 ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
1645 if (ret != 0)
1646 return ret;
1647 ret = wc_HmacUpdate(&hmac, decOut + ivExtra, macInSz);
1648 if (ret != 0)
1649 return ret;
1650 ret = wc_HmacFinal(&hmac, verify);
1651 if (ret != 0)
1652 return ret;
1653
1654 if (memcmp(verify, decOut + decSz - digestSz - pad - padByte,
1655 digestSz) != 0) {
1656 printf("myDecryptVerify verify failed\n");
1657 return -1;
1658 }
1659
1660 return ret;
1661}
1662
1663
1664static INLINE void SetupAtomicUser(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
1665{
1666 AtomicEncCtx* encCtx;
1667 AtomicDecCtx* decCtx;
1668
1669 encCtx = (AtomicEncCtx*)malloc(sizeof(AtomicEncCtx));
1670 if (encCtx == NULL)
1671 err_sys("AtomicEncCtx malloc failed");
1672 memset(encCtx, 0, sizeof(AtomicEncCtx));
1673
1674 decCtx = (AtomicDecCtx*)malloc(sizeof(AtomicDecCtx));
1675 if (decCtx == NULL) {
1676 free(encCtx);
1677 err_sys("AtomicDecCtx malloc failed");
1678 }
1679 memset(decCtx, 0, sizeof(AtomicDecCtx));
1680
1681 wolfSSL_CTX_SetMacEncryptCb(ctx, myMacEncryptCb);
1682 wolfSSL_SetMacEncryptCtx(ssl, encCtx);
1683
1684 wolfSSL_CTX_SetDecryptVerifyCb(ctx, myDecryptVerifyCb);
1685 wolfSSL_SetDecryptVerifyCtx(ssl, decCtx);
1686}
1687
1688
1689static INLINE void FreeAtomicUser(WOLFSSL* ssl)
1690{
1691 AtomicEncCtx* encCtx = (AtomicEncCtx*)wolfSSL_GetMacEncryptCtx(ssl);
1692 AtomicDecCtx* decCtx = (AtomicDecCtx*)wolfSSL_GetDecryptVerifyCtx(ssl);
1693
1694 free(decCtx);
1695 free(encCtx);
1696}
1697
1698#endif /* ATOMIC_USER */
1699
1700
1701#ifdef HAVE_PK_CALLBACKS
1702
1703#ifdef HAVE_ECC
1704
1705static INLINE int myEccSign(WOLFSSL* ssl, const byte* in, word32 inSz,
1706 byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
1707{
1708 WC_RNG rng;
1709 int ret;
1710 word32 idx = 0;
1711 ecc_key myKey;
1712
1713 (void)ssl;
1714 (void)ctx;
1715
1716 ret = wc_InitRng(&rng);
1717 if (ret != 0)
1718 return ret;
1719
1720 wc_ecc_init(&myKey);
1721
1722 ret = wc_EccPrivateKeyDecode(key, &idx, &myKey, keySz);
1723 if (ret == 0)
1724 ret = wc_ecc_sign_hash(in, inSz, out, outSz, &rng, &myKey);
1725 wc_ecc_free(&myKey);
1726 wc_FreeRng(&rng);
1727
1728 return ret;
1729}
1730
1731
1732static INLINE int myEccVerify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
1733 const byte* hash, word32 hashSz, const byte* key, word32 keySz,
1734 int* result, void* ctx)
1735{
1736 int ret;
1737 ecc_key myKey;
1738
1739 (void)ssl;
1740 (void)ctx;
1741
1742 wc_ecc_init(&myKey);
1743
1744 ret = wc_ecc_import_x963(key, keySz, &myKey);
1745 if (ret == 0)
1746 ret = wc_ecc_verify_hash(sig, sigSz, hash, hashSz, result, &myKey);
1747 wc_ecc_free(&myKey);
1748
1749 return ret;
1750}
1751
1752#endif /* HAVE_ECC */
1753
1754#ifndef NO_RSA
1755
1756static INLINE int myRsaSign(WOLFSSL* ssl, const byte* in, word32 inSz,
1757 byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
1758{
1759 WC_RNG rng;
1760 int ret;
1761 word32 idx = 0;
1762 RsaKey myKey;
1763
1764 (void)ssl;
1765 (void)ctx;
1766
1767 ret = wc_InitRng(&rng);
1768 if (ret != 0)
1769 return ret;
1770
1771 wc_InitRsaKey(&myKey, NULL);
1772
1773 ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
1774 if (ret == 0)
1775 ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, &myKey, &rng);
1776 if (ret > 0) { /* save and convert to 0 success */
1777 *outSz = ret;
1778 ret = 0;
1779 }
1780 wc_FreeRsaKey(&myKey);
1781 wc_FreeRng(&rng);
1782
1783 return ret;
1784}
1785
1786
1787static INLINE int myRsaVerify(WOLFSSL* ssl, byte* sig, word32 sigSz,
1788 byte** out,
1789 const byte* key, word32 keySz,
1790 void* ctx)
1791{
1792 int ret;
1793 word32 idx = 0;
1794 RsaKey myKey;
1795
1796 (void)ssl;
1797 (void)ctx;
1798
1799 wc_InitRsaKey(&myKey, NULL);
1800
1801 ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
1802 if (ret == 0)
1803 ret = wc_RsaSSL_VerifyInline(sig, sigSz, out, &myKey);
1804 wc_FreeRsaKey(&myKey);
1805
1806 return ret;
1807}
1808
1809
1810static INLINE int myRsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz,
1811 byte* out, word32* outSz, const byte* key,
1812 word32 keySz, void* ctx)
1813{
1814 int ret;
1815 word32 idx = 0;
1816 RsaKey myKey;
1817 WC_RNG rng;
1818
1819 (void)ssl;
1820 (void)ctx;
1821
1822 ret = wc_InitRng(&rng);
1823 if (ret != 0)
1824 return ret;
1825
1826 wc_InitRsaKey(&myKey, NULL);
1827
1828 ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
1829 if (ret == 0) {
1830 ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, &myKey, &rng);
1831 if (ret > 0) {
1832 *outSz = ret;
1833 ret = 0; /* reset to success */
1834 }
1835 }
1836 wc_FreeRsaKey(&myKey);
1837 wc_FreeRng(&rng);
1838
1839 return ret;
1840}
1841
1842static INLINE int myRsaDec(WOLFSSL* ssl, byte* in, word32 inSz,
1843 byte** out,
1844 const byte* key, word32 keySz, void* ctx)
1845{
1846 int ret;
1847 word32 idx = 0;
1848 RsaKey myKey;
1849
1850 (void)ssl;
1851 (void)ctx;
1852
1853 wc_InitRsaKey(&myKey, NULL);
1854
1855 ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
1856 if (ret == 0) {
1857 ret = wc_RsaPrivateDecryptInline(in, inSz, out, &myKey);
1858 }
1859 wc_FreeRsaKey(&myKey);
1860
1861 return ret;
1862}
1863
1864#endif /* NO_RSA */
1865
1866static INLINE void SetupPkCallbacks(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
1867{
1868 (void)ctx;
1869 (void)ssl;
1870
1871 #ifdef HAVE_ECC
1872 wolfSSL_CTX_SetEccSignCb(ctx, myEccSign);
1873 wolfSSL_CTX_SetEccVerifyCb(ctx, myEccVerify);
1874 #endif /* HAVE_ECC */
1875 #ifndef NO_RSA
1876 wolfSSL_CTX_SetRsaSignCb(ctx, myRsaSign);
1877 wolfSSL_CTX_SetRsaVerifyCb(ctx, myRsaVerify);
1878 wolfSSL_CTX_SetRsaEncCb(ctx, myRsaEnc);
1879 wolfSSL_CTX_SetRsaDecCb(ctx, myRsaDec);
1880 #endif /* NO_RSA */
1881}
1882
1883#endif /* HAVE_PK_CALLBACKS */
1884
1885
1886
1887
1888
1889#if defined(__hpux__) || defined(__MINGW32__) || defined (WOLFSSL_TIRTOS) \
1890 || defined(_MSC_VER)
1891
1892/* HP/UX doesn't have strsep, needed by test/suites.c */
1893static INLINE char* strsep(char **stringp, const char *delim)
1894{
1895 char* start;
1896 char* end;
1897
1898 start = *stringp;
1899 if (start == NULL)
1900 return NULL;
1901
1902 if ((end = strpbrk(start, delim))) {
1903 *end++ = '\0';
1904 *stringp = end;
1905 } else {
1906 *stringp = NULL;
1907 }
1908
1909 return start;
1910}
1911
1912#endif /* __hpux__ and others */
1913
1914/* Create unique filename, len is length of tempfn name, assuming
1915 len does not include null terminating character,
1916 num is number of characters in tempfn name to randomize */
1917static INLINE const char* mymktemp(char *tempfn, int len, int num)
1918{
1919 int x, size;
1920 static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1921 "abcdefghijklmnopqrstuvwxyz";
1922 WC_RNG rng;
1923 byte out;
1924
1925 if (tempfn == NULL || len < 1 || num < 1 || len <= num) {
1926 printf("Bad input\n");
1927 return NULL;
1928 }
1929
1930 size = len - 1;
1931
1932 if (wc_InitRng(&rng) != 0) {
1933 printf("InitRng failed\n");
1934 return NULL;
1935 }
1936
1937 for (x = size; x > size - num; x--) {
1938 if (wc_RNG_GenerateBlock(&rng,(byte*)&out, sizeof(out)) != 0) {
1939 printf("RNG_GenerateBlock failed\n");
1940 return NULL;
1941 }
1942 tempfn[x] = alphanum[out % (sizeof(alphanum) - 1)];
1943 }
1944 tempfn[len] = '\0';
1945
1946 wc_FreeRng(&rng);
1947
1948 return tempfn;
1949}
1950
1951
1952
1953#if defined(HAVE_SESSION_TICKET) && defined(HAVE_CHACHA) && \
1954 defined(HAVE_POLY1305)
1955
1956 #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
1957
1958 typedef struct key_ctx {
1959 byte name[WOLFSSL_TICKET_NAME_SZ]; /* name for this context */
1960 byte key[16]; /* cipher key */
1961 } key_ctx;
1962
1963 static key_ctx myKey_ctx;
1964 static WC_RNG myKey_rng;
1965
1966 static INLINE int TicketInit(void)
1967 {
1968 int ret = wc_InitRng(&myKey_rng);
1969 if (ret != 0) return ret;
1970
1971 ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.key, sizeof(myKey_ctx.key));
1972 if (ret != 0) return ret;
1973
1974 ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.name,sizeof(myKey_ctx.name));
1975 if (ret != 0) return ret;
1976
1977 return 0;
1978 }
1979
1980 static INLINE void TicketCleanup(void)
1981 {
1982 wc_FreeRng(&myKey_rng);
1983 }
1984
1985 static INLINE int myTicketEncCb(WOLFSSL* ssl,
1986 byte key_name[WOLFSSL_TICKET_NAME_SZ],
1987 byte iv[WOLFSSL_TICKET_IV_SZ],
1988 byte mac[WOLFSSL_TICKET_MAC_SZ],
1989 int enc, byte* ticket, int inLen, int* outLen,
1990 void* userCtx)
1991 {
1992 (void)ssl;
1993 (void)userCtx;
1994
1995 int ret;
1996 word16 sLen = htons(inLen);
1997 byte aad[WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2];
1998 int aadSz = WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2;
1999 byte* tmp = aad;
2000
2001 if (enc) {
2002 XMEMCPY(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ);
2003
2004 ret = wc_RNG_GenerateBlock(&myKey_rng, iv, WOLFSSL_TICKET_IV_SZ);
2005 if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
2006
2007 /* build aad from key name, iv, and length */
2008 XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
2009 tmp += WOLFSSL_TICKET_NAME_SZ;
2010 XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
2011 tmp += WOLFSSL_TICKET_IV_SZ;
2012 XMEMCPY(tmp, &sLen, 2);
2013
2014 ret = wc_ChaCha20Poly1305_Encrypt(myKey_ctx.key, iv,
2015 aad, aadSz,
2016 ticket, inLen,
2017 ticket,
2018 mac);
2019 if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
2020 *outLen = inLen; /* no padding in this mode */
2021 } else {
2022 /* decrypt */
2023
2024 /* see if we know this key */
2025 if (XMEMCMP(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ) != 0){
2026 printf("client presented unknown ticket key name ");
2027 return WOLFSSL_TICKET_RET_FATAL;
2028 }
2029
2030 /* build aad from key name, iv, and length */
2031 XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
2032 tmp += WOLFSSL_TICKET_NAME_SZ;
2033 XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
2034 tmp += WOLFSSL_TICKET_IV_SZ;
2035 XMEMCPY(tmp, &sLen, 2);
2036
2037 ret = wc_ChaCha20Poly1305_Decrypt(myKey_ctx.key, iv,
2038 aad, aadSz,
2039 ticket, inLen,
2040 mac,
2041 ticket);
2042 if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
2043 *outLen = inLen; /* no padding in this mode */
2044 }
2045
2046 return WOLFSSL_TICKET_RET_OK;
2047 }
2048
2049#endif /* HAVE_SESSION_TICKET && CHACHA20 && POLY1305 */
2050
2051#endif /* wolfSSL_TEST_H */
Note: See TracBrowser for help on using the repository browser.