source: asp3_tinet_ecnl_rx/trunk/wolfssl-3.12.2/wolfssl/test.h@ 337

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

ASP3版ECNLを追加

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-chdr;charset=UTF-8
File size: 65.9 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 #ifndef NO_RSA
22 #include <wolfssl/wolfcrypt/rsa.h>
23 #endif
24 #ifdef HAVE_ECC
25 #include <wolfssl/wolfcrypt/ecc.h>
26 #endif /* HAVE_ECC */
27 #ifdef HAVE_ED25519
28 #include <wolfssl/wolfcrypt/ed25519.h>
29 #endif /* HAVE_ED25519 */
30 #ifdef HAVE_CURVE25519
31 #include <wolfssl/wolfcrypt/curve25519.h>
32 #endif /* HAVE_ECC */
33#endif /*HAVE_PK_CALLBACKS */
34
35#ifdef USE_WINDOWS_API
36 #include <winsock2.h>
37 #include <process.h>
38 #ifdef TEST_IPV6 /* don't require newer SDK for IPV4 */
39 #include <ws2tcpip.h>
40 #include <wspiapi.h>
41 #endif
42 #define SOCKET_T SOCKET
43 #define SNPRINTF _snprintf
44#elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
45 #include <string.h>
46 #include "rl_net.h"
47 #define SOCKET_T int
48 typedef int socklen_t ;
49 static unsigned long inet_addr(const char *cp)
50 {
51 unsigned int a[4] ; unsigned long ret ;
52 sscanf(cp, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]) ;
53 ret = ((a[3]<<24) + (a[2]<<16) + (a[1]<<8) + a[0]) ;
54 return(ret) ;
55 }
56 #if defined(HAVE_KEIL_RTX)
57 #define sleep(t) os_dly_wait(t/1000+1) ;
58 #elif defined (WOLFSSL_CMSIS_RTOS)
59 #define sleep(t) osDelay(t/1000+1) ;
60 #endif
61
62 static int wolfssl_tcp_select(int sd, int timeout)
63 { return 0 ; }
64 #define tcp_select(sd,t) wolfssl_tcp_select(sd, t) /* avoid conflicting Keil TCP tcp_select */
65#elif defined(WOLFSSL_TIRTOS)
66 #include <string.h>
67 #include <netdb.h>
68 #include <sys/types.h>
69 #include <arpa/inet.h>
70 #include <sys/socket.h>
71 #include <ti/sysbios/knl/Task.h>
72 struct hostent {
73 char *h_name; /* official name of host */
74 char **h_aliases; /* alias list */
75 int h_addrtype; /* host address type */
76 int h_length; /* length of address */
77 char **h_addr_list; /* list of addresses from name server */
78 };
79 #define SOCKET_T int
80#elif defined(WOLFSSL_VXWORKS)
81 #include <hostLib.h>
82 #include <sockLib.h>
83 #include <arpa/inet.h>
84 #include <string.h>
85 #include <selectLib.h>
86 #include <sys/types.h>
87 #include <netinet/in.h>
88 #include <fcntl.h>
89 #include <sys/time.h>
90 #include <netdb.h>
91 #include <pthread.h>
92 #define SOCKET_T int
93#else
94 #include <string.h>
95 #include <sys/types.h>
96#ifndef WOLFSSL_LEANPSK
97 #include <unistd.h>
98 #include <netdb.h>
99 #include <netinet/in.h>
100 #include <netinet/tcp.h>
101 #include <arpa/inet.h>
102 #include <sys/ioctl.h>
103 #include <sys/time.h>
104 #include <sys/socket.h>
105 #include <pthread.h>
106 #include <fcntl.h>
107 #ifdef TEST_IPV6
108 #include <netdb.h>
109 #endif
110#endif
111 #define SOCKET_T int
112 #ifndef SO_NOSIGPIPE
113 #include <signal.h> /* ignore SIGPIPE */
114 #endif
115 #define SNPRINTF snprintf
116#endif /* USE_WINDOWS_API */
117
118#ifdef WOLFSSL_ASYNC_CRYPT
119 #include <wolfssl/wolfcrypt/async.h>
120#endif
121#ifdef HAVE_CAVIUM
122 #include <wolfssl/wolfcrypt/port/cavium/cavium_nitrox.h>
123#endif
124
125#ifdef _MSC_VER
126 /* disable conversion warning */
127 /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
128 #pragma warning(disable:4244 4996)
129#endif
130
131/* Buffer for benchmark tests */
132#ifndef TEST_BUFFER_SIZE
133#define TEST_BUFFER_SIZE 16384
134#endif
135
136#ifndef WOLFSSL_HAVE_MIN
137 #define WOLFSSL_HAVE_MIN
138 static INLINE word32 min(word32 a, word32 b)
139 {
140 return a > b ? b : a;
141 }
142#endif /* WOLFSSL_HAVE_MIN */
143
144/* Socket Handling */
145#ifndef WOLFSSL_SOCKET_INVALID
146#ifdef USE_WINDOWS_API
147 #define WOLFSSL_SOCKET_INVALID ((SOCKET_T)INVALID_SOCKET)
148#elif defined(WOLFSSL_TIRTOS)
149 #define WOLFSSL_SOCKET_INVALID ((SOCKET_T)-1)
150#else
151 #define WOLFSSL_SOCKET_INVALID (SOCKET_T)(0)
152#endif
153#endif /* WOLFSSL_SOCKET_INVALID */
154
155#ifndef WOLFSSL_SOCKET_IS_INVALID
156#if defined(USE_WINDOWS_API) || defined(WOLFSSL_TIRTOS)
157 #define WOLFSSL_SOCKET_IS_INVALID(s) ((SOCKET_T)(s) == WOLFSSL_SOCKET_INVALID)
158#else
159 #define WOLFSSL_SOCKET_IS_INVALID(s) ((SOCKET_T)(s) < WOLFSSL_SOCKET_INVALID)
160#endif
161#endif /* WOLFSSL_SOCKET_IS_INVALID */
162
163#if defined(__MACH__) || defined(USE_WINDOWS_API)
164 #ifndef _SOCKLEN_T
165 typedef int socklen_t;
166 #endif
167#endif
168
169
170/* HPUX doesn't use socklent_t for third parameter to accept, unless
171 _XOPEN_SOURCE_EXTENDED is defined */
172#if !defined(__hpux__) && !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_IAR_ARM)\
173 && !defined(WOLFSSL_ROWLEY_ARM) && !defined(WOLFSSL_KEIL_TCP_NET)
174 typedef socklen_t* ACCEPT_THIRD_T;
175#else
176 #if defined _XOPEN_SOURCE_EXTENDED
177 typedef socklen_t* ACCEPT_THIRD_T;
178 #else
179 typedef int* ACCEPT_THIRD_T;
180 #endif
181#endif
182
183
184#ifdef USE_WINDOWS_API
185 #define CloseSocket(s) closesocket(s)
186 #define StartTCP() { WSADATA wsd; WSAStartup(0x0002, &wsd); }
187#elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
188 #define CloseSocket(s) closesocket(s)
189 #define StartTCP()
190#else
191 #define CloseSocket(s) close(s)
192 #define StartTCP()
193#endif
194
195
196#ifdef SINGLE_THREADED
197 typedef unsigned int THREAD_RETURN;
198 typedef void* THREAD_TYPE;
199 #define WOLFSSL_THREAD
200#else
201 #if defined(_POSIX_THREADS) && !defined(__MINGW32__)
202 typedef void* THREAD_RETURN;
203 typedef pthread_t THREAD_TYPE;
204 #define WOLFSSL_THREAD
205 #define INFINITE -1
206 #define WAIT_OBJECT_0 0L
207 #elif defined(WOLFSSL_MDK_ARM)|| defined(WOLFSSL_KEIL_TCP_NET)
208 typedef unsigned int THREAD_RETURN;
209 typedef int THREAD_TYPE;
210 #define WOLFSSL_THREAD
211 #elif defined(WOLFSSL_TIRTOS)
212 typedef void THREAD_RETURN;
213 typedef Task_Handle THREAD_TYPE;
214 #define WOLFSSL_THREAD
215 #else
216 typedef unsigned int THREAD_RETURN;
217 typedef intptr_t THREAD_TYPE;
218 #define WOLFSSL_THREAD __stdcall
219 #endif
220#endif
221
222
223#ifdef TEST_IPV6
224 typedef struct sockaddr_in6 SOCKADDR_IN_T;
225 #define AF_INET_V AF_INET6
226#else
227 typedef struct sockaddr_in SOCKADDR_IN_T;
228 #define AF_INET_V AF_INET
229#endif
230
231
232#define SERVER_DEFAULT_VERSION 3
233#define SERVER_DTLS_DEFAULT_VERSION (-2)
234#define SERVER_INVALID_VERSION (-99)
235#define CLIENT_DEFAULT_VERSION 3
236#define CLIENT_DTLS_DEFAULT_VERSION (-2)
237#define CLIENT_INVALID_VERSION (-99)
238#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
239 #define DEFAULT_MIN_DHKEY_BITS 2048
240#else
241 #define DEFAULT_MIN_DHKEY_BITS 1024
242#endif
243#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
244 #define DEFAULT_MIN_RSAKEY_BITS 2048
245#else
246 #define DEFAULT_MIN_RSAKEY_BITS 1024
247#endif
248#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
249 #define DEFAULT_MIN_ECCKEY_BITS 256
250#else
251 #define DEFAULT_MIN_ECCKEY_BITS 224
252#endif
253
254/* all certs relative to wolfSSL home directory now */
255#if defined(WOLFSSL_NO_CURRDIR) || defined(WOLFSSL_MDK_SHELL)
256#define caCertFile "certs/ca-cert.pem"
257#define eccCertFile "certs/server-ecc.pem"
258#define eccKeyFile "certs/ecc-key.pem"
259#define svrCertFile "certs/server-cert.pem"
260#define svrKeyFile "certs/server-key.pem"
261#define cliCertFile "certs/client-cert.pem"
262#define cliKeyFile "certs/client-key.pem"
263#define ntruCertFile "certs/ntru-cert.pem"
264#define ntruKeyFile "certs/ntru-key.raw"
265#define dhParamFile "certs/dh2048.pem"
266#define cliEccKeyFile "certs/ecc-client-key.pem"
267#define cliEccCertFile "certs/client-ecc-cert.pem"
268#define caEccCertFile "certs/ca-ecc-cert/pem"
269#define crlPemDir "certs/crl"
270#ifdef HAVE_WNR
271 /* Whitewood netRandom default config file */
272 #define wnrConfig "wnr-example.conf"
273#endif
274#else
275#define caCertFile "./certs/ca-cert.pem"
276#define eccCertFile "./certs/server-ecc.pem"
277#define eccKeyFile "./certs/ecc-key.pem"
278#define svrCertFile "./certs/server-cert.pem"
279#define svrKeyFile "./certs/server-key.pem"
280#define cliCertFile "./certs/client-cert.pem"
281#define cliKeyFile "./certs/client-key.pem"
282#define ntruCertFile "./certs/ntru-cert.pem"
283#define ntruKeyFile "./certs/ntru-key.raw"
284#define dhParamFile "./certs/dh2048.pem"
285#define cliEccKeyFile "./certs/ecc-client-key.pem"
286#define cliEccCertFile "./certs/client-ecc-cert.pem"
287#define caEccCertFile "./certs/ca-ecc-cert.pem"
288#define crlPemDir "./certs/crl"
289#ifdef HAVE_WNR
290 /* Whitewood netRandom default config file */
291 #define wnrConfig "./wnr-example.conf"
292#endif
293#endif
294
295typedef struct tcp_ready {
296 word16 ready; /* predicate */
297 word16 port;
298 char* srfName; /* server ready file name */
299#if defined(_POSIX_THREADS) && !defined(__MINGW32__)
300 pthread_mutex_t mutex;
301 pthread_cond_t cond;
302#endif
303} tcp_ready;
304
305
306static INLINE void InitTcpReady(tcp_ready* ready)
307{
308 ready->ready = 0;
309 ready->port = 0;
310 ready->srfName = NULL;
311#ifdef SINGLE_THREADED
312#elif defined(_POSIX_THREADS) && !defined(__MINGW32__)
313 pthread_mutex_init(&ready->mutex, 0);
314 pthread_cond_init(&ready->cond, 0);
315#endif
316}
317
318
319static INLINE void FreeTcpReady(tcp_ready* ready)
320{
321#ifdef SINGLE_THREADED
322 (void)ready;
323#elif defined(_POSIX_THREADS) && !defined(__MINGW32__)
324 pthread_mutex_destroy(&ready->mutex);
325 pthread_cond_destroy(&ready->cond);
326#else
327 (void)ready;
328#endif
329}
330
331typedef WOLFSSL_METHOD* (*method_provider)(void);
332typedef void (*ctx_callback)(WOLFSSL_CTX* ctx);
333typedef void (*ssl_callback)(WOLFSSL* ssl);
334
335typedef struct callback_functions {
336 method_provider method;
337 ctx_callback ctx_ready;
338 ssl_callback ssl_ready;
339 ssl_callback on_result;
340} callback_functions;
341
342typedef struct func_args {
343 int argc;
344 char** argv;
345 int return_code;
346 tcp_ready* signal;
347 callback_functions *callbacks;
348} func_args;
349
350
351
352
353void wait_tcp_ready(func_args*);
354
355typedef THREAD_RETURN WOLFSSL_THREAD THREAD_FUNC(void*);
356
357void start_thread(THREAD_FUNC, func_args*, THREAD_TYPE*);
358void join_thread(THREAD_TYPE);
359
360/* wolfSSL */
361#ifndef TEST_IPV6
362 static const char* const wolfSSLIP = "127.0.0.1";
363#else
364 static const char* const wolfSSLIP = "::1";
365#endif
366static const word16 wolfSSLPort = 11111;
367
368
369#if defined(__GNUC__)
370 #define WC_NORETURN __attribute__((noreturn))
371#else
372 #define WC_NORETURN
373#endif
374
375static INLINE WC_NORETURN void err_sys(const char* msg)
376{
377 printf("wolfSSL error: %s\n", msg);
378
379#if !defined(__GNUC__)
380 /* scan-build (which pretends to be gnuc) can get confused and think the
381 * msg pointer can be null even when hardcoded and then it won't exit,
382 * making null pointer checks above the err_sys() call useless.
383 * We could just always exit() but some compilers will complain about no
384 * possible return, with gcc we know the attribute to handle that with
385 * WC_NORETURN. */
386 if (msg)
387#endif
388 {
389 exit(EXIT_FAILURE);
390 }
391}
392
393
394#define MY_EX_USAGE 2
395
396extern int myoptind;
397extern char* myoptarg;
398
399static INLINE int mygetopt(int argc, char** argv, const char* optstring)
400{
401 static char* next = NULL;
402
403 char c;
404 char* cp;
405
406 if (myoptind == 0)
407 next = NULL; /* we're starting new/over */
408
409 if (next == NULL || *next == '\0') {
410 if (myoptind == 0)
411 myoptind++;
412
413 if (myoptind >= argc || argv[myoptind][0] != '-' ||
414 argv[myoptind][1] == '\0') {
415 myoptarg = NULL;
416 if (myoptind < argc)
417 myoptarg = argv[myoptind];
418
419 return -1;
420 }
421
422 if (strcmp(argv[myoptind], "--") == 0) {
423 myoptind++;
424 myoptarg = NULL;
425
426 if (myoptind < argc)
427 myoptarg = argv[myoptind];
428
429 return -1;
430 }
431
432 next = argv[myoptind];
433 next++; /* skip - */
434 myoptind++;
435 }
436
437 c = *next++;
438 /* The C++ strchr can return a different value */
439 cp = (char*)strchr(optstring, c);
440
441 if (cp == NULL || c == ':')
442 return '?';
443
444 cp++;
445
446 if (*cp == ':') {
447 if (*next != '\0') {
448 myoptarg = next;
449 next = NULL;
450 }
451 else if (myoptind < argc) {
452 myoptarg = argv[myoptind];
453 myoptind++;
454 }
455 else
456 return '?';
457 }
458
459 return c;
460}
461
462
463#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
464
465static INLINE int PasswordCallBack(char* passwd, int sz, int rw, void* userdata)
466{
467 (void)rw;
468 (void)userdata;
469 strncpy(passwd, "yassl123", sz);
470 return 8;
471}
472
473#endif
474
475
476#if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS)
477
478static INLINE void ShowX509(WOLFSSL_X509* x509, const char* hdr)
479{
480 char* altName;
481 char* issuer;
482 char* subject;
483 byte serial[32];
484 int ret;
485 int sz = sizeof(serial);
486
487 if (x509 == NULL) {
488 printf("%s No Cert\n", hdr);
489 return;
490 }
491
492 issuer = wolfSSL_X509_NAME_oneline(
493 wolfSSL_X509_get_issuer_name(x509), 0, 0);
494 subject = wolfSSL_X509_NAME_oneline(
495 wolfSSL_X509_get_subject_name(x509), 0, 0);
496
497 printf("%s\n issuer : %s\n subject: %s\n", hdr, issuer, subject);
498
499 while ( (altName = wolfSSL_X509_get_next_altname(x509)) != NULL)
500 printf(" altname = %s\n", altName);
501
502 ret = wolfSSL_X509_get_serial_number(x509, serial, &sz);
503 if (ret == WOLFSSL_SUCCESS) {
504 int i;
505 int strLen;
506 char serialMsg[80];
507
508 /* testsuite has multiple threads writing to stdout, get output
509 message ready to write once */
510 strLen = sprintf(serialMsg, " serial number");
511 for (i = 0; i < sz; i++)
512 sprintf(serialMsg + strLen + (i*3), ":%02x ", serial[i]);
513 printf("%s\n", serialMsg);
514 }
515
516 XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
517 XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
518}
519
520#endif /* KEEP_PEER_CERT || SESSION_CERTS */
521
522#if defined(SESSION_CERTS) && defined(SHOW_CERTS)
523static INLINE void ShowX509Chain(WOLFSSL_X509_CHAIN* chain, int count,
524 const char* hdr)
525{
526 int i;
527 int length;
528 unsigned char buffer[3072];
529 WOLFSSL_X509* chainX509;
530
531 for (i = 0; i < count; i++) {
532 wolfSSL_get_chain_cert_pem(chain, i, buffer, sizeof(buffer), &length);
533 buffer[length] = 0;
534 printf("\n%s: %d has length %d data = \n%s\n", hdr, i, length, buffer);
535
536 chainX509 = wolfSSL_get_chain_X509(chain, i);
537 if (chainX509)
538 ShowX509(chainX509, hdr);
539 else
540 printf("get_chain_X509 failed\n");
541 wolfSSL_FreeX509(chainX509);
542 }
543}
544#endif
545
546static INLINE void showPeer(WOLFSSL* ssl)
547{
548 WOLFSSL_CIPHER* cipher;
549#ifdef HAVE_ECC
550 const char *name;
551#endif
552#ifndef NO_DH
553 int bits;
554#endif
555#ifdef KEEP_PEER_CERT
556 WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl);
557 if (peer)
558 ShowX509(peer, "peer's cert info:");
559 else
560 printf("peer has no cert!\n");
561 wolfSSL_FreeX509(peer);
562#endif
563#if defined(SHOW_CERTS) && defined(OPENSSL_EXTRA) && defined(KEEP_OUR_CERT)
564 ShowX509(wolfSSL_get_certificate(ssl), "our cert info:");
565 printf("Peer verify result = %lu\n", wolfSSL_get_verify_result(ssl));
566#endif /* SHOW_CERTS */
567 printf("SSL version is %s\n", wolfSSL_get_version(ssl));
568
569 cipher = wolfSSL_get_current_cipher(ssl);
570#ifdef HAVE_QSH
571 printf("SSL cipher suite is %s%s\n", (wolfSSL_isQSH(ssl))? "QSH:": "",
572 wolfSSL_CIPHER_get_name(cipher));
573#else
574 printf("SSL cipher suite is %s\n", wolfSSL_CIPHER_get_name(cipher));
575#endif
576#ifdef HAVE_ECC
577 if ((name = wolfSSL_get_curve_name(ssl)) != NULL)
578 printf("SSL curve name is %s\n", name);
579#endif
580#ifndef NO_DH
581 if ((bits = wolfSSL_GetDhKey_Sz(ssl)) > 0)
582 printf("SSL DH size is %d bits\n", bits);
583#endif
584 if (wolfSSL_session_reused(ssl))
585 printf("SSL reused session\n");
586#ifdef WOLFSSL_ALT_CERT_CHAINS
587 if (wolfSSL_is_peer_alt_cert_chain(ssl))
588 printf("Alternate cert chain used\n");
589#endif
590
591#if defined(SESSION_CERTS) && defined(SHOW_CERTS)
592 {
593 WOLFSSL_X509_CHAIN* chain;
594
595 chain = wolfSSL_get_peer_chain(ssl);
596 ShowX509Chain(chain, wolfSSL_get_chain_count(chain), "session cert");
597
598 #ifdef WOLFSSL_ALT_CERT_CHAINS
599 if (wolfSSL_is_peer_alt_cert_chain(ssl)) {
600 chain = wolfSSL_get_peer_alt_chain(ssl);
601 ShowX509Chain(chain, wolfSSL_get_chain_count(chain), "alt cert");
602 }
603 #endif
604 }
605#endif /* SESSION_CERTS && SHOW_CERTS */
606 (void)ssl;
607}
608
609
610static INLINE void build_addr(SOCKADDR_IN_T* addr, const char* peer,
611 word16 port, int udp, int sctp)
612{
613 int useLookup = 0;
614 (void)useLookup;
615 (void)udp;
616 (void)sctp;
617
618 if (addr == NULL)
619 err_sys("invalid argument to build_addr, addr is NULL");
620
621 memset(addr, 0, sizeof(SOCKADDR_IN_T));
622
623#ifndef TEST_IPV6
624 /* peer could be in human readable form */
625 if ( ((size_t)peer != INADDR_ANY) && isalpha((int)peer[0])) {
626 #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
627 int err;
628 struct hostent* entry = gethostbyname(peer, &err);
629 #elif defined(WOLFSSL_TIRTOS)
630 struct hostent* entry = DNSGetHostByName(peer);
631 #elif defined(WOLFSSL_VXWORKS)
632 struct hostent* entry = (struct hostent*)hostGetByName((char*)peer);
633 #else
634 struct hostent* entry = gethostbyname(peer);
635 #endif
636
637 if (entry) {
638 XMEMCPY(&addr->sin_addr.s_addr, entry->h_addr_list[0],
639 entry->h_length);
640 useLookup = 1;
641 }
642 else
643 err_sys("no entry for host");
644 }
645#endif
646
647
648#ifndef TEST_IPV6
649 #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
650 addr->sin_family = PF_INET;
651 #else
652 addr->sin_family = AF_INET_V;
653 #endif
654 addr->sin_port = XHTONS(port);
655 if ((size_t)peer == INADDR_ANY)
656 addr->sin_addr.s_addr = INADDR_ANY;
657 else {
658 if (!useLookup)
659 addr->sin_addr.s_addr = inet_addr(peer);
660 }
661#else
662 addr->sin6_family = AF_INET_V;
663 addr->sin6_port = XHTONS(port);
664 if (peer == INADDR_ANY)
665 addr->sin6_addr = in6addr_any;
666 else {
667 #ifdef HAVE_GETADDRINFO
668 struct addrinfo hints;
669 struct addrinfo* answer = NULL;
670 int ret;
671 char strPort[80];
672
673 memset(&hints, 0, sizeof(hints));
674
675 hints.ai_family = AF_INET_V;
676 if (udp) {
677 hints.ai_socktype = SOCK_DGRAM;
678 hints.ai_protocol = IPPROTO_UDP;
679 }
680 #ifdef WOLFSSL_SCTP
681 else if (sctp) {
682 hints.ai_socktype = SOCK_STREAM;
683 hints.ai_protocol = IPPROTO_SCTP;
684 }
685 #endif
686 else {
687 hints.ai_socktype = SOCK_STREAM;
688 hints.ai_protocol = IPPROTO_TCP;
689 }
690
691 SNPRINTF(strPort, sizeof(strPort), "%d", port);
692 strPort[79] = '\0';
693
694 ret = getaddrinfo(peer, strPort, &hints, &answer);
695 if (ret < 0 || answer == NULL)
696 err_sys("getaddrinfo failed");
697
698 XMEMCPY(addr, answer->ai_addr, answer->ai_addrlen);
699 freeaddrinfo(answer);
700 #else
701 printf("no ipv6 getaddrinfo, loopback only tests/examples\n");
702 addr->sin6_addr = in6addr_loopback;
703 #endif
704 }
705#endif
706}
707
708
709static INLINE void tcp_socket(SOCKET_T* sockfd, int udp, int sctp)
710{
711 (void)sctp;
712
713 if (udp)
714 *sockfd = socket(AF_INET_V, SOCK_DGRAM, IPPROTO_UDP);
715#ifdef WOLFSSL_SCTP
716 else if (sctp)
717 *sockfd = socket(AF_INET_V, SOCK_STREAM, IPPROTO_SCTP);
718#endif
719 else
720 *sockfd = socket(AF_INET_V, SOCK_STREAM, IPPROTO_TCP);
721
722 if(WOLFSSL_SOCKET_IS_INVALID(*sockfd)) {
723 err_sys("socket failed\n");
724 }
725
726#ifndef USE_WINDOWS_API
727#ifdef SO_NOSIGPIPE
728 {
729 int on = 1;
730 socklen_t len = sizeof(on);
731 int res = setsockopt(*sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, len);
732 if (res < 0)
733 err_sys("setsockopt SO_NOSIGPIPE failed\n");
734 }
735#elif defined(WOLFSSL_MDK_ARM) || defined (WOLFSSL_TIRTOS) ||\
736 defined(WOLFSSL_KEIL_TCP_NET)
737 /* nothing to define */
738#else /* no S_NOSIGPIPE */
739 signal(SIGPIPE, SIG_IGN);
740#endif /* S_NOSIGPIPE */
741
742#if defined(TCP_NODELAY)
743 if (!udp && !sctp)
744 {
745 int on = 1;
746 socklen_t len = sizeof(on);
747 int res = setsockopt(*sockfd, IPPROTO_TCP, TCP_NODELAY, &on, len);
748 if (res < 0)
749 err_sys("setsockopt TCP_NODELAY failed\n");
750 }
751#endif
752#endif /* USE_WINDOWS_API */
753}
754
755static INLINE void tcp_connect(SOCKET_T* sockfd, const char* ip, word16 port,
756 int udp, int sctp, WOLFSSL* ssl)
757{
758 SOCKADDR_IN_T addr;
759 build_addr(&addr, ip, port, udp, sctp);
760 if (udp) {
761 wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
762 }
763 tcp_socket(sockfd, udp, sctp);
764
765 if (!udp) {
766 if (connect(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
767 err_sys("tcp connect failed");
768 }
769}
770
771
772static INLINE void udp_connect(SOCKET_T* sockfd, void* addr, int addrSz)
773{
774 if (connect(*sockfd, (const struct sockaddr*)addr, addrSz) != 0)
775 err_sys("tcp connect failed");
776}
777
778
779enum {
780 TEST_SELECT_FAIL,
781 TEST_TIMEOUT,
782 TEST_RECV_READY,
783 TEST_ERROR_READY
784};
785
786
787#if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET) && \
788 !defined(WOLFSSL_TIRTOS)
789static INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
790{
791 fd_set recvfds, errfds;
792 SOCKET_T nfds = socketfd + 1;
793 struct timeval timeout = { (to_sec > 0) ? to_sec : 0, 0};
794 int result;
795
796 FD_ZERO(&recvfds);
797 FD_SET(socketfd, &recvfds);
798 FD_ZERO(&errfds);
799 FD_SET(socketfd, &errfds);
800
801 result = select(nfds, &recvfds, NULL, &errfds, &timeout);
802
803 if (result == 0)
804 return TEST_TIMEOUT;
805 else if (result > 0) {
806 if (FD_ISSET(socketfd, &recvfds))
807 return TEST_RECV_READY;
808 else if(FD_ISSET(socketfd, &errfds))
809 return TEST_ERROR_READY;
810 }
811
812 return TEST_SELECT_FAIL;
813}
814#elif defined(WOLFSSL_TIRTOS)
815static INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
816{
817 return TEST_RECV_READY;
818}
819#endif /* !WOLFSSL_MDK_ARM */
820
821
822static INLINE void tcp_listen(SOCKET_T* sockfd, word16* port, int useAnyAddr,
823 int udp, int sctp)
824{
825 SOCKADDR_IN_T addr;
826
827 /* don't use INADDR_ANY by default, firewall may block, make user switch
828 on */
829 build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), *port, udp, sctp);
830 tcp_socket(sockfd, udp, sctp);
831
832#if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\
833 && !defined(WOLFSSL_KEIL_TCP_NET)
834 {
835 int res, on = 1;
836 socklen_t len = sizeof(on);
837 res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
838 if (res < 0)
839 err_sys("setsockopt SO_REUSEADDR failed\n");
840 }
841#endif
842
843 if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
844 err_sys("tcp bind failed");
845 if (!udp) {
846 if (listen(*sockfd, 5) != 0)
847 err_sys("tcp listen failed");
848 }
849 #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_TIRTOS)
850 if (*port == 0) {
851 socklen_t len = sizeof(addr);
852 if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
853 #ifndef TEST_IPV6
854 *port = XNTOHS(addr.sin_port);
855 #else
856 *port = XNTOHS(addr.sin6_port);
857 #endif
858 }
859 }
860 #endif
861}
862
863
864#if 0
865static INLINE int udp_read_connect(SOCKET_T sockfd)
866{
867 SOCKADDR_IN_T cliaddr;
868 byte b[1500];
869 int n;
870 socklen_t len = sizeof(cliaddr);
871
872 n = (int)recvfrom(sockfd, (char*)b, sizeof(b), MSG_PEEK,
873 (struct sockaddr*)&cliaddr, &len);
874 if (n > 0) {
875 if (connect(sockfd, (const struct sockaddr*)&cliaddr,
876 sizeof(cliaddr)) != 0)
877 err_sys("udp connect failed");
878 }
879 else
880 err_sys("recvfrom failed");
881
882 return sockfd;
883}
884#endif
885
886static INLINE void udp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
887 int useAnyAddr, word16 port, func_args* args)
888{
889 SOCKADDR_IN_T addr;
890
891 (void)args;
892 build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), port, 1, 0);
893 tcp_socket(sockfd, 1, 0);
894
895
896#if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM) \
897 && !defined(WOLFSSL_KEIL_TCP_NET)
898 {
899 int res, on = 1;
900 socklen_t len = sizeof(on);
901 res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
902 if (res < 0)
903 err_sys("setsockopt SO_REUSEADDR failed\n");
904 }
905#endif
906
907 if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
908 err_sys("tcp bind failed");
909
910 #if (defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API)) && !defined(WOLFSSL_TIRTOS)
911 if (port == 0) {
912 socklen_t len = sizeof(addr);
913 if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
914 #ifndef TEST_IPV6
915 port = XNTOHS(addr.sin_port);
916 #else
917 port = XNTOHS(addr.sin6_port);
918 #endif
919 }
920 }
921 #endif
922
923#if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
924 /* signal ready to accept data */
925 {
926 tcp_ready* ready = args->signal;
927 pthread_mutex_lock(&ready->mutex);
928 ready->ready = 1;
929 ready->port = port;
930 pthread_cond_signal(&ready->cond);
931 pthread_mutex_unlock(&ready->mutex);
932 }
933#elif defined (WOLFSSL_TIRTOS)
934 /* Need mutex? */
935 tcp_ready* ready = args->signal;
936 ready->ready = 1;
937 ready->port = port;
938#endif
939
940 *clientfd = *sockfd;
941}
942
943static INLINE void tcp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
944 func_args* args, word16 port, int useAnyAddr,
945 int udp, int sctp, int ready_file, int do_listen)
946{
947 SOCKADDR_IN_T client;
948 socklen_t client_len = sizeof(client);
949 tcp_ready* ready = NULL;
950
951 (void) ready; /* Account for case when "ready" is not used */
952
953 if (udp) {
954 udp_accept(sockfd, clientfd, useAnyAddr, port, args);
955 return;
956 }
957
958 if(do_listen) {
959 tcp_listen(sockfd, &port, useAnyAddr, udp, sctp);
960
961 #if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
962 /* signal ready to tcp_accept */
963 if (args)
964 ready = args->signal;
965 if (ready) {
966 pthread_mutex_lock(&ready->mutex);
967 ready->ready = 1;
968 ready->port = port;
969 pthread_cond_signal(&ready->cond);
970 pthread_mutex_unlock(&ready->mutex);
971 }
972 #elif defined (WOLFSSL_TIRTOS)
973 /* Need mutex? */
974 if (args)
975 ready = args->signal;
976 if (ready) {
977 ready->ready = 1;
978 ready->port = port;
979 }
980 #endif
981
982 if (ready_file) {
983 #if !defined(NO_FILESYSTEM) || defined(FORCE_BUFFER_TEST)
984 FILE* srf = NULL;
985 if (args)
986 ready = args->signal;
987
988 if (ready) {
989 srf = fopen(ready->srfName, "w");
990
991 if (srf) {
992 /* let's write port sever is listening on to ready file
993 external monitor can then do ephemeral ports by passing
994 -p 0 to server on supported platforms with -R ready_file
995 client can then wait for existence of ready_file and see
996 which port the server is listening on. */
997 fprintf(srf, "%d\n", (int)port);
998 fclose(srf);
999 }
1000 }
1001 #endif
1002 }
1003 }
1004
1005 *clientfd = accept(*sockfd, (struct sockaddr*)&client,
1006 (ACCEPT_THIRD_T)&client_len);
1007 if(WOLFSSL_SOCKET_IS_INVALID(*clientfd)) {
1008 err_sys("tcp accept failed");
1009 }
1010}
1011
1012
1013static INLINE void tcp_set_nonblocking(SOCKET_T* sockfd)
1014{
1015 #ifdef USE_WINDOWS_API
1016 unsigned long blocking = 1;
1017 int ret = ioctlsocket(*sockfd, FIONBIO, &blocking);
1018 if (ret == SOCKET_ERROR)
1019 err_sys("ioctlsocket failed");
1020 #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) \
1021 || defined (WOLFSSL_TIRTOS)|| defined(WOLFSSL_VXWORKS)
1022 /* non blocking not supported, for now */
1023 #else
1024 int flags = fcntl(*sockfd, F_GETFL, 0);
1025 if (flags < 0)
1026 err_sys("fcntl get failed");
1027 flags = fcntl(*sockfd, F_SETFL, flags | O_NONBLOCK);
1028 if (flags < 0)
1029 err_sys("fcntl set failed");
1030 #endif
1031}
1032
1033
1034#ifndef NO_PSK
1035
1036/* identity is OpenSSL testing default for openssl s_client, keep same */
1037static const char* kIdentityStr = "Client_identity";
1038
1039static INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint,
1040 char* identity, unsigned int id_max_len, unsigned char* key,
1041 unsigned int key_max_len)
1042{
1043 (void)ssl;
1044 (void)hint;
1045 (void)key_max_len;
1046
1047 /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
1048 strncpy(identity, kIdentityStr, id_max_len);
1049
1050 /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
1051 unsigned binary */
1052 key[0] = 26;
1053 key[1] = 43;
1054 key[2] = 60;
1055 key[3] = 77;
1056
1057 return 4; /* length of key in octets or 0 for error */
1058}
1059
1060
1061static INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identity,
1062 unsigned char* key, unsigned int key_max_len)
1063{
1064 (void)ssl;
1065 (void)key_max_len;
1066
1067 /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
1068 if (strncmp(identity, kIdentityStr, strlen(kIdentityStr)) != 0)
1069 return 0;
1070
1071 /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
1072 unsigned binary */
1073 key[0] = 26;
1074 key[1] = 43;
1075 key[2] = 60;
1076 key[3] = 77;
1077
1078 return 4; /* length of key in octets or 0 for error */
1079}
1080
1081#endif /* NO_PSK */
1082
1083
1084#if defined(WOLFSSL_USER_CURRTIME)
1085 extern double current_time(int reset);
1086
1087#elif defined(USE_WINDOWS_API)
1088
1089 #define WIN32_LEAN_AND_MEAN
1090 #include <windows.h>
1091
1092 static INLINE double current_time(int reset)
1093 {
1094 static int init = 0;
1095 static LARGE_INTEGER freq;
1096
1097 LARGE_INTEGER count;
1098
1099 if (!init) {
1100 QueryPerformanceFrequency(&freq);
1101 init = 1;
1102 }
1103
1104 QueryPerformanceCounter(&count);
1105
1106 (void)reset;
1107 return (double)count.QuadPart / freq.QuadPart;
1108 }
1109
1110#elif defined(WOLFSSL_TIRTOS)
1111 extern double current_time();
1112#else
1113
1114#if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET)
1115 #include <sys/time.h>
1116
1117 static INLINE double current_time(int reset)
1118 {
1119 struct timeval tv;
1120 gettimeofday(&tv, 0);
1121 (void)reset;
1122
1123 return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
1124 }
1125#else
1126 extern double current_time(int reset);
1127#endif
1128#endif /* USE_WINDOWS_API */
1129
1130
1131#if !defined(NO_CERTS)
1132 #if !defined(NO_FILESYSTEM) || \
1133 (defined(NO_FILESYSTEM) && defined(FORCE_BUFFER_TEST))
1134
1135 /* reads file size, allocates buffer, reads into buffer, returns buffer */
1136 static INLINE int load_file(const char* fname, byte** buf, size_t* bufLen)
1137 {
1138 int ret;
1139 long int fileSz;
1140 FILE* file;
1141
1142 if (fname == NULL || buf == NULL || bufLen == NULL)
1143 return BAD_FUNC_ARG;
1144
1145 /* set defaults */
1146 *buf = NULL;
1147 *bufLen = 0;
1148
1149 /* open file (read-only binary) */
1150 file = fopen(fname, "rb");
1151 if (!file) {
1152 printf("Error loading %s\n", fname);
1153 return BAD_PATH_ERROR;
1154 }
1155
1156 fseek(file, 0, SEEK_END);
1157 fileSz = (int)ftell(file);
1158 rewind(file);
1159 if (fileSz > 0) {
1160 *bufLen = (size_t)fileSz;
1161 *buf = (byte*)malloc(*bufLen);
1162 if (*buf == NULL) {
1163 ret = MEMORY_E;
1164 printf("Error allocating %lu bytes\n", (unsigned long)*bufLen);
1165 }
1166 else {
1167 size_t readLen = fread(*buf, *bufLen, 1, file);
1168
1169 /* check response code */
1170 ret = (readLen > 0) ? 0 : -1;
1171 }
1172 }
1173 else {
1174 ret = BUFFER_E;
1175 }
1176 fclose(file);
1177
1178 return ret;
1179 }
1180
1181 enum {
1182 WOLFSSL_CA = 1,
1183 WOLFSSL_CERT = 2,
1184 WOLFSSL_KEY = 3,
1185 WOLFSSL_CERT_CHAIN = 4,
1186 };
1187
1188 static INLINE void load_buffer(WOLFSSL_CTX* ctx, const char* fname, int type)
1189 {
1190 int format = WOLFSSL_FILETYPE_PEM;
1191 byte* buff = NULL;
1192 size_t sz = 0;
1193
1194 if (load_file(fname, &buff, &sz) != 0) {
1195 err_sys("can't open file for buffer load "
1196 "Please run from wolfSSL home directory if not");
1197 }
1198
1199 /* determine format */
1200 if (strstr(fname, ".der"))
1201 format = WOLFSSL_FILETYPE_ASN1;
1202
1203 if (type == WOLFSSL_CA) {
1204 if (wolfSSL_CTX_load_verify_buffer(ctx, buff, (long)sz, format)
1205 != WOLFSSL_SUCCESS)
1206 err_sys("can't load buffer ca file");
1207 }
1208 else if (type == WOLFSSL_CERT) {
1209 if (wolfSSL_CTX_use_certificate_buffer(ctx, buff, (long)sz,
1210 format) != WOLFSSL_SUCCESS)
1211 err_sys("can't load buffer cert file");
1212 }
1213 else if (type == WOLFSSL_KEY) {
1214 if (wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, (long)sz,
1215 format) != WOLFSSL_SUCCESS)
1216 err_sys("can't load buffer key file");
1217 }
1218 else if (type == WOLFSSL_CERT_CHAIN) {
1219 if (wolfSSL_CTX_use_certificate_chain_buffer_format(ctx, buff,
1220 (long)sz, format) != WOLFSSL_SUCCESS)
1221 err_sys("can't load cert chain buffer");
1222 }
1223
1224 if (buff)
1225 free(buff);
1226 }
1227 #endif /* !NO_FILESYSTEM || (NO_FILESYSTEM && FORCE_BUFFER_TEST) */
1228#endif /* !NO_CERTS */
1229
1230static INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store)
1231{
1232 char buffer[WOLFSSL_MAX_ERROR_SZ];
1233#ifdef OPENSSL_EXTRA
1234 WOLFSSL_X509* peer;
1235#endif
1236 (void)preverify;
1237
1238 printf("In verification callback, error = %d, %s\n", store->error,
1239 wolfSSL_ERR_error_string(store->error, buffer));
1240#ifdef OPENSSL_EXTRA
1241 peer = store->current_cert;
1242 if (peer) {
1243 char* issuer = wolfSSL_X509_NAME_oneline(
1244 wolfSSL_X509_get_issuer_name(peer), 0, 0);
1245 char* subject = wolfSSL_X509_NAME_oneline(
1246 wolfSSL_X509_get_subject_name(peer), 0, 0);
1247 printf("\tPeer's cert info:\n issuer : %s\n subject: %s\n", issuer,
1248 subject);
1249 XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
1250 XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
1251 }
1252 else
1253 printf("\tPeer has no cert!\n");
1254#else
1255 printf("\tPeer certs: %d\n", store->totalCerts);
1256 #ifdef SHOW_CERTS
1257 { int i;
1258 for (i=0; i<store->totalCerts; i++) {
1259 WOLFSSL_BUFFER_INFO* cert = &store->certs[i];
1260 printf("\t\tCert %d: Ptr %p, Len %u\n", i, cert->buffer, cert->length);
1261 }
1262 }
1263 #endif
1264#endif
1265
1266 printf("\tSubject's domain name is %s\n", store->domain);
1267
1268 printf("\tAllowing to continue anyway (shouldn't do this, EVER!!!)\n");
1269 return 1;
1270}
1271
1272
1273static INLINE int myDateCb(int preverify, WOLFSSL_X509_STORE_CTX* store)
1274{
1275 char buffer[WOLFSSL_MAX_ERROR_SZ];
1276 (void)preverify;
1277
1278 printf("In verification callback, error = %d, %s\n", store->error,
1279 wolfSSL_ERR_error_string(store->error, buffer));
1280 printf("Subject's domain name is %s\n", store->domain);
1281
1282 if (store->error == ASN_BEFORE_DATE_E || store->error == ASN_AFTER_DATE_E) {
1283 printf("Overriding cert date error as example for bad clock testing\n");
1284 return 1;
1285 }
1286 printf("Cert error is not date error, not overriding\n");
1287
1288 return 0;
1289}
1290
1291
1292#ifdef HAVE_CRL
1293
1294static INLINE void CRL_CallBack(const char* url)
1295{
1296 printf("CRL callback url = %s\n", url);
1297}
1298
1299#endif
1300
1301#ifndef NO_DH
1302static INLINE void SetDH(WOLFSSL* ssl)
1303{
1304 /* dh1024 p */
1305 static unsigned char p[] =
1306 {
1307 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
1308 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
1309 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
1310 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
1311 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
1312 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
1313 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
1314 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
1315 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
1316 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
1317 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
1318 };
1319
1320 /* dh1024 g */
1321 static unsigned char g[] =
1322 {
1323 0x02,
1324 };
1325
1326 wolfSSL_SetTmpDH(ssl, p, sizeof(p), g, sizeof(g));
1327}
1328
1329static INLINE void SetDHCtx(WOLFSSL_CTX* ctx)
1330{
1331 /* dh1024 p */
1332 static unsigned char p[] =
1333 {
1334 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
1335 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
1336 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
1337 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
1338 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
1339 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
1340 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
1341 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
1342 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
1343 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
1344 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
1345 };
1346
1347 /* dh1024 g */
1348 static unsigned char g[] =
1349 {
1350 0x02,
1351 };
1352
1353 wolfSSL_CTX_SetTmpDH(ctx, p, sizeof(p), g, sizeof(g));
1354}
1355#endif /* NO_DH */
1356
1357#ifndef NO_CERTS
1358
1359static INLINE void CaCb(unsigned char* der, int sz, int type)
1360{
1361 (void)der;
1362 printf("Got CA cache add callback, derSz = %d, type = %d\n", sz, type);
1363}
1364
1365#endif /* !NO_CERTS */
1366
1367
1368/* Wolf Root Directory Helper */
1369/* KEIL-RL File System does not support relative directory */
1370#if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_FS) && !defined(WOLFSSL_TIRTOS)
1371 /* Maximum depth to search for WolfSSL root */
1372 #define MAX_WOLF_ROOT_DEPTH 5
1373
1374 static INLINE int ChangeToWolfRoot(void)
1375 {
1376 #if !defined(NO_FILESYSTEM) || defined(FORCE_BUFFER_TEST)
1377 int depth, res;
1378 FILE* file;
1379 for(depth = 0; depth <= MAX_WOLF_ROOT_DEPTH; depth++) {
1380 file = fopen(ntruKeyFile, "rb");
1381 if (file != NULL) {
1382 fclose(file);
1383 return depth;
1384 }
1385 #ifdef USE_WINDOWS_API
1386 res = SetCurrentDirectoryA("..\\");
1387 #else
1388 res = chdir("../");
1389 #endif
1390 if (res < 0) {
1391 printf("chdir to ../ failed!\n");
1392 break;
1393 }
1394 }
1395
1396 err_sys("wolf root not found");
1397 return -1;
1398 #else
1399 return 0;
1400 #endif
1401 }
1402#endif /* !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_FS) && !defined(WOLFSSL_TIRTOS) */
1403
1404#ifdef HAVE_STACK_SIZE
1405
1406typedef THREAD_RETURN WOLFSSL_THREAD (*thread_func)(void* args);
1407#define STACK_CHECK_VAL 0x01
1408
1409static INLINE int StackSizeCheck(func_args* args, thread_func tf)
1410{
1411 int ret, i, used;
1412 void* status;
1413 unsigned char* myStack = NULL;
1414 int stackSize = 1024*128;
1415 pthread_attr_t myAttr;
1416 pthread_t threadId;
1417
1418#ifdef PTHREAD_STACK_MIN
1419 if (stackSize < PTHREAD_STACK_MIN)
1420 stackSize = PTHREAD_STACK_MIN;
1421#endif
1422
1423 ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize);
1424 if (ret != 0 || myStack == NULL)
1425 err_sys("posix_memalign failed\n");
1426
1427 XMEMSET(myStack, STACK_CHECK_VAL, stackSize);
1428
1429 ret = pthread_attr_init(&myAttr);
1430 if (ret != 0)
1431 err_sys("attr_init failed");
1432
1433 ret = pthread_attr_setstack(&myAttr, myStack, stackSize);
1434 if (ret != 0)
1435 err_sys("attr_setstackaddr failed");
1436
1437 ret = pthread_create(&threadId, &myAttr, tf, args);
1438 if (ret != 0) {
1439 perror("pthread_create failed");
1440 exit(EXIT_FAILURE);
1441 }
1442
1443 ret = pthread_join(threadId, &status);
1444 if (ret != 0)
1445 err_sys("pthread_join failed");
1446
1447 for (i = 0; i < stackSize; i++) {
1448 if (myStack[i] != STACK_CHECK_VAL) {
1449 break;
1450 }
1451 }
1452
1453 free(myStack);
1454
1455 used = stackSize - i;
1456 printf("stack used = %d\n", used);
1457
1458 return (int)((size_t)status);
1459}
1460
1461
1462#endif /* HAVE_STACK_SIZE */
1463
1464
1465#ifdef STACK_TRAP
1466
1467/* good settings
1468 --enable-debug --disable-shared C_EXTRA_FLAGS="-DUSER_TIME -DTFM_TIMING_RESISTANT -DPOSITIVE_EXP_ONLY -DSTACK_TRAP"
1469
1470*/
1471
1472#ifdef HAVE_STACK_SIZE
1473 /* client only for now, setrlimit will fail if pthread_create() called */
1474 /* STACK_SIZE does pthread_create() on client */
1475 #error "can't use STACK_TRAP with STACK_SIZE, setrlimit will fail"
1476#endif /* HAVE_STACK_SIZE */
1477
1478static INLINE void StackTrap(void)
1479{
1480 struct rlimit rl;
1481 if (getrlimit(RLIMIT_STACK, &rl) != 0)
1482 err_sys("getrlimit failed");
1483 printf("rlim_cur = %llu\n", rl.rlim_cur);
1484 rl.rlim_cur = 1024*21; /* adjust trap size here */
1485 if (setrlimit(RLIMIT_STACK, &rl) != 0) {
1486 perror("setrlimit");
1487 err_sys("setrlimit failed");
1488 }
1489}
1490
1491#else /* STACK_TRAP */
1492
1493static INLINE void StackTrap(void)
1494{
1495}
1496
1497#endif /* STACK_TRAP */
1498
1499
1500#ifdef ATOMIC_USER
1501
1502/* Atomic Encrypt Context example */
1503typedef struct AtomicEncCtx {
1504 int keySetup; /* have we done key setup yet */
1505 Aes aes; /* for aes example */
1506} AtomicEncCtx;
1507
1508
1509/* Atomic Decrypt Context example */
1510typedef struct AtomicDecCtx {
1511 int keySetup; /* have we done key setup yet */
1512 Aes aes; /* for aes example */
1513} AtomicDecCtx;
1514
1515
1516static INLINE int myMacEncryptCb(WOLFSSL* ssl, unsigned char* macOut,
1517 const unsigned char* macIn, unsigned int macInSz, int macContent,
1518 int macVerify, unsigned char* encOut, const unsigned char* encIn,
1519 unsigned int encSz, void* ctx)
1520{
1521 int ret;
1522 Hmac hmac;
1523 byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
1524 AtomicEncCtx* encCtx = (AtomicEncCtx*)ctx;
1525 const char* tlsStr = "TLS";
1526
1527 /* example supports (d)tls aes */
1528 if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
1529 printf("myMacEncryptCb not using AES\n");
1530 return -1;
1531 }
1532
1533 if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
1534 printf("myMacEncryptCb not using (D)TLS\n");
1535 return -1;
1536 }
1537
1538 /* hmac, not needed if aead mode */
1539 wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
1540
1541 ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
1542 wolfSSL_GetMacSecret(ssl, macVerify), wolfSSL_GetHmacSize(ssl));
1543 if (ret != 0)
1544 return ret;
1545 ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
1546 if (ret != 0)
1547 return ret;
1548 ret = wc_HmacUpdate(&hmac, macIn, macInSz);
1549 if (ret != 0)
1550 return ret;
1551 ret = wc_HmacFinal(&hmac, macOut);
1552 if (ret != 0)
1553 return ret;
1554
1555
1556 /* encrypt setup on first time */
1557 if (encCtx->keySetup == 0) {
1558 int keyLen = wolfSSL_GetKeySize(ssl);
1559 const byte* key;
1560 const byte* iv;
1561
1562 if (wolfSSL_GetSide(ssl) == WOLFSSL_CLIENT_END) {
1563 key = wolfSSL_GetClientWriteKey(ssl);
1564 iv = wolfSSL_GetClientWriteIV(ssl);
1565 }
1566 else {
1567 key = wolfSSL_GetServerWriteKey(ssl);
1568 iv = wolfSSL_GetServerWriteIV(ssl);
1569 }
1570
1571 ret = wc_AesSetKey(&encCtx->aes, key, keyLen, iv, AES_ENCRYPTION);
1572 if (ret != 0) {
1573 printf("AesSetKey failed in myMacEncryptCb\n");
1574 return ret;
1575 }
1576 encCtx->keySetup = 1;
1577 }
1578
1579 /* encrypt */
1580 return wc_AesCbcEncrypt(&encCtx->aes, encOut, encIn, encSz);
1581}
1582
1583
1584static INLINE int myDecryptVerifyCb(WOLFSSL* ssl,
1585 unsigned char* decOut, const unsigned char* decIn,
1586 unsigned int decSz, int macContent, int macVerify,
1587 unsigned int* padSz, void* ctx)
1588{
1589 AtomicDecCtx* decCtx = (AtomicDecCtx*)ctx;
1590 int ret = 0;
1591 int macInSz = 0;
1592 int ivExtra = 0;
1593 int digestSz = wolfSSL_GetHmacSize(ssl);
1594 unsigned int pad = 0;
1595 unsigned int padByte = 0;
1596 Hmac hmac;
1597 byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
1598 byte verify[MAX_DIGEST_SIZE];
1599 const char* tlsStr = "TLS";
1600
1601 /* example supports (d)tls aes */
1602 if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
1603 printf("myMacEncryptCb not using AES\n");
1604 return -1;
1605 }
1606
1607 if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
1608 printf("myMacEncryptCb not using (D)TLS\n");
1609 return -1;
1610 }
1611
1612 /*decrypt */
1613 if (decCtx->keySetup == 0) {
1614 int keyLen = wolfSSL_GetKeySize(ssl);
1615 const byte* key;
1616 const byte* iv;
1617
1618 /* decrypt is from other side (peer) */
1619 if (wolfSSL_GetSide(ssl) == WOLFSSL_SERVER_END) {
1620 key = wolfSSL_GetClientWriteKey(ssl);
1621 iv = wolfSSL_GetClientWriteIV(ssl);
1622 }
1623 else {
1624 key = wolfSSL_GetServerWriteKey(ssl);
1625 iv = wolfSSL_GetServerWriteIV(ssl);
1626 }
1627
1628 ret = wc_AesSetKey(&decCtx->aes, key, keyLen, iv, AES_DECRYPTION);
1629 if (ret != 0) {
1630 printf("AesSetKey failed in myDecryptVerifyCb\n");
1631 return ret;
1632 }
1633 decCtx->keySetup = 1;
1634 }
1635
1636 /* decrypt */
1637 ret = wc_AesCbcDecrypt(&decCtx->aes, decOut, decIn, decSz);
1638 if (ret != 0)
1639 return ret;
1640
1641 if (wolfSSL_GetCipherType(ssl) == WOLFSSL_AEAD_TYPE) {
1642 *padSz = wolfSSL_GetAeadMacSize(ssl);
1643 return 0; /* hmac, not needed if aead mode */
1644 }
1645
1646 if (wolfSSL_GetCipherType(ssl) == WOLFSSL_BLOCK_TYPE) {
1647 pad = *(decOut + decSz - 1);
1648 padByte = 1;
1649 if (wolfSSL_IsTLSv1_1(ssl))
1650 ivExtra = wolfSSL_GetCipherBlockSize(ssl);
1651 }
1652
1653 *padSz = wolfSSL_GetHmacSize(ssl) + pad + padByte;
1654 macInSz = decSz - ivExtra - digestSz - pad - padByte;
1655
1656 wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
1657
1658 ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
1659 wolfSSL_GetMacSecret(ssl, macVerify), digestSz);
1660 if (ret != 0)
1661 return ret;
1662 ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
1663 if (ret != 0)
1664 return ret;
1665 ret = wc_HmacUpdate(&hmac, decOut + ivExtra, macInSz);
1666 if (ret != 0)
1667 return ret;
1668 ret = wc_HmacFinal(&hmac, verify);
1669 if (ret != 0)
1670 return ret;
1671
1672 if (XMEMCMP(verify, decOut + decSz - digestSz - pad - padByte,
1673 digestSz) != 0) {
1674 printf("myDecryptVerify verify failed\n");
1675 return -1;
1676 }
1677
1678 return ret;
1679}
1680
1681
1682static INLINE void SetupAtomicUser(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
1683{
1684 AtomicEncCtx* encCtx;
1685 AtomicDecCtx* decCtx;
1686
1687 encCtx = (AtomicEncCtx*)malloc(sizeof(AtomicEncCtx));
1688 if (encCtx == NULL)
1689 err_sys("AtomicEncCtx malloc failed");
1690 memset(encCtx, 0, sizeof(AtomicEncCtx));
1691
1692 decCtx = (AtomicDecCtx*)malloc(sizeof(AtomicDecCtx));
1693 if (decCtx == NULL) {
1694 free(encCtx);
1695 err_sys("AtomicDecCtx malloc failed");
1696 }
1697 memset(decCtx, 0, sizeof(AtomicDecCtx));
1698
1699 wolfSSL_CTX_SetMacEncryptCb(ctx, myMacEncryptCb);
1700 wolfSSL_SetMacEncryptCtx(ssl, encCtx);
1701
1702 wolfSSL_CTX_SetDecryptVerifyCb(ctx, myDecryptVerifyCb);
1703 wolfSSL_SetDecryptVerifyCtx(ssl, decCtx);
1704}
1705
1706
1707static INLINE void FreeAtomicUser(WOLFSSL* ssl)
1708{
1709 AtomicEncCtx* encCtx = (AtomicEncCtx*)wolfSSL_GetMacEncryptCtx(ssl);
1710 AtomicDecCtx* decCtx = (AtomicDecCtx*)wolfSSL_GetDecryptVerifyCtx(ssl);
1711
1712 free(decCtx);
1713 free(encCtx);
1714}
1715
1716#endif /* ATOMIC_USER */
1717
1718#ifdef WOLFSSL_STATIC_MEMORY
1719static INLINE int wolfSSL_PrintStats(WOLFSSL_MEM_STATS* stats)
1720{
1721 word16 i;
1722
1723 if (stats == NULL) {
1724 return 0;
1725 }
1726
1727 /* print to stderr so is on the same pipe as WOLFSSL_DEBUG */
1728 fprintf(stderr, "Total mallocs = %d\n", stats->totalAlloc);
1729 fprintf(stderr, "Total frees = %d\n", stats->totalFr);
1730 fprintf(stderr, "Current mallocs = %d\n", stats->curAlloc);
1731 fprintf(stderr, "Available IO = %d\n", stats->avaIO);
1732 fprintf(stderr, "Max con. handshakes = %d\n", stats->maxHa);
1733 fprintf(stderr, "Max con. IO = %d\n", stats->maxIO);
1734 fprintf(stderr, "State of memory blocks: size : available \n");
1735 for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
1736 fprintf(stderr, " : %d\t : %d\n", stats->blockSz[i],
1737 stats->avaBlock[i]);
1738 }
1739
1740 return 1;
1741}
1742#endif /* WOLFSSL_STATIC_MEMORY */
1743
1744#ifdef HAVE_PK_CALLBACKS
1745
1746#ifdef HAVE_ECC
1747
1748static INLINE int myEccSign(WOLFSSL* ssl, const byte* in, word32 inSz,
1749 byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
1750{
1751 WC_RNG rng;
1752 int ret;
1753 word32 idx = 0;
1754 ecc_key myKey;
1755
1756 (void)ssl;
1757 (void)ctx;
1758
1759 ret = wc_InitRng(&rng);
1760 if (ret != 0)
1761 return ret;
1762
1763 ret = wc_ecc_init(&myKey);
1764 if (ret == 0) {
1765 ret = wc_EccPrivateKeyDecode(key, &idx, &myKey, keySz);
1766 if (ret == 0)
1767 ret = wc_ecc_sign_hash(in, inSz, out, outSz, &rng, &myKey);
1768 wc_ecc_free(&myKey);
1769 }
1770 wc_FreeRng(&rng);
1771
1772 return ret;
1773}
1774
1775
1776static INLINE int myEccVerify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
1777 const byte* hash, word32 hashSz, const byte* key, word32 keySz,
1778 int* result, void* ctx)
1779{
1780 int ret;
1781 ecc_key myKey;
1782
1783 (void)ssl;
1784 (void)ctx;
1785
1786 ret = wc_ecc_init(&myKey);
1787 if (ret == 0) {
1788 ret = wc_ecc_import_x963(key, keySz, &myKey);
1789 if (ret == 0)
1790 ret = wc_ecc_verify_hash(sig, sigSz, hash, hashSz, result, &myKey);
1791 wc_ecc_free(&myKey);
1792 }
1793
1794 return ret;
1795}
1796
1797static INLINE int myEccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey,
1798 unsigned char* pubKeyDer, unsigned int* pubKeySz,
1799 unsigned char* out, unsigned int* outlen,
1800 int side, void* ctx)
1801{
1802 int ret;
1803 ecc_key* privKey = NULL;
1804 ecc_key* pubKey = NULL;
1805 ecc_key tmpKey;
1806
1807 (void)ssl;
1808 (void)ctx;
1809
1810 ret = wc_ecc_init(&tmpKey);
1811 if (ret != 0) {
1812 return ret;
1813 }
1814
1815 /* for client: create and export public key */
1816 if (side == WOLFSSL_CLIENT_END) {
1817 WC_RNG rng;
1818
1819 privKey = &tmpKey;
1820 pubKey = otherKey;
1821
1822 ret = wc_InitRng(&rng);
1823 if (ret == 0) {
1824 ret = wc_ecc_make_key_ex(&rng, 0, privKey, otherKey->dp->id);
1825 #ifdef WOLFSSL_ASYNC_CRYPT
1826 if (ret == WC_PENDING_E) {
1827 ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_NONE);
1828 }
1829 #endif
1830 if (ret == 0)
1831 ret = wc_ecc_export_x963(privKey, pubKeyDer, pubKeySz);
1832 wc_FreeRng(&rng);
1833 }
1834 }
1835
1836 /* for server: import public key */
1837 else if (side == WOLFSSL_SERVER_END) {
1838 privKey = otherKey;
1839 pubKey = &tmpKey;
1840
1841 ret = wc_ecc_import_x963_ex(pubKeyDer, *pubKeySz, pubKey,
1842 otherKey->dp->id);
1843 }
1844 else {
1845 ret = BAD_FUNC_ARG;
1846 }
1847
1848 /* generate shared secret and return it */
1849 if (ret == 0) {
1850 ret = wc_ecc_shared_secret(privKey, pubKey, out, outlen);
1851
1852 #ifdef WOLFSSL_ASYNC_CRYPT
1853 if (ret == WC_PENDING_E) {
1854 ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
1855 }
1856 #endif
1857 }
1858
1859 wc_ecc_free(&tmpKey);
1860
1861 return ret;
1862}
1863
1864#ifdef HAVE_ED25519
1865static INLINE int myEd25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
1866 byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
1867{
1868 int ret;
1869 word32 idx = 0;
1870 ed25519_key myKey;
1871
1872 (void)ssl;
1873 (void)ctx;
1874
1875 ret = wc_ed25519_init(&myKey);
1876 if (ret == 0) {
1877 ret = wc_Ed25519PrivateKeyDecode(key, &idx, &myKey, keySz);
1878 if (ret == 0)
1879 ret = wc_ed25519_sign_msg(in, inSz, out, outSz, &myKey);
1880 wc_ed25519_free(&myKey);
1881 }
1882
1883 return ret;
1884}
1885
1886
1887static INLINE int myEd25519Verify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
1888 const byte* msg, word32 msgSz, const byte* key, word32 keySz,
1889 int* result, void* ctx)
1890{
1891 int ret;
1892 ed25519_key myKey;
1893
1894 (void)ssl;
1895 (void)ctx;
1896
1897 ret = wc_ed25519_init(&myKey);
1898 if (ret == 0) {
1899 ret = wc_ed25519_import_public(key, keySz, &myKey);
1900 if (ret == 0) {
1901 ret = wc_ed25519_verify_msg(sig, sigSz, msg, msgSz, result, &myKey);
1902 }
1903 wc_ed25519_free(&myKey);
1904 }
1905
1906 return ret;
1907}
1908#endif /* HAVE_ED25519 */
1909
1910#ifdef HAVE_CURVE25519
1911static INLINE int myX25519SharedSecret(WOLFSSL* ssl, curve25519_key* otherKey,
1912 unsigned char* pubKeyDer, unsigned int* pubKeySz,
1913 unsigned char* out, unsigned int* outlen,
1914 int side, void* ctx)
1915{
1916 int ret;
1917 curve25519_key* privKey = NULL;
1918 curve25519_key* pubKey = NULL;
1919 curve25519_key tmpKey;
1920
1921 (void)ssl;
1922 (void)ctx;
1923
1924 ret = wc_curve25519_init(&tmpKey);
1925 if (ret != 0) {
1926 return ret;
1927 }
1928
1929 /* for client: create and export public key */
1930 if (side == WOLFSSL_CLIENT_END) {
1931 WC_RNG rng;
1932
1933 privKey = &tmpKey;
1934 pubKey = otherKey;
1935
1936 ret = wc_InitRng(&rng);
1937 if (ret == 0) {
1938 ret = wc_curve25519_make_key(&rng, CURVE25519_KEYSIZE, privKey);
1939 if (ret == 0) {
1940 ret = wc_curve25519_export_public_ex(privKey, pubKeyDer,
1941 pubKeySz, EC25519_LITTLE_ENDIAN);
1942 }
1943 wc_FreeRng(&rng);
1944 }
1945 }
1946
1947 /* for server: import public key */
1948 else if (side == WOLFSSL_SERVER_END) {
1949 privKey = otherKey;
1950 pubKey = &tmpKey;
1951
1952 ret = wc_curve25519_import_public_ex(pubKeyDer, *pubKeySz, pubKey,
1953 EC25519_LITTLE_ENDIAN);
1954 }
1955 else {
1956 ret = BAD_FUNC_ARG;
1957 }
1958
1959 /* generate shared secret and return it */
1960 if (ret == 0) {
1961 ret = wc_curve25519_shared_secret_ex(privKey, pubKey, out, outlen,
1962 EC25519_LITTLE_ENDIAN);
1963 }
1964
1965 wc_curve25519_free(&tmpKey);
1966
1967 return ret;
1968}
1969#endif /* HAVE_CURVE25519 */
1970
1971#endif /* HAVE_ECC */
1972
1973#ifndef NO_RSA
1974
1975static INLINE int myRsaSign(WOLFSSL* ssl, const byte* in, word32 inSz,
1976 byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
1977{
1978 WC_RNG rng;
1979 int ret;
1980 word32 idx = 0;
1981 RsaKey myKey;
1982
1983 (void)ssl;
1984 (void)ctx;
1985
1986 ret = wc_InitRng(&rng);
1987 if (ret != 0)
1988 return ret;
1989
1990 ret = wc_InitRsaKey(&myKey, NULL);
1991 if (ret == 0) {
1992 ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
1993 if (ret == 0)
1994 ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, &myKey, &rng);
1995 if (ret > 0) { /* save and convert to 0 success */
1996 *outSz = ret;
1997 ret = 0;
1998 }
1999 wc_FreeRsaKey(&myKey);
2000 }
2001 wc_FreeRng(&rng);
2002
2003 return ret;
2004}
2005
2006
2007static INLINE int myRsaVerify(WOLFSSL* ssl, byte* sig, word32 sigSz,
2008 byte** out,
2009 const byte* key, word32 keySz,
2010 void* ctx)
2011{
2012 int ret;
2013 word32 idx = 0;
2014 RsaKey myKey;
2015
2016 (void)ssl;
2017 (void)ctx;
2018
2019 ret = wc_InitRsaKey(&myKey, NULL);
2020 if (ret == 0) {
2021 ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
2022 if (ret == 0)
2023 ret = wc_RsaSSL_VerifyInline(sig, sigSz, out, &myKey);
2024 wc_FreeRsaKey(&myKey);
2025 }
2026
2027 return ret;
2028}
2029
2030#ifdef WC_RSA_PSS
2031static INLINE int myRsaPssSign(WOLFSSL* ssl, const byte* in, word32 inSz,
2032 byte* out, word32* outSz, int hash, int mgf, const byte* key,
2033 word32 keySz, void* ctx)
2034{
2035 enum wc_HashType hashType = WC_HASH_TYPE_NONE;
2036 WC_RNG rng;
2037 int ret;
2038 word32 idx = 0;
2039 RsaKey myKey;
2040
2041 (void)ssl;
2042 (void)ctx;
2043
2044 switch (hash) {
2045#ifndef NO_SHA256
2046 case SHA256h:
2047 hashType = WC_HASH_TYPE_SHA256;
2048 break;
2049#endif
2050#ifdef WOLFSSL_SHA384
2051 case SHA384h:
2052 hashType = WC_HASH_TYPE_SHA384;
2053 break;
2054#endif
2055#ifdef WOLFSSL_SHA512
2056 case SHA512h:
2057 hashType = WC_HASH_TYPE_SHA512;
2058 break;
2059#endif
2060 }
2061
2062 ret = wc_InitRng(&rng);
2063 if (ret != 0)
2064 return ret;
2065
2066 ret = wc_InitRsaKey(&myKey, NULL);
2067 if (ret == 0) {
2068 ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
2069 if (ret == 0) {
2070 ret = wc_RsaPSS_Sign(in, inSz, out, *outSz, hashType, mgf, &myKey,
2071 &rng);
2072 }
2073 if (ret > 0) { /* save and convert to 0 success */
2074 *outSz = ret;
2075 ret = 0;
2076 }
2077 wc_FreeRsaKey(&myKey);
2078 }
2079 wc_FreeRng(&rng);
2080
2081 return ret;
2082}
2083
2084
2085static INLINE int myRsaPssVerify(WOLFSSL* ssl, byte* sig, word32 sigSz,
2086 byte** out, int hash, int mgf, const byte* key, word32 keySz, void* ctx)
2087{
2088 enum wc_HashType hashType = WC_HASH_TYPE_NONE;
2089 int ret;
2090 word32 idx = 0;
2091 RsaKey myKey;
2092
2093 (void)ssl;
2094 (void)ctx;
2095
2096 switch (hash) {
2097#ifndef NO_SHA256
2098 case SHA256h:
2099 hashType = WC_HASH_TYPE_SHA256;
2100 break;
2101#endif
2102#ifdef WOLFSSL_SHA384
2103 case SHA384h:
2104 hashType = WC_HASH_TYPE_SHA384;
2105 break;
2106#endif
2107#ifdef WOLFSSL_SHA512
2108 case SHA512h:
2109 hashType = WC_HASH_TYPE_SHA512;
2110 break;
2111#endif
2112 }
2113
2114 ret = wc_InitRsaKey(&myKey, NULL);
2115 if (ret == 0) {
2116 ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
2117 if (ret == 0) {
2118 ret = wc_RsaPSS_VerifyInline(sig, sigSz, out, hashType, mgf,
2119 &myKey);
2120 }
2121 wc_FreeRsaKey(&myKey);
2122 }
2123
2124 return ret;
2125}
2126#endif
2127
2128
2129static INLINE int myRsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz,
2130 byte* out, word32* outSz, const byte* key,
2131 word32 keySz, void* ctx)
2132{
2133 int ret;
2134 word32 idx = 0;
2135 RsaKey myKey;
2136 WC_RNG rng;
2137
2138 (void)ssl;
2139 (void)ctx;
2140
2141 ret = wc_InitRng(&rng);
2142 if (ret != 0)
2143 return ret;
2144
2145 ret = wc_InitRsaKey(&myKey, NULL);
2146 if (ret == 0) {
2147 ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
2148 if (ret == 0) {
2149 ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, &myKey, &rng);
2150 if (ret > 0) {
2151 *outSz = ret;
2152 ret = 0; /* reset to success */
2153 }
2154 }
2155 wc_FreeRsaKey(&myKey);
2156 }
2157 wc_FreeRng(&rng);
2158
2159 return ret;
2160}
2161
2162static INLINE int myRsaDec(WOLFSSL* ssl, byte* in, word32 inSz,
2163 byte** out,
2164 const byte* key, word32 keySz, void* ctx)
2165{
2166 int ret;
2167 word32 idx = 0;
2168 RsaKey myKey;
2169
2170 (void)ssl;
2171 (void)ctx;
2172
2173 ret = wc_InitRsaKey(&myKey, NULL);
2174 if (ret == 0) {
2175 ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
2176 if (ret == 0) {
2177 #ifdef WC_RSA_BLINDING
2178 ret = wc_RsaSetRNG(&myKey, wolfSSL_GetRNG(ssl));
2179 if (ret != 0) {
2180 wc_FreeRsaKey(&myKey);
2181 return ret;
2182 }
2183 #endif
2184 ret = wc_RsaPrivateDecryptInline(in, inSz, out, &myKey);
2185 }
2186 wc_FreeRsaKey(&myKey);
2187 }
2188
2189 return ret;
2190}
2191
2192#endif /* NO_RSA */
2193
2194static INLINE void SetupPkCallbacks(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
2195{
2196 (void)ctx;
2197 (void)ssl;
2198
2199 #ifdef HAVE_ECC
2200 wolfSSL_CTX_SetEccSignCb(ctx, myEccSign);
2201 wolfSSL_CTX_SetEccVerifyCb(ctx, myEccVerify);
2202 wolfSSL_CTX_SetEccSharedSecretCb(ctx, myEccSharedSecret);
2203 #endif /* HAVE_ECC */
2204 #ifdef HAVE_ED25519
2205 wolfSSL_CTX_SetEd25519SignCb(ctx, myEd25519Sign);
2206 wolfSSL_CTX_SetEd25519VerifyCb(ctx, myEd25519Verify);
2207 #endif
2208 #ifdef HAVE_CURVE25519
2209 wolfSSL_CTX_SetX25519SharedSecretCb(ctx, myX25519SharedSecret);
2210 #endif
2211 #ifndef NO_RSA
2212 wolfSSL_CTX_SetRsaSignCb(ctx, myRsaSign);
2213 wolfSSL_CTX_SetRsaVerifyCb(ctx, myRsaVerify);
2214 #ifdef WC_RSA_PSS
2215 wolfSSL_CTX_SetRsaPssSignCb(ctx, myRsaPssSign);
2216 wolfSSL_CTX_SetRsaPssVerifyCb(ctx, myRsaPssVerify);
2217 #endif
2218 wolfSSL_CTX_SetRsaEncCb(ctx, myRsaEnc);
2219 wolfSSL_CTX_SetRsaDecCb(ctx, myRsaDec);
2220 #endif /* NO_RSA */
2221}
2222
2223#endif /* HAVE_PK_CALLBACKS */
2224
2225
2226
2227
2228
2229#if defined(__hpux__) || defined(__MINGW32__) || defined (WOLFSSL_TIRTOS) \
2230 || defined(_MSC_VER)
2231
2232/* HP/UX doesn't have strsep, needed by test/suites.c */
2233static INLINE char* strsep(char **stringp, const char *delim)
2234{
2235 char* start;
2236 char* end;
2237
2238 start = *stringp;
2239 if (start == NULL)
2240 return NULL;
2241
2242 if ((end = strpbrk(start, delim))) {
2243 *end++ = '\0';
2244 *stringp = end;
2245 } else {
2246 *stringp = NULL;
2247 }
2248
2249 return start;
2250}
2251
2252#endif /* __hpux__ and others */
2253
2254/* Create unique filename, len is length of tempfn name, assuming
2255 len does not include null terminating character,
2256 num is number of characters in tempfn name to randomize */
2257static INLINE const char* mymktemp(char *tempfn, int len, int num)
2258{
2259 int x, size;
2260 static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2261 "abcdefghijklmnopqrstuvwxyz";
2262 WC_RNG rng;
2263 byte out;
2264
2265 if (tempfn == NULL || len < 1 || num < 1 || len <= num) {
2266 printf("Bad input\n");
2267 return NULL;
2268 }
2269
2270 size = len - 1;
2271
2272 if (wc_InitRng(&rng) != 0) {
2273 printf("InitRng failed\n");
2274 return NULL;
2275 }
2276
2277 for (x = size; x > size - num; x--) {
2278 if (wc_RNG_GenerateBlock(&rng,(byte*)&out, sizeof(out)) != 0) {
2279 printf("RNG_GenerateBlock failed\n");
2280 return NULL;
2281 }
2282 tempfn[x] = alphanum[out % (sizeof(alphanum) - 1)];
2283 }
2284 tempfn[len] = '\0';
2285
2286 wc_FreeRng(&rng);
2287
2288 return tempfn;
2289}
2290
2291
2292
2293#if defined(HAVE_SESSION_TICKET) && defined(HAVE_CHACHA) && \
2294 defined(HAVE_POLY1305)
2295
2296 #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
2297
2298 typedef struct key_ctx {
2299 byte name[WOLFSSL_TICKET_NAME_SZ]; /* name for this context */
2300 byte key[CHACHA20_POLY1305_AEAD_KEYSIZE]; /* cipher key */
2301 } key_ctx;
2302
2303 static key_ctx myKey_ctx;
2304 static WC_RNG myKey_rng;
2305
2306 static INLINE int TicketInit(void)
2307 {
2308 int ret = wc_InitRng(&myKey_rng);
2309 if (ret != 0) return ret;
2310
2311 ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.key, sizeof(myKey_ctx.key));
2312 if (ret != 0) return ret;
2313
2314 ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.name,sizeof(myKey_ctx.name));
2315 if (ret != 0) return ret;
2316
2317 return 0;
2318 }
2319
2320 static INLINE void TicketCleanup(void)
2321 {
2322 wc_FreeRng(&myKey_rng);
2323 }
2324
2325 static INLINE int myTicketEncCb(WOLFSSL* ssl,
2326 byte key_name[WOLFSSL_TICKET_NAME_SZ],
2327 byte iv[WOLFSSL_TICKET_IV_SZ],
2328 byte mac[WOLFSSL_TICKET_MAC_SZ],
2329 int enc, byte* ticket, int inLen, int* outLen,
2330 void* userCtx)
2331 {
2332 (void)ssl;
2333 (void)userCtx;
2334
2335 int ret;
2336 word16 sLen = XHTONS(inLen);
2337 byte aad[WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2];
2338 int aadSz = WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2;
2339 byte* tmp = aad;
2340
2341 if (enc) {
2342 XMEMCPY(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ);
2343
2344 ret = wc_RNG_GenerateBlock(&myKey_rng, iv, WOLFSSL_TICKET_IV_SZ);
2345 if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
2346
2347 /* build aad from key name, iv, and length */
2348 XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
2349 tmp += WOLFSSL_TICKET_NAME_SZ;
2350 XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
2351 tmp += WOLFSSL_TICKET_IV_SZ;
2352 XMEMCPY(tmp, &sLen, 2);
2353
2354 ret = wc_ChaCha20Poly1305_Encrypt(myKey_ctx.key, iv,
2355 aad, aadSz,
2356 ticket, inLen,
2357 ticket,
2358 mac);
2359 if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
2360 *outLen = inLen; /* no padding in this mode */
2361 } else {
2362 /* decrypt */
2363
2364 /* see if we know this key */
2365 if (XMEMCMP(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ) != 0){
2366 printf("client presented unknown ticket key name ");
2367 return WOLFSSL_TICKET_RET_FATAL;
2368 }
2369
2370 /* build aad from key name, iv, and length */
2371 XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
2372 tmp += WOLFSSL_TICKET_NAME_SZ;
2373 XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
2374 tmp += WOLFSSL_TICKET_IV_SZ;
2375 XMEMCPY(tmp, &sLen, 2);
2376
2377 ret = wc_ChaCha20Poly1305_Decrypt(myKey_ctx.key, iv,
2378 aad, aadSz,
2379 ticket, inLen,
2380 mac,
2381 ticket);
2382 if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
2383 *outLen = inLen; /* no padding in this mode */
2384 }
2385
2386 return WOLFSSL_TICKET_RET_OK;
2387 }
2388
2389#endif /* HAVE_SESSION_TICKET && CHACHA20 && POLY1305 */
2390
2391static INLINE word16 GetRandomPort(void)
2392{
2393 word16 port = 0;
2394
2395 /* Generate random port for testing */
2396 WC_RNG rng;
2397 if (wc_InitRng(&rng) == 0) {
2398 wc_RNG_GenerateBlock(&rng, (byte*)&port, sizeof(port));
2399 port |= 0xC000; /* Make sure its in the 49152 - 65535 range */
2400 wc_FreeRng(&rng);
2401 }
2402 return port;
2403}
2404
2405#endif /* wolfSSL_TEST_H */
Note: See TracBrowser for help on using the repository browser.