int ClientBenchmarkConnections(WOLFSSL_CTX* ctx, char* host, word16 port, int doDTLS, int benchmark, int resumeSession) { /* time passed in number of connects give average */ int times = benchmark; int loops = resumeSession ? 2 : 1; int i = 0; #ifndef NO_SESSION_CACHE WOLFSSL_SESSION* benchSession = NULL; #endif (void)resumeSession; while (loops--) { #ifndef NO_SESSION_CACHE int benchResume = resumeSession && loops == 0; #endif double start = current_time(), avg; for (i = 0; i < times; i++) { SOCKET_T sockfd; WOLFSSL* ssl = wolfSSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL object"); tcp_connect(&sockfd, host, port, doDTLS, ssl); #ifndef NO_SESSION_CACHE if (benchResume) wolfSSL_set_session(ssl, benchSession); #endif wolfSSL_set_fd(ssl, sockfd); if (wolfSSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed"); wolfSSL_shutdown(ssl); #ifndef NO_SESSION_CACHE if (i == (times-1) && resumeSession) { benchSession = wolfSSL_get_session(ssl); } #endif wolfSSL_free(ssl); CloseSocket(sockfd); } avg = current_time() - start; avg /= times; avg *= 1000; /* milliseconds */ #ifndef NO_SESSION_CACHE if (benchResume) printf("wolfSSL_resume avg took: %8.3f milliseconds\n", avg); else #endif printf("wolfSSL_connect avg took: %8.3f milliseconds\n", avg); } return EXIT_SUCCESS; }
int Client(const char* ip, word16 port) { int n; char msg[] = "hello wolfssl"; char reply[MAXSZ]; int msgSz = strlen(msg); SOCKET_T fd; WOLFSSL_CTX* ctx; WOLFSSL* ssl; if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())) == NULL) err_sys("Error in setting client ctx\n"); if (wolfSSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS) err_sys("trouble loading client cert"); if (wolfSSL_CTX_use_certificate_file(ctx, cliCert, SSL_FILETYPE_PEM) != SSL_SUCCESS) err_sys("trouble loading client cert"); if (wolfSSL_CTX_use_PrivateKey_file(ctx, cliKey, SSL_FILETYPE_PEM) != SSL_SUCCESS) err_sys("trouble loading client cert"); /*sets the IO callback methods*/ wolfSSL_SetIORecv(ctx, CbIORecv); wolfSSL_SetIOSend(ctx, CbIOSend); if ((ssl = wolfSSL_new(ctx)) == NULL) err_sys("issue when creating ssl"); tcp_connect(&fd, ip, port, 0); wolfSSL_set_fd(ssl, fd); if (wolfSSL_connect(ssl) != SSL_SUCCESS) err_sys("client connect failed"); if (wolfSSL_write(ssl, msg, msgSz) != msgSz) err_sys("client write failed"); memset(reply, 0, MAXSZ); if ((n = wolfSSL_read(ssl, reply, MAXSZ - 1)) > 0) { reply[n] = '\0'; } else { printf("client read returned %d\n", n); return -1; } printf("Server sent : %s\n", reply); wolfSSL_shutdown(ssl); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); return 0; }
void *ThreadHandler(void* socketDesc) { int connd = *(int*)socketDesc; WOLFSSL* ssl; /* Create our reply message */ const char reply[] = "I hear ya fa shizzle!\n"; printf("Client connected successfully\n"); if ( (ssl = wolfSSL_new(ctx)) == NULL) { fprintf(stderr, "wolfSSL_new error.\n"); exit(EXIT_FAILURE); } /* Direct our ssl to our clients connection */ wolfSSL_set_fd(ssl, connd); for ( ; ; ) { char buff[256]; int ret = 0; /* Clear the buffer memory for anything possibly left over */ memset(&buff, 0, sizeof(buff)); /* Read the client data into our buff array */ if ((ret = wolfSSL_read(ssl, buff, sizeof(buff)-1)) > 0) { /* Print any data the client sends to the console */ printf("Client on Socket %d: %s\n", connd, buff); /* Reply back to the client */ if ((ret = wolfSSL_write(ssl, reply, sizeof(reply)-1)) < 0) { printf("wolfSSL_write error = %d\n", wolfSSL_get_error(ssl, ret)); } } /* if the client disconnects break the loop */ else { if (ret < 0) printf("wolfSSL_read error = %d\n", wolfSSL_get_error(ssl ,ret)); else if (ret == 0) printf("The client has closed the connection.\n"); wolfSSL_free(ssl); /* Free the WOLFSSL object */ close(connd); /* close the connected socket */ break; } } exit(EXIT_SUCCESS); }
int main() { int sockfd; WOLFSSL_CTX* ctx; WOLFSSL* ssl; WOLFSSL_METHOD* method; struct sockaddr_in servAddr; const char message[] = "Hello, World!"; /* create and set up socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(SERV_PORT); /* connect to socket */ connect(sockfd, (struct sockaddr *) &servAddr, sizeof(servAddr)); /* initialize wolfssl library */ wolfSSL_Init(); method = wolfTLSv1_2_client_method(); /* use TLS v1.2 */ /* make new ssl context */ if ( (ctx = wolfSSL_CTX_new(method)) == NULL) { err_sys("wolfSSL_CTX_new error"); } /* make new wolfSSL struct */ if ( (ssl = wolfSSL_new(ctx)) == NULL) { err_sys("wolfSSL_new error"); } /* Add cert to ctx */ if (wolfSSL_CTX_load_verify_locations(ctx, "certs/ca-cert.pem", 0) != SSL_SUCCESS) { err_sys("Error loading certs/ca-cert.pem"); } /* Connect wolfssl to the socket, server, then send message */ wolfSSL_set_fd(ssl, sockfd); wolfSSL_connect(ssl); wolfSSL_write(ssl, message, strlen(message)); /* frees all data before client termination */ wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); }
bool NET_PRES_EncProviderStreamClientOpen0(uintptr_t transHandle, void * providerData) { WOLFSSL* ssl = wolfSSL_new(net_pres_wolfSSLInfoStreamClient0.context); if (ssl == NULL) { return false; } if (wolfSSL_set_fd(ssl, transHandle) != SSL_SUCCESS) { wolfSSL_free(ssl); return false; } memcpy(providerData, &ssl, sizeof(WOLFSSL*)); return true; }
WOLFSSL *start_ssl(WOLFSSL_CTX *wsslctx, socklen_t clisocketfd, struct sockaddr_in cliaddr) { socklen_t casize; WOLFSSL *wssl; casize = sizeof(cliaddr); if ( (wssl = wolfSSL_new(wsslctx)) == NULL ) { std::cout<<"Failed to create new SSL object"<<std::endl; return NULL; } wolfSSL_set_fd(wssl,clisocketfd); return wssl; }
/* Connects to the server. * * ctx The SSL/TLS connection data. * sslCtx The SSL/TLS context. * sockfd The socket for communicating with the server. * sslConn The SSL connection. * returns EXIT_SUCCESS if a new connection connected or EXIT_FAILURE otherwise. */ static int SSLConn_Connect(SSLConn_CTX* ctx, WOLFSSL_CTX* sslCtx, int sockfd, SSLConn* sslConn) { ctx->numCreated++; /* Setup connection. */ sslConn->sockfd = sockfd; if ((sslConn->ssl = wolfSSL_new(sslCtx)) == NULL) { fprintf(stderr, "wolfSSL_new error.\n"); return EXIT_FAILURE; } sslConn->state = CONNECT; /* Set the socket to communicate over. */ wolfSSL_set_fd(sslConn->ssl, sslConn->sockfd); wolfSSL_set_using_nonblock(sslConn->ssl, 1); return EXIT_SUCCESS; }
/* * Process handled by a thread. */ void* wolfssl_thread(void* fd) { WOLFSSL* ssl; int connfd = *((int*)fd); int n; char buf[MAXLINE]; char response[] = "I hear ya for shizzle"; memset(buf, 0, MAXLINE); /* create WOLFSSL object */ if ((ssl = wolfSSL_new(ctx)) == NULL) { printf("Fatal error : wolfSSL_new error"); /* place signal for forced error exit here */ } wolfSSL_set_fd(ssl, connfd); /* respond to client */ n = wolfSSL_read(ssl, buf, MAXLINE); if (n > 0) { printf("%s\n", buf); if (wolfSSL_write(ssl, response, strlen(response)) != strlen(response)) { printf("Fatal error :respond: write error\n"); /* place signal for forced error exit here */ } } if (n < 0) { printf("Fatal error : respond: read error\n"); /* place signal for forced error exit here */ } /* closes the connections after responding */ wolfSSL_shutdown(ssl); wolfSSL_free(ssl); if (close(connfd) == -1) { printf("Fatal error : close error\n"); /* place signal for forced error exit here */ } pthread_exit(NULL); }
/* Accepts a new connection. * * threadData The SSL/TLS connection data for a thread. * sslCtx The SSL/TLS context. * sockfd The socket file descriptor to accept on. * sslConn The newly create SSL connection data object. * returns EXIT_SUCCESS if a new connection was accepted or EXIT_FAILURE * otherwise. */ static int SSLConn_Accept(ThreadData* threadData, WOLFSSL_CTX* sslCtx, socklen_t sockfd, SSLConn** sslConn) { struct sockaddr_in clientAddr = {0}; socklen_t size = sizeof(clientAddr); SSLConn* conn; conn = malloc(sizeof(*conn)); if (conn == NULL) return EXIT_FAILURE; /* Accept the client connection. */ conn->sockfd = accept(sockfd, (struct sockaddr *)&clientAddr, &size); if (conn->sockfd == -1) { free(conn); fprintf(stderr, "ERROR: failed to accept\n"); return EXIT_FAILURE; } /* Set the new socket to be non-blocking. */ fcntl(conn->sockfd, F_SETFL, O_NONBLOCK); /* Setup SSL/TLS connection. */ if ((conn->ssl = wolfSSL_new(sslCtx)) == NULL) { free(conn); fprintf(stderr, "wolfSSL_new error.\n"); return EXIT_FAILURE; } /* Set the socket to communicate over into the wolfSSL object. */ wolfSSL_set_fd(conn->ssl, conn->sockfd); wolfSSL_set_using_nonblock(conn->ssl, 1); conn->state = ACCEPT; conn->next = threadData->sslConn; conn->prev = NULL; if (threadData->sslConn != NULL) threadData->sslConn->prev = conn; threadData->sslConn = conn; threadData->cnt++; *sslConn = conn; return EXIT_SUCCESS; }
/* * applies TLS 1.2 security layer to data being sent. */ int Security(int sock) { WOLFSSL_CTX* ctx; WOLFSSL* ssl; /* create WOLFSSL object */ int ret = 0; wolfSSL_Init(); /* initialize wolfSSL */ /* create and initiLize WOLFSSL_CTX structure */ if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())) == NULL) { printf("SSL_CTX_new error.\n"); return EXIT_FAILURE; } /* set callback for action when CA's are added */ wolfSSL_CTX_SetCACb(ctx, CaCb); /* load CA certificates into wolfSSL_CTX. which will verify the server */ if (wolfSSL_CTX_load_verify_locations(ctx, cert, 0) != SSL_SUCCESS) { printf("Error loading %s. Please check the file.\n", cert); return EXIT_FAILURE; } if ((ssl = wolfSSL_new(ctx)) == NULL) { printf("wolfSSL_new error.\n"); return EXIT_FAILURE; } wolfSSL_set_fd(ssl, sock); ret = wolfSSL_connect(ssl); if (ret == SSL_SUCCESS) { ret = ClientGreet(sock, ssl); } /* frees all data before client termination */ wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); return ret; }
static void *_mod_wolftls_getctx(void *arg, http_client_t *ctl, struct sockaddr *addr, int addrsize) { _mod_wolftls_t *mod = (_mod_wolftls_t *)arg; _mod_wolftls_ctx_t *ctx = calloc(1, sizeof(*ctx)); ctx->ssl = wolfSSL_new(mod->ctx); if (ctx->ssl == NULL) { err("wolftls connection error"); free(ctx); return NULL; } dbg("TLS Open"); ctx->ctl = ctl; ctx->ctx = httpclient_context(ctl); ctx->recvreq = httpclient_addreceiver(ctl, _mod_wolftls_recv, ctx); ctx->sendresp = httpclient_addsender(ctl, _mod_wolftls_send, ctx); wolfSSL_set_fd(ctx->ssl, httpclient_wait(ctl, WAIT_ACCEPT)); return ctx; }
THREAD_RETURN WOLFSSL_THREAD client_test(void* args) { SOCKET_T sockfd = 0; WOLFSSL_METHOD* method = 0; WOLFSSL_CTX* ctx = 0; WOLFSSL* ssl = 0; WOLFSSL* sslResume = 0; WOLFSSL_SESSION* session = 0; char resumeMsg[] = "resuming wolfssl!"; int resumeSz = sizeof(resumeMsg); char msg[32] = "hello wolfssl!"; /* GET may make bigger */ char reply[80]; int input; int msgSz = (int)strlen(msg); word16 port = yasslPort; char* host = (char*)yasslIP; const char* domain = "www.yassl.com"; int ch; int version = CLIENT_INVALID_VERSION; int usePsk = 0; int useAnon = 0; int sendGET = 0; int benchmark = 0; int doDTLS = 0; int matchName = 0; int doPeerCheck = 1; int nonBlocking = 0; int resumeSession = 0; int scr = 0; /* allow secure renegotiation */ int forceScr = 0; /* force client initiaed scr */ int trackMemory = 0; int useClientCert = 1; int fewerPackets = 0; int atomicUser = 0; int pkCallbacks = 0; int overrideDateErrors = 0; char* cipherList = NULL; const char* verifyCert = caCert; const char* ourCert = cliCert; const char* ourKey = cliKey; #ifdef HAVE_SNI char* sniHostName = NULL; #endif #ifdef HAVE_MAX_FRAGMENT byte maxFragment = 0; #endif #ifdef HAVE_TRUNCATED_HMAC byte truncatedHMAC = 0; #endif #ifdef HAVE_OCSP int useOcsp = 0; char* ocspUrl = NULL; #endif int argc = ((func_args*)args)->argc; char** argv = ((func_args*)args)->argv; ((func_args*)args)->return_code = -1; /* error state */ #ifdef NO_RSA verifyCert = (char*)eccCert; ourCert = (char*)cliEccCert; ourKey = (char*)cliEccKey; #endif (void)resumeSz; (void)session; (void)sslResume; (void)trackMemory; (void)atomicUser; (void)pkCallbacks; (void)scr; (void)forceScr; StackTrap(); while ((ch = mygetopt(argc, argv, "?gdDusmNrRitfxUPh:p:v:l:A:c:k:b:zS:L:ToO:a")) != -1) { switch (ch) { case '?' : Usage(); exit(EXIT_SUCCESS); case 'g' : sendGET = 1; break; case 'd' : doPeerCheck = 0; break; case 'D' : overrideDateErrors = 1; break; case 'u' : doDTLS = 1; break; case 's' : usePsk = 1; break; case 't' : #ifdef USE_WOLFSSL_MEMORY trackMemory = 1; #endif break; case 'm' : matchName = 1; break; case 'x' : useClientCert = 0; break; case 'f' : fewerPackets = 1; break; case 'U' : #ifdef ATOMIC_USER atomicUser = 1; #endif break; case 'P' : #ifdef HAVE_PK_CALLBACKS pkCallbacks = 1; #endif break; case 'h' : host = myoptarg; domain = myoptarg; break; case 'p' : port = (word16)atoi(myoptarg); #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API) if (port == 0) err_sys("port number cannot be 0"); #endif break; case 'v' : version = atoi(myoptarg); if (version < 0 || version > 3) { Usage(); exit(MY_EX_USAGE); } break; case 'l' : cipherList = myoptarg; break; case 'A' : verifyCert = myoptarg; break; case 'c' : ourCert = myoptarg; break; case 'k' : ourKey = myoptarg; break; case 'b' : benchmark = atoi(myoptarg); if (benchmark < 0 || benchmark > 1000000) { Usage(); exit(MY_EX_USAGE); } break; case 'N' : nonBlocking = 1; break; case 'r' : resumeSession = 1; break; case 'R' : #ifdef HAVE_SECURE_RENEGOTIATION scr = 1; #endif break; case 'i' : #ifdef HAVE_SECURE_RENEGOTIATION scr = 1; forceScr = 1; #endif break; case 'z' : #ifndef WOLFSSL_LEANPSK wolfSSL_GetObjectSize(); #endif break; case 'S' : #ifdef HAVE_SNI sniHostName = myoptarg; #endif break; case 'L' : #ifdef HAVE_MAX_FRAGMENT maxFragment = atoi(myoptarg); if (maxFragment < WOLFSSL_MFL_2_9 || maxFragment > WOLFSSL_MFL_2_13) { Usage(); exit(MY_EX_USAGE); } #endif break; case 'T' : #ifdef HAVE_TRUNCATED_HMAC truncatedHMAC = 1; #endif break; case 'o' : #ifdef HAVE_OCSP useOcsp = 1; #endif break; case 'O' : #ifdef HAVE_OCSP useOcsp = 1; ocspUrl = myoptarg; #endif break; case 'a' : #ifdef HAVE_ANON useAnon = 1; #endif break; default: Usage(); exit(MY_EX_USAGE); } } myoptind = 0; /* reset for test cases */ /* sort out DTLS versus TLS versions */ if (version == CLIENT_INVALID_VERSION) { if (doDTLS) version = CLIENT_DTLS_DEFAULT_VERSION; else version = CLIENT_DEFAULT_VERSION; } else { if (doDTLS) { if (version == 3) version = -2; else version = -1; } } #ifdef USE_WOLFSSL_MEMORY if (trackMemory) InitMemoryTracker(); #endif switch (version) { #ifndef NO_OLD_TLS case 0: method = wolfSSLv3_client_method(); break; #ifndef NO_TLS case 1: method = wolfTLSv1_client_method(); break; case 2: method = wolfTLSv1_1_client_method(); break; #endif /* NO_TLS */ #endif /* NO_OLD_TLS */ #ifndef NO_TLS case 3: method = wolfTLSv1_2_client_method(); break; #endif #ifdef WOLFSSL_DTLS case -1: method = wolfDTLSv1_client_method(); break; case -2: method = wolfDTLSv1_2_client_method(); break; #endif default: err_sys("Bad SSL version"); break; } if (method == NULL) err_sys("unable to get method"); ctx = wolfSSL_CTX_new(method); if (ctx == NULL) err_sys("unable to get ctx"); if (cipherList) if (wolfSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS) err_sys("client can't set cipher list 1"); #ifdef WOLFSSL_LEANPSK usePsk = 1; #endif #if defined(NO_RSA) && !defined(HAVE_ECC) usePsk = 1; #endif if (fewerPackets) wolfSSL_CTX_set_group_messages(ctx); if (usePsk) { #ifndef NO_PSK wolfSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb); if (cipherList == NULL) { const char *defaultCipherList; #ifdef HAVE_NULL_CIPHER defaultCipherList = "PSK-NULL-SHA256"; #else defaultCipherList = "PSK-AES128-CBC-SHA256"; #endif if (wolfSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS) err_sys("client can't set cipher list 2"); } #endif useClientCert = 0; } if (useAnon) { #ifdef HAVE_ANON if (cipherList == NULL) { wolfSSL_CTX_allow_anon_cipher(ctx); if (wolfSSL_CTX_set_cipher_list(ctx,"ADH-AES128-SHA") != SSL_SUCCESS) err_sys("client can't set cipher list 4"); } #endif useClientCert = 0; } #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); #endif #if defined(WOLFSSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC) if (cipherList == NULL) { /* don't use EDH, can't sniff tmp keys */ if (wolfSSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS) { err_sys("client can't set cipher list 3"); } } #endif #ifdef HAVE_OCSP if (useOcsp) { if (ocspUrl != NULL) { wolfSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl); wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE | WOLFSSL_OCSP_URL_OVERRIDE); } else wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE); } #endif #ifdef USER_CA_CB wolfSSL_CTX_SetCACb(ctx, CaCb); #endif #ifdef VERIFY_CALLBACK wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); #endif #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) if (useClientCert){ if (wolfSSL_CTX_use_certificate_chain_file(ctx, ourCert) != SSL_SUCCESS) err_sys("can't load client cert file, check file and run from" " wolfSSL home dir"); if (wolfSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM) != SSL_SUCCESS) err_sys("can't load client private key file, check file and run " "from wolfSSL home dir"); } if (!usePsk && !useAnon) { if (wolfSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS) err_sys("can't load ca file, Please run from wolfSSL home dir"); } #endif #if !defined(NO_CERTS) if (!usePsk && !useAnon && doPeerCheck == 0) wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0); if (!usePsk && !useAnon && overrideDateErrors == 1) wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myDateCb); #endif #ifdef HAVE_CAVIUM wolfSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID); #endif #ifdef HAVE_SNI if (sniHostName) if (wolfSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName)) != SSL_SUCCESS) err_sys("UseSNI failed"); #endif #ifdef HAVE_MAX_FRAGMENT if (maxFragment) if (wolfSSL_CTX_UseMaxFragment(ctx, maxFragment) != SSL_SUCCESS) err_sys("UseMaxFragment failed"); #endif #ifdef HAVE_TRUNCATED_HMAC if (truncatedHMAC) if (wolfSSL_CTX_UseTruncatedHMAC(ctx) != SSL_SUCCESS) err_sys("UseTruncatedHMAC failed"); #endif #ifdef HAVE_SESSION_TICKET if (wolfSSL_CTX_UseSessionTicket(ctx) != SSL_SUCCESS) err_sys("UseSessionTicket failed"); #endif if (benchmark) { /* time passed in number of connects give average */ int times = benchmark; int i = 0; double start = current_time(), avg; for (i = 0; i < times; i++) { tcp_connect(&sockfd, host, port, doDTLS); ssl = wolfSSL_new(ctx); wolfSSL_set_fd(ssl, sockfd); if (wolfSSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed"); wolfSSL_shutdown(ssl); wolfSSL_free(ssl); CloseSocket(sockfd); } avg = current_time() - start; avg /= times; avg *= 1000; /* milliseconds */ printf("wolfSSL_connect avg took: %8.3f milliseconds\n", avg); wolfSSL_CTX_free(ctx); ((func_args*)args)->return_code = 0; exit(EXIT_SUCCESS); } #if defined(WOLFSSL_MDK_ARM) wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0); #endif ssl = wolfSSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL object"); #ifdef HAVE_SESSION_TICKET wolfSSL_set_SessionTicket_cb(ssl, sessionTicketCB, (void*)"initial session"); #endif if (doDTLS) { SOCKADDR_IN_T addr; build_addr(&addr, host, port, 1); wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr)); tcp_socket(&sockfd, 1); } else { tcp_connect(&sockfd, host, port, 0); } #ifdef HAVE_POLY1305 /* use old poly to connect with google server */ if (!XSTRNCMP(domain, "www.google.com", 14)) { if (wolfSSL_use_old_poly(ssl, 1) != 0) err_sys("unable to set to old poly"); } #endif wolfSSL_set_fd(ssl, sockfd); #ifdef HAVE_CRL if (wolfSSL_EnableCRL(ssl, WOLFSSL_CRL_CHECKALL) != SSL_SUCCESS) err_sys("can't enable crl check"); if (wolfSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS) err_sys("can't load crl, check crlfile and date validity"); if (wolfSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS) err_sys("can't set crl callback"); #endif #ifdef HAVE_SECURE_RENEGOTIATION if (scr) { if (wolfSSL_UseSecureRenegotiation(ssl) != SSL_SUCCESS) err_sys("can't enable secure renegotiation"); } #endif #ifdef ATOMIC_USER if (atomicUser) SetupAtomicUser(ctx, ssl); #endif #ifdef HAVE_PK_CALLBACKS if (pkCallbacks) SetupPkCallbacks(ctx, ssl); #endif if (matchName && doPeerCheck) wolfSSL_check_domain_name(ssl, domain); #ifndef WOLFSSL_CALLBACKS if (nonBlocking) { wolfSSL_set_using_nonblock(ssl, 1); tcp_set_nonblocking(&sockfd); NonBlockingSSL_Connect(ssl); } else if (wolfSSL_connect(ssl) != SSL_SUCCESS) { /* see note at top of README */ int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("err = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); err_sys("SSL_connect failed"); /* if you're getting an error here */ } #else timeout.tv_sec = 2; timeout.tv_usec = 0; NonBlockingSSL_Connect(ssl); /* will keep retrying on timeout */ #endif showPeer(ssl); #ifdef HAVE_SECURE_RENEGOTIATION if (scr && forceScr) { if (nonBlocking) { printf("not doing secure renegotiation on example with" " nonblocking yet"); } else { #ifndef NO_SESSION_CACHE if (resumeSession) { session = wolfSSL_get_session(ssl); wolfSSL_set_session(ssl, session); resumeSession = 0; /* only resume once */ } #endif if (wolfSSL_Rehandshake(ssl) != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("err = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); err_sys("wolfSSL_Rehandshake failed"); } } } #endif /* HAVE_SECURE_RENEGOTIATION */ if (sendGET) { printf("SSL connect ok, sending GET...\n"); msgSz = 28; strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz); msg[msgSz] = '\0'; } if (wolfSSL_write(ssl, msg, msgSz) != msgSz) err_sys("SSL_write failed"); input = wolfSSL_read(ssl, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("Server response: %s\n", reply); if (sendGET) { /* get html */ while (1) { input = wolfSSL_read(ssl, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("%s\n", reply); } else break; } } } else if (input < 0) { int readErr = wolfSSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) err_sys("wolfSSL_read failed"); } #ifndef NO_SESSION_CACHE if (resumeSession) { if (doDTLS) { strncpy(msg, "break", 6); msgSz = (int)strlen(msg); /* try to send session close */ wolfSSL_write(ssl, msg, msgSz); } session = wolfSSL_get_session(ssl); sslResume = wolfSSL_new(ctx); } #endif if (doDTLS == 0) /* don't send alert after "break" command */ wolfSSL_shutdown(ssl); /* echoserver will interpret as new conn */ #ifdef ATOMIC_USER if (atomicUser) FreeAtomicUser(ssl); #endif wolfSSL_free(ssl); CloseSocket(sockfd); #ifndef NO_SESSION_CACHE if (resumeSession) { if (doDTLS) { SOCKADDR_IN_T addr; #ifdef USE_WINDOWS_API Sleep(500); #elif defined(WOLFSSL_TIRTOS) Task_sleep(1); #else sleep(1); #endif build_addr(&addr, host, port, 1); wolfSSL_dtls_set_peer(sslResume, &addr, sizeof(addr)); tcp_socket(&sockfd, 1); } else { tcp_connect(&sockfd, host, port, 0); } wolfSSL_set_fd(sslResume, sockfd); wolfSSL_set_session(sslResume, session); #ifdef HAVE_SESSION_TICKET wolfSSL_set_SessionTicket_cb(sslResume, sessionTicketCB, (void*)"resumed session"); #endif showPeer(sslResume); #ifndef WOLFSSL_CALLBACKS if (nonBlocking) { wolfSSL_set_using_nonblock(sslResume, 1); tcp_set_nonblocking(&sockfd); NonBlockingSSL_Connect(sslResume); } else if (wolfSSL_connect(sslResume) != SSL_SUCCESS) err_sys("SSL resume failed"); #else timeout.tv_sec = 2; timeout.tv_usec = 0; NonBlockingSSL_Connect(ssl); /* will keep retrying on timeout */ #endif if (wolfSSL_session_reused(sslResume)) printf("reused session id\n"); else printf("didn't reuse session id!!!\n"); if (wolfSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz) err_sys("SSL_write failed"); if (nonBlocking) { /* give server a chance to bounce a message back to client */ #ifdef USE_WINDOWS_API Sleep(500); #elif defined(WOLFSSL_TIRTOS) Task_sleep(1); #else sleep(1); #endif } input = wolfSSL_read(sslResume, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("Server resume response: %s\n", reply); } /* try to send session break */ wolfSSL_write(sslResume, msg, msgSz); wolfSSL_shutdown(sslResume); wolfSSL_free(sslResume); CloseSocket(sockfd); } #endif /* NO_SESSION_CACHE */ wolfSSL_CTX_free(ctx); ((func_args*)args)->return_code = 0; #ifdef USE_WOLFSSL_MEMORY if (trackMemory) ShowMemoryTracker(); #endif /* USE_WOLFSSL_MEMORY */ #if !defined(WOLFSSL_TIRTOS) return 0; #endif }
int main (int argc, char** argv) { /* standard variables used in a dtls client*/ int sockfd = 0; int err1; int readErr; struct sockaddr_in servAddr; const char* host = argv[1]; WOLFSSL* ssl = 0; WOLFSSL_CTX* ctx = 0; WOLFSSL* sslResume = 0; WOLFSSL_SESSION* session = 0; char* srTest = "testing session resume"; char cert_array[] = "../certs/ca-cert.pem"; char buffer[80]; char* certs = cert_array; /* variables used in a dtls client for session reuse*/ int recvlen; char sendLine[MAXLINE]; char recvLine[MAXLINE - 1]; if (argc != 2) { printf("usage: udpcli <IP address>\n"); return 1; } wolfSSL_Init(); /* Un-comment the following line to enable debugging */ /* wolfSSL_Debugging_ON(); */ if ( (ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method())) == NULL) { fprintf(stderr, "wolfSSL_CTX_new error.\n"); return 1; } if (wolfSSL_CTX_load_verify_locations(ctx, certs, 0) != SSL_SUCCESS) { fprintf(stderr, "Error loading %s, please check the file.\n", certs); return 1; } ssl = wolfSSL_new(ctx); if (ssl == NULL) { printf("unable to get ssl object"); return 1; } memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(SERV_PORT); if ( (inet_pton(AF_INET, host, &servAddr.sin_addr)) < 1) { printf("Error and/or invalid IP address"); return 1; } wolfSSL_dtls_set_peer(ssl, &servAddr, sizeof(servAddr)); if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { printf("cannot create a socket."); return 1; } wolfSSL_set_fd(ssl, sockfd); if (wolfSSL_connect(ssl) != SSL_SUCCESS) { err1 = wolfSSL_get_error(ssl, 0); memset(buffer, 0, 80); printf("err = %d, %s\n", err1, wolfSSL_ERR_error_string(err1, buffer)); printf("SSL_connect failed"); return 1; } /*****************************************************************************/ /* Code for sending datagram to server */ /* Loop while the user gives input or until an EOF is read */ while( fgets(sendLine, MAXLINE, stdin) != NULL ) { /* Attempt to send sendLine to the server */ if ( ( wolfSSL_write(ssl, sendLine, strlen(sendLine))) != strlen(sendLine) ) { printf("Error: wolfSSL_write failed.\n"); } /* Attempt to read a message from server and store it in recvLine */ recvlen = wolfSSL_read(ssl, recvLine, sizeof(recvLine) - 1); /* Error checking wolfSSL_read */ if (recvlen < 0) { readErr = wolfSSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) { printf("Error: wolfSSL_read failed.\n"); } } recvLine[recvlen] = '\0'; fputs(recvLine, stdout); } /* */ /*****************************************************************************/ /* Keep track of the old session information */ wolfSSL_write(ssl, srTest, sizeof(srTest)); session = wolfSSL_get_session(ssl); sslResume = wolfSSL_new(ctx); /* Cleanup the memory used by the old session & ssl object */ wolfSSL_shutdown(ssl); wolfSSL_free(ssl); close(sockfd); /* Perform setup with new variables/old session information */ memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(SERV_PORT); if ( (inet_pton(AF_INET, host, &servAddr.sin_addr)) < 1) { printf("Error and/or invalid IP address"); return 1; } wolfSSL_dtls_set_peer(sslResume, &servAddr, sizeof(servAddr)); if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { printf("cannot create a socket."); return 1; } wolfSSL_set_fd(sslResume, sockfd); /* New method call - specifies to the WOLFSSL object to use the * * given WOLFSSL_SESSION object */ wolfSSL_set_session(sslResume, session); wolfSSL_set_fd(sslResume, sockfd); if (wolfSSL_connect(sslResume) != SSL_SUCCESS) { err1 = wolfSSL_get_error(sslResume, 0); memset(buffer, 0, 80); printf("err = %d, %s\n", err1, wolfSSL_ERR_error_string(err1, buffer)); printf("SSL_connect failed on session reuse\n"); return 1; } if (wolfSSL_session_reused(sslResume)) { printf("reused session id\n"); } else { printf("didn't reuse session id!!!\n"); } /*****************************************************************************/ /* Code for sending datagram to server */ /* Clear out variables for reuse */ recvlen = 0; memset(sendLine, 0, MAXLINE); memset(recvLine, 0, MAXLINE - 1); /* Loop while the user gives input or until an EOF is read */ while( fgets(sendLine, MAXLINE, stdin) != NULL ) { /* Attempt to send sendLine to the server */ if ( ( wolfSSL_write(ssl, sendLine, strlen(sendLine))) != strlen(sendLine) ) { printf("Error: wolfSSL_write failed.\n"); } /* Attempt to read a message from server and store it in recvLine */ recvlen = wolfSSL_read(ssl, recvLine, sizeof(recvLine) - 1); /* Error checking wolfSSL_read */ if (recvlen < 0) { readErr = wolfSSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) { printf("Error: wolfSSL_read failed.\n"); } } recvLine[recvlen] = '\0'; fputs(recvLine, stdout); } /* */ /*****************************************************************************/ wolfSSL_write(sslResume, srTest, sizeof(srTest)); /* Cleanup memory used for storing the session information */ wolfSSL_shutdown(sslResume); wolfSSL_free(sslResume); close(sockfd); wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); return 0; }
int main() { int sockfd; int connd; struct sockaddr_in servAddr; struct sockaddr_in clientAddr; socklen_t size = sizeof(clientAddr); char command[256]; char buffer[256]; int shutDown = 0; int ret, err, firstRead, gotFirstG, echoSz; unsigned char serverDer[2048]; int serverDerSz = sizeof(serverDer); /* PEM certificate buffers */ unsigned char server[2048]; unsigned char serveK[2048]; unsigned char cert[4096]; /* certificate chain to send */ int serverSz = sizeof(server); int serveKSz = sizeof(serveK); int certSz = sizeof(cert); /* declare wolfSSL objects */ WOLFSSL_CTX* ctx; WOLFSSL* ssl; wolfSSL_Debugging_ON(); /* Initialize wolfSSL */ wolfSSL_Init(); /* create new certificate with IP address as common name */ if (createSignedCert( (unsigned char*)server_cert_der_2048, sizeof_server_cert_der_2048, (unsigned char*)server_key_der_2048, sizeof_server_key_der_2048, serverDer, &serverDerSz, server, &serverSz, serveK, &serveKSz, "127.0.0.1", 0) != 0) { fprintf(stderr, "Failure creating new certificate\n"); return -1; } XMEMCPY(cert, server, serverSz); /* convert CA to PEM format */ ret = wc_DerToPem((unsigned char*)server_cert_der_2048, sizeof_server_cert_der_2048, cert + serverSz, certSz - serverSz, CERT_TYPE); if (ret <= 0) { fprintf(stderr, "error converting CA to PEM format.\n"); return -1; } certSz = ret + serverSz; { /* for debugging print out created certificate to files */ FILE* f = fopen("created_chain.pem", "wb"); if (f != NULL ) { fwrite(cert, 1, certSz, f); fclose(f); } f = fopen("created_cert.der", "wb"); if (f != NULL ) { fwrite(server, 1, serverSz, f); fclose(f); } f = fopen("created_key.der", "wb"); if (f != NULL ) { fwrite(serveK, 1, serveKSz, f); fclose(f); } } /* Create a socket that uses an internet IPv4 address, * Sets the socket to be stream based (TCP), * 0 means choose the default protocol. */ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "ERROR: failed to create the socket\n"); return -1; } /* Create and initialize WOLFSSL_CTX */ if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method())) == NULL) { fprintf(stderr, "ERROR: failed to create WOLFSSL_CTX\n"); return -1; } /* For this example load certificate chain into WOLFSSL_CTX */ if (wolfSSL_CTX_use_certificate_chain_buffer(ctx, cert, certSz) != SSL_SUCCESS) { fprintf(stderr, "ERROR: failed to load certificate chain.\n"); return -1; } /* Load server key into WOLFSSL_CTX */ if (wolfSSL_CTX_use_PrivateKey_buffer(ctx, serveK, serveKSz, SSL_FILETYPE_ASN1) != SSL_SUCCESS) { fprintf(stderr, "ERROR: failed to load server key.\n"); return -1; } /* Initialize the server address struct with zeros */ memset(&servAddr, 0, sizeof(servAddr)); /* Fill in the server address */ servAddr.sin_family = AF_INET; /* using IPv4 */ servAddr.sin_port = htons(DEFAULT_PORT); /* on DEFAULT_PORT */ servAddr.sin_addr.s_addr = INADDR_ANY; /* from anywhere */ /* Bind the server socket to our port */ if (bind(sockfd, (struct sockaddr*)&servAddr, sizeof(servAddr)) == -1) { fprintf(stderr, "ERROR: failed to bind\n"); return -1; } /* Listen for a new connection, allow 5 pending connections */ if (listen(sockfd, 5) == -1) { fprintf(stderr, "ERROR: failed to listen\n"); return -1; } /* Continue to accept clients until shutdown is issued */ while (!shutDown) { printf("Waiting for a connection...\n"); /* Accept client connections */ if ((connd = accept(sockfd, (struct sockaddr*)&clientAddr, &size)) == -1) { fprintf(stderr, "ERROR: failed to accept the connection\n\n"); return -1; } /* Create a WOLFSSL object */ if ((ssl = wolfSSL_new(ctx)) == NULL) { fprintf(stderr, "ERROR: failed to create WOLFSSL object\n"); return -1; } /* Attach wolfSSL to the socket */ wolfSSL_set_fd(ssl, connd); printf("Client connected successfully\n"); /* Very basic HTTP GET command -- intended to be used as an example. * read and write from wolfssl-root/examples/echoserver/echoserver.c */ while (1) { err = 0; /* reset error */ ret = wolfSSL_read(ssl, command, sizeof(command)-1); if (ret <= 0) { err = wolfSSL_get_error(ssl, 0); if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_ZERO_RETURN){ printf("SSL_read echo error %d, %s!\n", err, wolfSSL_ERR_error_string(err, buffer)); } break; } echoSz = ret; if (firstRead == 1) { firstRead = 0; /* browser may send 1 byte 'G' to start */ if (echoSz == 1 && command[0] == 'G') { gotFirstG = 1; continue; } } else if (gotFirstG == 1 && strncmp(command, "ET /", 4) == 0) { strncpy(command, "GET", 4); /* fall through to normal GET */ } if ( strncmp(command, "quit", 4) == 0) { printf("client sent quit command: shutting down!\n"); shutDown = 1; break; } if ( strncmp(command, "break", 5) == 0) { printf("client sent break command: closing session!\n"); break; } if ( strncmp(command, "GET", 3) == 0) { char type[] = "HTTP/1.0 200 ok\r\nContent-type:" " text/html\r\n\r\n"; char header[] = "<html><body BGCOLOR=\"#ffffff\">\n<pre>\n"; char body[] = "greetings from wolfSSL\n"; char footer[] = "</body></html>\r\n\r\n"; strncpy(command, type, sizeof(type)); echoSz = sizeof(type) - 1; strncpy(&command[echoSz], header, sizeof(header)); echoSz += (int)sizeof(header) - 1; strncpy(&command[echoSz], body, sizeof(body)); echoSz += (int)sizeof(body) - 1; strncpy(&command[echoSz], footer, sizeof(footer)); echoSz += (int)sizeof(footer); err = 0; /* reset error */ ret = wolfSSL_write(ssl, command, echoSz); if (ret <= 0) { err = wolfSSL_get_error(ssl, 0); } if (ret != echoSz) { printf("SSL_write get error = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); printf("SSL_write get failed\n"); } break; } command[echoSz] = 0; ret = wolfSSL_write(ssl, command, echoSz); if (ret <= 0) { printf("Error %d\n", wolfSSL_get_error(ssl, 0)); break; } if (ret != echoSz) { printf("SSL_write echo error = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); printf("SSL_write echo failed\n"); } } /* Cleanup after this connection */ wolfSSL_free(ssl); /* Free the wolfSSL object */ close(connd); /* Close the connection to the client */ } printf("Shutdown complete\n"); /* Cleanup and return */ wolfSSL_CTX_free(ctx); /* Free the wolfSSL context object */ wolfSSL_Cleanup(); /* Cleanup the wolfSSL environment */ close(sockfd); /* Close the socket listening for clients */ return 0; /* Return reporting a success */ }
/* See the comments at the top of main.c. */ void vSecureTCPClientTask( void *pvParameters ) { SOCKET xClientSocket; struct sockaddr_in xConnection; WOLFSSL* xWolfSSL_Object; WORD wVersionRequested; WSADATA xWSAData; char cString[ 50 ]; BaseType_t lReturned; uint32_t ulCount = 0UL; /* Remove compiler warning about unused parameters. */ ( void ) pvParameters; /* Prepare to use WinSock. */ wVersionRequested = MAKEWORD( 2, 2 ); configASSERT( WSAStartup( wVersionRequested, &xWSAData ) == 0 ); /* Set family and port for client socket. */ memset( ( void * ) &xConnection, 0x00, sizeof( struct sockaddr_in ) ); xConnection.sin_family = AF_INET; xConnection.sin_addr.s_addr = inet_addr("127.0.0.1"); xConnection.sin_port = htons( configTCP_PORT_NUMBER ); /* Attempt to create a context that uses the TLS 1.2 server protocol. */ xWolfSSL_ClientContext = wolfSSL_CTX_new( wolfTLSv1_2_client_method() ); configASSERT( xWolfSSL_ClientContext ); /* Load the CA certificate. */ lReturned = wolfSSL_CTX_load_verify_locations( xWolfSSL_ClientContext, "ca-cert.pem", 0 ); configASSERT( lReturned == SSL_SUCCESS ); for( ;; ) { /* Create the socket. */ xClientSocket = socket( AF_INET, SOCK_STREAM, 0 ); configASSERT( xClientSocket != INVALID_SOCKET ); /* Connect to the secure server. */ if( connect( xClientSocket, ( SOCKADDR * ) &xConnection, sizeof( xConnection ) ) == 0 ) { /* The connect was successful. Create a wolfSSL object to associate with this connection. */ xWolfSSL_Object = wolfSSL_new( xWolfSSL_ClientContext ); if( xWolfSSL_Object != NULL ) { /* Associate the created wolfSSL object with the connected socket. */ lReturned = wolfSSL_set_fd( xWolfSSL_Object, xClientSocket ); configASSERT( lReturned == SSL_SUCCESS ); /* The count is used to differentiate between messages sent to the server, and to break out of the do while loop below. */ ulCount = 0UL; do { /* Create the string that is sent to the secure server. */ sprintf( cString, "Message number %lu\r\n", ulCount ); /* The next line is the secure equivalent of the standard sockets call: lReturned = send( xClientSocket, cString, strlen( cString ) + 1, 0 ); */ lReturned = wolfSSL_write( xWolfSSL_Object, cString, strlen( cString ) + 1 ); /* Short delay to prevent the messages streaming up the console too quickly. */ vTaskDelay( 50 ); ulCount++; } while( ( lReturned != SOCKET_ERROR ) && ( ulCount < 10UL ) ); } wolfSSL_free( xWolfSSL_Object ); closesocket( xClientSocket ); /* Delay for a short time before starting over. */ vTaskDelay( 250 ); } } }
int main() { int listenfd, connfd; int opt; struct sockaddr_in cliAddr, servAddr; char buff[MAXLINE]; socklen_t cliLen; WOLFSSL_CTX* ctx; wolfSSL_Init(); if ((ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())) == NULL) { printf("Fatal error : wolfSSL_CTX_new error\n"); return 1; } /* use psk suite for security */ wolfSSL_CTX_set_psk_server_callback(ctx, my_psk_server_cb); wolfSSL_CTX_use_psk_identity_hint(ctx, "wolfssl server"); if (wolfSSL_CTX_set_cipher_list(ctx, "PSK-AES128-CBC-SHA256") != SSL_SUCCESS) printf("Fatal error : server can't set cipher list\n"); /* find a socket */ listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { printf("Fatal error : socket error\n"); return 1; } /* set up server address and port */ memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(SERV_PORT); /* bind to a socket */ opt = 1; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void*)&opt, sizeof(int)) != 0) { printf("Fatal error : setsockopt errer"); return 1; } if (bind(listenfd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { printf("Fatal error : bind error\n"); return 1; } /* main loop for accepting and responding to clients */ for ( ; ; ) { WOLFSSL* ssl; /* listen to the socket */ if (listen(listenfd, LISTENQ) < 0) { printf("Fatal error : listen error\n"); return 1; } cliLen = sizeof(cliAddr); connfd = accept(listenfd, (struct sockaddr *) &cliAddr, &cliLen); if (connfd < 0) { if (errno != EINTR) { printf("Fatal error : accept error\n"); return 1; } } else { printf("Connection from %s, port %d\n", inet_ntop(AF_INET, &cliAddr.sin_addr, buff, sizeof(buff)), ntohs(cliAddr.sin_port)); /* create WOLFSSL object */ if ((ssl = wolfSSL_new(ctx)) == NULL) { printf("Fatal error : wolfSSL_new error\n"); return 1; } wolfSSL_set_fd(ssl, connfd); /* set wolfSSL and socket to non blocking and respond */ wolfSSL_set_using_nonblock(ssl, 1); if (fcntl(connfd, F_SETFL, O_NONBLOCK) < 0) { printf("Fatal error : fcntl set failed\n"); return 1; } if (respond(ssl) != 0) printf("Fatal error : respond error\n"); return 1; /* closes the connections after responding */ wolfSSL_shutdown(ssl); wolfSSL_free(ssl); if (close(connfd) == -1) { printf("Fatal error : close error\n"); return 1; } } } /* free up memory used by wolfssl */ wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); return 0; }
int main(int argc, char **argv){ int sockfd, sock, ret; WOLFSSL* ssl; WOLFSSL* sslResume = 0; WOLFSSL_SESSION* session = 0; WOLFSSL_CTX* ctx; struct sockaddr_in servaddr;; /* must include an ip address of this will flag */ if (argc != 2) { printf("Usage: tcpClient <IPaddress>\n"); return 1; } wolfSSL_Init(); /* initialize wolfSSL */ /* create and initialize WOLFSSL_CTX structure */ if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())) == NULL) { fprintf(stderr, "SSL_CTX_new error.\n"); return 1; } /* create a stream socket using tcp,internet protocal IPv4, * full-duplex stream */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* places n zero-valued bytes in the address servaddr */ memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); /* converts IPv4 addresses from text to binary form */ ret = inet_pton(AF_INET, argv[1], &servaddr.sin_addr); if (ret != 1){ return 1; } /* set up pre shared keys */ wolfSSL_CTX_set_psk_client_callback(ctx, My_Psk_Client_Cb); /* attempts to make a connection on a socket */ ret = connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); if (ret != 0 ){ return 1; } /* create wolfSSL object after each tcp connect */ if ( (ssl = wolfSSL_new(ctx)) == NULL) { fprintf(stderr, "wolfSSL_new error.\n"); return 1; } /* associate the file descriptor with the session */ wolfSSL_set_fd(ssl, sockfd); /* takes inputting string and outputs it to the server */ SendReceive(ssl); /* Save the session ID to reuse */ session = wolfSSL_get_session(ssl); sslResume = wolfSSL_new(ctx); /* shut down wolfSSL */ wolfSSL_shutdown(ssl); /* close connection */ close(sockfd); /* cleanup */ wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); /* * resume session, start new connection and socket */ /* start a new socket connection */ sock = socket(AF_INET, SOCK_STREAM, 0); /* connect to the socket */ ret = connect(sock, (struct sockaddr *) &servaddr, sizeof(servaddr)); if (ret != 0){ return 1; } /* set the session ID to connect to the server */ wolfSSL_set_fd(sslResume, sock); wolfSSL_set_session(sslResume, session); /* check has connect successfully */ if (wolfSSL_connect(sslResume) != SSL_SUCCESS) { printf("SSL resume failed\n"); return 1; } /* takes inputting string and outputs it to the server */ ret = SendReceive(sslResume); if (ret != 0) { return 1; } /* check to see if the session id is being reused */ if (wolfSSL_session_reused(sslResume)) printf("reused session id\n"); else printf("didn't reuse session id!!!\n"); /* shut down wolfSSL */ wolfSSL_shutdown(sslResume); /* shut down socket */ close(sock); /* clean up */ wolfSSL_free(sslResume); wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); return ret; }
int WolfSSLConnection::connect(const char* host, const int port) { int result; if(sslContext == NULL) { LogError("NULL SSL context\r\n"); result = __LINE__; } else { if (init_socket(SOCK_STREAM) < 0) { LogError("init_socket failed\r\n"); result = __LINE__; } else { if (set_address(host, port) != 0) { LogError("set_address failed\r\n"); result = __LINE__; } else if (lwip_connect(_sock_fd, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)) < 0) { close(); LogError("lwip_connect failed\r\n"); result = __LINE__; } else { wolfSSL_SetIOSend(sslContext, &sendCallback); wolfSSL_SetIORecv(sslContext, &receiveCallback); ssl = wolfSSL_new(sslContext); if(ssl == NULL) { LogError("wolfssl new error\r\n"); result = __LINE__; } else { wolfSSL_set_fd(ssl, _sock_fd); result = wolfSSL_connect(ssl); if (result != SSL_SUCCESS) { LogError("wolfssl connect error=%d\r\n", result); result = __LINE__; } else { result = 0; isConnected = true; } } } } } return result; };
static THREAD_RETURN WOLFSSL_THREAD test_server_nofail(void* args) { SOCKET_T sockfd = 0; SOCKET_T clientfd = 0; word16 port = wolfSSLPort; WOLFSSL_METHOD* method = 0; WOLFSSL_CTX* ctx = 0; WOLFSSL* ssl = 0; char msg[] = "I hear you fa shizzle!"; char input[1024]; int idx; #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif ((func_args*)args)->return_code = TEST_FAIL; method = wolfSSLv23_server_method(); ctx = wolfSSL_CTX_new(method); #if defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API) && \ !defined(WOLFSSL_SNIFFER) && !defined(WOLFSSL_MDK_SHELL) && \ !defined(WOLFSSL_TIRTOS) port = 0; #endif wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); #ifdef OPENSSL_EXTRA wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); #endif if (wolfSSL_CTX_load_verify_locations(ctx, cliCert, 0) != SSL_SUCCESS) { /*err_sys("can't load ca file, Please run from wolfSSL home dir");*/ goto done; } if (wolfSSL_CTX_use_certificate_file(ctx, svrCert, SSL_FILETYPE_PEM) != SSL_SUCCESS) { /*err_sys("can't load server cert chain file, " "Please run from wolfSSL home dir");*/ goto done; } if (wolfSSL_CTX_use_PrivateKey_file(ctx, svrKey, SSL_FILETYPE_PEM) != SSL_SUCCESS) { /*err_sys("can't load server key file, " "Please run from wolfSSL home dir");*/ goto done; } ssl = wolfSSL_new(ctx); tcp_accept(&sockfd, &clientfd, (func_args*)args, port, 0, 0, 0); CloseSocket(sockfd); wolfSSL_set_fd(ssl, clientfd); #ifdef NO_PSK #if !defined(NO_FILESYSTEM) && !defined(NO_DH) wolfSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM); #elif !defined(NO_DH) SetDH(ssl); /* will repick suites with DHE, higher priority than PSK */ #endif #endif if (wolfSSL_accept(ssl) != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("error = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); /*err_sys("SSL_accept failed");*/ goto done; } idx = wolfSSL_read(ssl, input, sizeof(input)-1); if (idx > 0) { input[idx] = 0; printf("Client message: %s\n", input); } if (wolfSSL_write(ssl, msg, sizeof(msg)) != sizeof(msg)) { /*err_sys("SSL_write failed");*/ #ifdef WOLFSSL_TIRTOS return; #else return 0; #endif } #ifdef WOLFSSL_TIRTOS Task_yield(); #endif done: wolfSSL_shutdown(ssl); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); CloseSocket(clientfd); ((func_args*)args)->return_code = TEST_SUCCESS; #ifdef WOLFSSL_TIRTOS fdCloseSession(Task_self()); #endif #if defined(NO_MAIN_DRIVER) && defined(HAVE_ECC) && defined(FP_ECC) \ && defined(HAVE_THREAD_LS) wc_ecc_fp_free(); /* free per thread cache */ #endif #ifndef WOLFSSL_TIRTOS return 0; #endif }
int main(int argc, char** argv) { /* cont short for "continue?", Loc short for "location" */ int cont = 0; char caCertLoc[] = "../certs/ca-cert.pem"; char servCertLoc[] = "../certs/server-cert.pem"; char servKeyLoc[] = "../certs/server-key.pem"; WOLFSSL_CTX* ctx; /* Variables for awaiting datagram */ int on = 1; int res = 1; int connfd = 0; int recvLen = 0; /* length of message */ int listenfd = 0; /* Initialize our socket */ WOLFSSL* ssl = NULL; socklen_t cliLen; socklen_t len = sizeof(int); unsigned char b[MSGLEN]; /* watch for incoming messages */ char buff[MSGLEN]; /* the incoming message */ char ack[] = "I hear you fashizzle!\n"; /* Code for handling signals */ struct sigaction act, oact; act.sa_handler = sig_handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGINT, &act, &oact); /* "./config --enable-debug" and uncomment next line for debugging */ /* wolfSSL_Debugging_ON(); */ /* Initialize wolfSSL */ wolfSSL_Init(); /* Set ctx to DTLS 1.2 */ if ((ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method())) == NULL) { printf("wolfSSL_CTX_new error.\n"); return 1; } /* Load CA certificates */ if (wolfSSL_CTX_load_verify_locations(ctx,caCertLoc,0) != SSL_SUCCESS) { printf("Error loading %s, please check the file.\n", caCertLoc); return 1; } /* Load server certificates */ if (wolfSSL_CTX_use_certificate_file(ctx, servCertLoc, SSL_FILETYPE_PEM) != SSL_SUCCESS) { printf("Error loading %s, please check the file.\n", servCertLoc); return 1; } /* Load server Keys */ if (wolfSSL_CTX_use_PrivateKey_file(ctx, servKeyLoc, SSL_FILETYPE_PEM) != SSL_SUCCESS) { printf("Error loading %s, please check the file.\n", servKeyLoc); return 1; } /* Await Datagram */ while (cleanup != 1) { /* Create a UDP/IP socket */ if ((listenfd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ) { printf("Cannot create socket.\n"); cleanup = 1; } printf("Socket allocated\n"); /* clear servAddr each loop */ memset((char *)&servAddr, 0, sizeof(servAddr)); /* host-to-network-long conversion (htonl) */ /* host-to-network-short conversion (htons) */ servAddr.sin6_family = AF_INET6; servAddr.sin6_port = htons(SERV_PORT); /* Eliminate socket already in use error */ res = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, len); if (res < 0) { printf("Setsockopt SO_REUSEADDR failed.\n"); cleanup = 1; cont = 1; } /*Bind Socket*/ if (bind(listenfd, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0) { printf("Bind failed.\n"); cleanup = 1; cont = 1; } printf("Awaiting client connection on port %d\n", SERV_PORT); cliLen = sizeof(cliaddr); connfd = (int)recvfrom(listenfd, (char *)&b, sizeof(b), MSG_PEEK, (struct sockaddr*)&cliaddr, &cliLen); if (connfd < 0) { printf("No clients in que, enter idle state\n"); continue; } else if (connfd > 0) { if (connect(listenfd, (const struct sockaddr *)&cliaddr, sizeof(cliaddr)) != 0) { printf("Udp connect failed.\n"); cleanup = 1; cont = 1; } } else { printf("Recvfrom failed.\n"); cleanup = 1; cont = 1; } printf("Connected!\n"); /* Create the WOLFSSL Object */ if ((ssl = wolfSSL_new(ctx)) == NULL) { printf("wolfSSL_new error.\n"); cleanup = 1; cont = 1; } /* set the session ssl to client connection port */ wolfSSL_set_fd(ssl, listenfd); if (wolfSSL_accept(ssl) != SSL_SUCCESS) { int e = wolfSSL_get_error(ssl, 0); printf("error = %d, %s\n", e, wolfSSL_ERR_reason_error_string(e)); printf("SSL_accept failed.\n"); continue; } if ((recvLen = wolfSSL_read(ssl, buff, sizeof(buff)-1)) > 0) { printf("heard %d bytes\n", recvLen); buff[recvLen] = 0; printf("I heard this: \"%s\"\n", buff); } else if (recvLen < 0) { int readErr = wolfSSL_get_error(ssl, 0); if(readErr != SSL_ERROR_WANT_READ) { printf("SSL_read failed.\n"); cleanup = 1; cont = 1; } } if (wolfSSL_write(ssl, ack, sizeof(ack)) < 0) { printf("wolfSSL_write fail.\n"); cleanup = 1; cont = 1; } else { printf("Sending reply.\n"); } printf("reply sent \"%s\"\n", ack); wolfSSL_set_fd(ssl, 0); wolfSSL_shutdown(ssl); wolfSSL_free(ssl); printf("Client left cont to idle state\n"); cont = 0; } /* With the "continue" keywords, it is possible for the loop to exit * * without changing the value of cont */ if (cleanup == 1) { cont = 1; } if (cont == 1) { wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); } return 0; }
int main(int argc, char **argv) { int sockfd, ret; WOLFSSL_CTX* ctx; WOLFSSL* ssl; struct sockaddr_in servaddr;; /* must include an ip address of this will flag */ if (argc != 2) { printf("Usage: tcpClient <IPaddress>\n"); return 1; } wolfSSL_Init(); /* initialize wolfSSL */ /* create and initialize WOLFSSL_CTX structure */ if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())) == NULL) { fprintf(stderr, "SSL_CTX_new error.\n"); return 1; } /* create a stream socket using tcp,internet protocal IPv4, * full-duplex stream */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* places n zero-valued bytes in the address servaddr */ memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); /* converts IPv4 addresses from text to binary form */ ret = inet_pton(AF_INET, argv[1], &servaddr.sin_addr); if (ret != 1) { printf("inet_pton error\n"); return 1; } /* set up pre shared keys */ wolfSSL_CTX_set_psk_client_callback(ctx,My_Psk_Client_Cb); /* attempts to make a connection on a socket */ ret = connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); if (ret != 0) { printf("Connection Error\n"); return 1; } /* create wolfSSL object after each tcp connect */ if ((ssl = wolfSSL_new(ctx)) == NULL) { fprintf(stderr, "wolfSSL_new error.\n"); return 1; } /* associate the file descriptor with the session */ wolfSSL_set_fd(ssl, sockfd); /* tell wolfSSL that nonblocking is going to be used */ wolfSSL_set_using_nonblock(ssl, 1); /* invokes the fcntl callable service to get the file status * flags for a file. checks if it returns an error, if it does * stop program */ int flags = fcntl(sockfd, F_GETFL, 0); if (flags < 0) { printf("fcntl get failed\n"); return 1; } /* invokes the fcntl callable service to set file status flags. * Do not block an open, a read, or a write on the file * (do not wait for terminal input. If an error occurs, * stop program*/ flags = fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); if (flags < 0) { printf("fcntl set failed\n"); return 1; } /* setting up and running nonblocking socket */ ret = NonBlockingSSL_Connect(ssl); if (ret != 0) { return 1; } /* takes inputting string and outputs it to the server */ ret = SendReceive(ssl); if (ret != 0) { return 1; } /* cleanup */ wolfSSL_free(ssl); /* when completely done using SSL/TLS, free the * wolfssl_ctx object */ wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); return ret; }
static void run_wolfssl_client(void* args) { callback_functions* callbacks = ((func_args*)args)->callbacks; WOLFSSL_CTX* ctx = wolfSSL_CTX_new(callbacks->method()); WOLFSSL* ssl = NULL; SOCKET_T sfd = 0; char msg[] = "hello wolfssl server!"; int len = (int) XSTRLEN(msg); char input[1024]; int idx; #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif ((func_args*)args)->return_code = TEST_FAIL; #ifdef OPENSSL_EXTRA wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); #endif AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_load_verify_locations(ctx, caCert, 0)); AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_use_certificate_file(ctx, cliCert, SSL_FILETYPE_PEM)); AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file(ctx, cliKey, SSL_FILETYPE_PEM)); if (callbacks->ctx_ready) callbacks->ctx_ready(ctx); tcp_connect(&sfd, wolfSSLIP, ((func_args*)args)->signal->port, 0); ssl = wolfSSL_new(ctx); wolfSSL_set_fd(ssl, sfd); if (callbacks->ssl_ready) callbacks->ssl_ready(ssl); if (wolfSSL_connect(ssl) != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("error = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); } else { AssertIntEQ(len, wolfSSL_write(ssl, msg, len)); if (0 < (idx = wolfSSL_read(ssl, input, sizeof(input)-1))) { input[idx] = 0; printf("Server response: %s\n", input); } } if (callbacks->on_result) callbacks->on_result(ssl); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); CloseSocket(sfd); ((func_args*)args)->return_code = TEST_SUCCESS; #ifdef WOLFSSL_TIRTOS fdCloseSession(Task_self()); #endif }
static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) { callback_functions* callbacks = ((func_args*)args)->callbacks; WOLFSSL_CTX* ctx = wolfSSL_CTX_new(callbacks->method()); WOLFSSL* ssl = NULL; SOCKET_T sfd = 0; SOCKET_T cfd = 0; word16 port = wolfSSLPort; char msg[] = "I hear you fa shizzle!"; int len = (int) XSTRLEN(msg); char input[1024]; int idx; #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif ((func_args*)args)->return_code = TEST_FAIL; #if defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API) && \ !defined(WOLFSSL_SNIFFER) && !defined(WOLFSSL_MDK_SHELL) && \ !defined(WOLFSSL_TIRTOS) port = 0; #endif wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); #ifdef OPENSSL_EXTRA wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); #endif AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_load_verify_locations(ctx, cliCert, 0)); AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_use_certificate_file(ctx, svrCert, SSL_FILETYPE_PEM)); AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file(ctx, svrKey, SSL_FILETYPE_PEM)); if (callbacks->ctx_ready) callbacks->ctx_ready(ctx); ssl = wolfSSL_new(ctx); tcp_accept(&sfd, &cfd, (func_args*)args, port, 0, 0, 0); CloseSocket(sfd); wolfSSL_set_fd(ssl, cfd); #ifdef NO_PSK #if !defined(NO_FILESYSTEM) && !defined(NO_DH) wolfSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM); #elif !defined(NO_DH) SetDH(ssl); /* will repick suites with DHE, higher priority than PSK */ #endif #endif if (callbacks->ssl_ready) callbacks->ssl_ready(ssl); /* AssertIntEQ(SSL_SUCCESS, wolfSSL_accept(ssl)); */ if (wolfSSL_accept(ssl) != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("error = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); } else { if (0 < (idx = wolfSSL_read(ssl, input, sizeof(input)-1))) { input[idx] = 0; printf("Client message: %s\n", input); } AssertIntEQ(len, wolfSSL_write(ssl, msg, len)); #ifdef WOLFSSL_TIRTOS Task_yield(); #endif wolfSSL_shutdown(ssl); } if (callbacks->on_result) callbacks->on_result(ssl); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); CloseSocket(cfd); ((func_args*)args)->return_code = TEST_SUCCESS; #ifdef WOLFSSL_TIRTOS fdCloseSession(Task_self()); #endif #if defined(NO_MAIN_DRIVER) && defined(HAVE_ECC) && defined(FP_ECC) \ && defined(HAVE_THREAD_LS) wc_ecc_fp_free(); /* free per thread cache */ #endif #ifndef WOLFSSL_TIRTOS return 0; #endif }
static void test_client_nofail(void* args) { SOCKET_T sockfd = 0; WOLFSSL_METHOD* method = 0; WOLFSSL_CTX* ctx = 0; WOLFSSL* ssl = 0; char msg[64] = "hello wolfssl!"; char reply[1024]; int input; int msgSz = (int)strlen(msg); #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif ((func_args*)args)->return_code = TEST_FAIL; method = wolfSSLv23_client_method(); ctx = wolfSSL_CTX_new(method); #ifdef OPENSSL_EXTRA wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); #endif if (wolfSSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS) { /* err_sys("can't load ca file, Please run from wolfSSL home dir");*/ goto done2; } if (wolfSSL_CTX_use_certificate_file(ctx, cliCert, SSL_FILETYPE_PEM) != SSL_SUCCESS) { /*err_sys("can't load client cert file, " "Please run from wolfSSL home dir");*/ goto done2; } if (wolfSSL_CTX_use_PrivateKey_file(ctx, cliKey, SSL_FILETYPE_PEM) != SSL_SUCCESS) { /*err_sys("can't load client key file, " "Please run from wolfSSL home dir");*/ goto done2; } tcp_connect(&sockfd, wolfSSLIP, ((func_args*)args)->signal->port, 0); ssl = wolfSSL_new(ctx); wolfSSL_set_fd(ssl, sockfd); if (wolfSSL_connect(ssl) != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("err = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); /*printf("SSL_connect failed");*/ goto done2; } if (wolfSSL_write(ssl, msg, msgSz) != msgSz) { /*err_sys("SSL_write failed");*/ goto done2; } input = wolfSSL_read(ssl, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("Server response: %s\n", reply); } done2: wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); CloseSocket(sockfd); ((func_args*)args)->return_code = TEST_SUCCESS; #ifdef WOLFSSL_TIRTOS fdCloseSession(Task_self()); #endif return; }
/* * ======== tcpHandler ======== * Creates new Task to handle new TCP connections. */ Void tcpHandler(UArg arg0, UArg arg1) { int sockfd; int ret; struct sockaddr_in servAddr; Error_Block eb; bool flag = true; bool internal_flag = true; int nbytes; char *buffer; char msg[] = "Hello from TM4C1294XL Connected Launchpad"; WOLFSSL* ssl = (WOLFSSL *) arg0; fdOpenSession(TaskSelf()); wolfSSL_Init(); WOLFSSL_CTX* ctx = NULL; ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method()); if (ctx == 0) { System_printf("tcpHandler: wolfSSL_CTX_new error.\n"); exitApp(ctx); } if (wolfSSL_CTX_load_verify_buffer(ctx, ca_cert_der_2048, sizeof(ca_cert_der_2048) / sizeof(char), SSL_FILETYPE_ASN1) != SSL_SUCCESS) { System_printf("tcpHandler: Error loading ca_cert_der_2048" " please check the wolfssl/certs_test.h file.\n"); exitApp(ctx); } if (wolfSSL_CTX_use_certificate_buffer(ctx, client_cert_der_2048, sizeof(client_cert_der_2048) / sizeof(char), SSL_FILETYPE_ASN1) != SSL_SUCCESS) { System_printf("tcpHandler: Error loading client_cert_der_2048," " please check the wolfssl/certs_test.h file.\n"); exitApp(ctx); } if (wolfSSL_CTX_use_PrivateKey_buffer(ctx, client_key_der_2048, sizeof(client_key_der_2048) / sizeof(char), SSL_FILETYPE_ASN1) != SSL_SUCCESS) { System_printf("tcpHandler: Error loading client_key_der_2048," " please check the wolfssl/certs_test.h file.\n"); exitApp(ctx); } /* Init the Error_Block */ Error_init(&eb); do { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { System_printf("tcpHandler: socket failed\n"); Task_sleep(2000); continue; } memset((char *) &servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(TCPPORT); inet_aton(IP_ADDR, &servAddr.sin_addr); ret = connect(sockfd, (struct sockaddr *) &servAddr, sizeof(servAddr)); if (ret < 0) { fdClose((SOCKET) sockfd); Task_sleep(2000); continue; } } while (ret != 0); if ((ssl = wolfSSL_new(ctx)) == NULL) { System_printf("tcpHandler: wolfSSL_new error.\n"); exitApp(ctx); } wolfSSL_set_fd(ssl, sockfd); ret = wolfSSL_connect(ssl); /* Delete "TOP_LINE" and "END_LINE" for debugging. */ /* TOP_LINE System_printf("looked for: %d.\n", SSL_SUCCESS); System_printf("return was: %d.\n", ret); int err; char err_buffer[80]; err = wolfSSL_get_error(ssl, 0); System_printf("wolfSSL error: %d\n", err); System_printf("wolfSSL error string: %s\n", wolfSSL_ERR_error_string(err, err_buffer)); END_LINE */ if (ret == SSL_SUCCESS) { sockfd = wolfSSL_get_fd(ssl); /* Get a buffer to receive incoming packets. Use the default heap. */ buffer = Memory_alloc(NULL, TCPPACKETSIZE, 0, &eb); if (buffer == NULL) { System_printf("tcpWorker: failed to alloc memory\n"); exitApp(ctx); } /* Say hello to the server */ while (flag) { if (wolfSSL_write(ssl, msg, strlen(msg)) != strlen(msg)) { ret = wolfSSL_get_error(ssl, 0); System_printf("Write error: %i.\n", ret); } while (internal_flag) { nbytes = wolfSSL_read(ssl, (char *) buffer, TCPPACKETSIZE); if (nbytes > 0) { internal_flag = false; } } /* success */ System_printf("Heard: \"%s\".\n", buffer); wolfSSL_free(ssl); fdClose((SOCKET) sockfd); flag = false; } /* Free the buffer back to the heap */ Memory_free(NULL, buffer, TCPPACKETSIZE); /* * Since deleteTerminatedTasks is set in the cfg file, * the Task will be deleted when the idle task runs. */ exitApp(ctx); } else { wolfSSL_free(ssl); fdClose((SOCKET) sockfd); System_printf("wolfSSL_connect failed.\n"); fdCloseSession(TaskSelf()); exitApp(ctx); } }
/* See the comments at the top of main.c. */ void vSecureTCPServerTask( void *pvParameters ) { BaseType_t xReturned; long lBytes; uint8_t cReceivedString[ 60 ]; struct sockaddr_in xClient; int xClientAddressLength = sizeof( struct sockaddr_in ); SOCKET xListeningSocket, xConnectedSocket; WOLFSSL* xWolfSSL_Object; /* Only one connection is accepted at a time, so only one object is needed at a time. */ /* Just to prevent compiler warnings. */ ( void ) pvParameters; /* Perform the initialisation necessary before wolfSSL can be used. */ prvInitialiseWolfSSL(); configASSERT( xWolfSSL_ServerContext ); /* Attempt to open the socket. */ xListeningSocket = prvOpenServerSocket(); /* Now the server socket has been created and the wolfSSL library has been initialised, the task that implements the client side can be created. */ xTaskCreate( vSecureTCPClientTask, "Client", configMINIMAL_STACK_SIZE, NULL, sstSECURE_CLIENT_TASK_PRIORITY, NULL ); if( xListeningSocket != INVALID_SOCKET ) { for( ;; ) { /* Wait until the client connects. */ printf( "Waiting for new connection\r\n" ); xConnectedSocket = accept( xListeningSocket, ( struct sockaddr * ) &xClient, &xClientAddressLength ); if( xConnectedSocket != INVALID_SOCKET ) { printf( "Connection established\r\n" ); /* A connection has been accepted by the server. Create a wolfSSL object for use with the newly connected socket. */ xWolfSSL_Object = NULL; xWolfSSL_Object = wolfSSL_new( xWolfSSL_ServerContext ); if( xWolfSSL_Object != NULL ) { /* Associate the created wolfSSL object with the connected socket. */ xReturned = wolfSSL_set_fd( xWolfSSL_Object, xConnectedSocket ); configASSERT( xReturned == SSL_SUCCESS ); do { /* The next line is the secure equivalent to the standard sockets call: lBytes = recv( xConnectedSocket, cReceivedString, 50, 0 ); */ lBytes = wolfSSL_read( xWolfSSL_Object, cReceivedString, sizeof( cReceivedString ) ); /* Print the received characters. */ if( lBytes > 0 ) { printf( "Received by the secure server: %s\r\n", cReceivedString ); } } while ( lBytes > 0 ); /* The connection was closed, close the socket and free the wolfSSL object. */ closesocket( xConnectedSocket ); wolfSSL_free( xWolfSSL_Object ); printf( "Connection closed, back to start\r\n\r\n" ); } } } } else { /* The socket could not be opened. */ vTaskDelete( NULL ); } }
int main(int argc, char **argv) { int ret, sockfd; WOLFSSL* ssl; WOLFSSL_CTX* ctx; struct sockaddr_in servaddr;; /* must include an ip address of this will flag */ if (argc != 2) { printf("Usage: tcpClient <IPaddress>\n"); return 1; } wolfSSL_Init(); /* initialize wolfSSL */ /* create and initialize WOLFSSL_CTX structure */ if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())) == NULL) { fprintf(stderr, "SSL_CTX_new error.\n"); return 1; } /* create a stream socket using tcp,internet protocal IPv4, * full-duplex stream */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* places n zero-valued bytes in the address servaddr */ memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); /* converts IPv4 addresses from text to binary form */ ret = inet_pton(AF_INET, argv[1], &servaddr.sin_addr); if (ret != 1) { printf("inet_pton error\n"); return 1; } /* set up pre shared keys */ wolfSSL_CTX_set_psk_client_callback(ctx, My_Psk_Client_Cb); /* attempts to make a connection on a socket */ ret = connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); if (ret != 0) { printf("Connection Error\n"); return 1; } /* creat wolfssl object after each tcp connct */ if ( (ssl = wolfSSL_new(ctx)) == NULL) { fprintf(stderr, "wolfSSL_new error.\n"); return 1; } /* associate the file descriptor with the session */ ret = wolfSSL_set_fd(ssl, sockfd); if (ret != SSL_SUCCESS){ return 1; } /* takes inputting string and outputs it to the server */ ret = SendReceive(ssl); if(ret != 0){ return 1; } /* cleanup */ wolfSSL_free(ssl); /* when completely done using SSL/TLS, free the * wolfssl_ctx object */ wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); /* exit client */ return ret; }
THREAD_RETURN WOLFSSL_THREAD client_test(void* args) { SOCKET_T sockfd = WOLFSSL_SOCKET_INVALID; WOLFSSL_METHOD* method = 0; WOLFSSL_CTX* ctx = 0; WOLFSSL* ssl = 0; WOLFSSL* sslResume = 0; WOLFSSL_SESSION* session = 0; char resumeMsg[32] = "resuming wolfssl!"; int resumeSz = (int)strlen(resumeMsg); char msg[32] = "hello wolfssl!"; /* GET may make bigger */ char reply[80]; int input; int msgSz = (int)strlen(msg); word16 port = wolfSSLPort; char* host = (char*)wolfSSLIP; const char* domain = "localhost"; /* can't default to www.wolfssl.com because can't tell if we're really going there to detect old chacha-poly */ int ch; int version = CLIENT_INVALID_VERSION; int usePsk = 0; int useAnon = 0; int sendGET = 0; int benchmark = 0; int throughput = 0; int doDTLS = 0; int matchName = 0; int doPeerCheck = 1; int nonBlocking = 0; int resumeSession = 0; int wc_shutdown = 0; int disableCRL = 0; int externalTest = 0; int ret; int scr = 0; /* allow secure renegotiation */ int forceScr = 0; /* force client initiaed scr */ int trackMemory = 0; int useClientCert = 1; int fewerPackets = 0; int atomicUser = 0; int pkCallbacks = 0; int overrideDateErrors = 0; int minDhKeyBits = DEFAULT_MIN_DHKEY_BITS; char* alpnList = NULL; unsigned char alpn_opt = 0; char* cipherList = NULL; const char* verifyCert = caCert; const char* ourCert = cliCert; const char* ourKey = cliKey; #ifdef HAVE_SNI char* sniHostName = NULL; #endif #ifdef HAVE_MAX_FRAGMENT byte maxFragment = 0; #endif #ifdef HAVE_TRUNCATED_HMAC byte truncatedHMAC = 0; #endif #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) byte statusRequest = 0; #endif #ifdef HAVE_OCSP int useOcsp = 0; char* ocspUrl = NULL; #endif int argc = ((func_args*)args)->argc; char** argv = ((func_args*)args)->argv; ((func_args*)args)->return_code = -1; /* error state */ #ifdef NO_RSA verifyCert = (char*)eccCert; ourCert = (char*)cliEccCert; ourKey = (char*)cliEccKey; #endif (void)resumeSz; (void)session; (void)sslResume; (void)trackMemory; (void)atomicUser; (void)pkCallbacks; (void)scr; (void)forceScr; (void)ourKey; (void)ourCert; (void)verifyCert; (void)useClientCert; (void)overrideDateErrors; (void)disableCRL; (void)minDhKeyBits; (void)alpnList; (void)alpn_opt; StackTrap(); #ifndef WOLFSSL_VXWORKS while ((ch = mygetopt(argc, argv, "?gdeDusmNrwRitfxXUPCVh:p:v:l:A:c:k:Z:b:zS:F:L:ToO:aB:W:")) != -1) { switch (ch) { case '?' : Usage(); exit(EXIT_SUCCESS); case 'g' : sendGET = 1; break; case 'd' : doPeerCheck = 0; break; case 'e' : ShowCiphers(); exit(EXIT_SUCCESS); case 'D' : overrideDateErrors = 1; break; case 'C' : #ifdef HAVE_CRL disableCRL = 1; #endif break; case 'u' : doDTLS = 1; break; case 's' : usePsk = 1; break; case 't' : #ifdef USE_WOLFSSL_MEMORY trackMemory = 1; #endif break; case 'm' : matchName = 1; break; case 'x' : useClientCert = 0; break; case 'X' : externalTest = 1; break; case 'f' : fewerPackets = 1; break; case 'U' : #ifdef ATOMIC_USER atomicUser = 1; #endif break; case 'P' : #ifdef HAVE_PK_CALLBACKS pkCallbacks = 1; #endif break; case 'h' : host = myoptarg; domain = myoptarg; break; case 'p' : port = (word16)atoi(myoptarg); #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API) if (port == 0) err_sys("port number cannot be 0"); #endif break; case 'v' : version = atoi(myoptarg); if (version < 0 || version > 3) { Usage(); exit(MY_EX_USAGE); } break; case 'V' : ShowVersions(); exit(EXIT_SUCCESS); case 'l' : cipherList = myoptarg; break; case 'A' : verifyCert = myoptarg; break; case 'c' : ourCert = myoptarg; break; case 'k' : ourKey = myoptarg; break; case 'Z' : #ifndef NO_DH minDhKeyBits = atoi(myoptarg); if (minDhKeyBits <= 0 || minDhKeyBits > 16000) { Usage(); exit(MY_EX_USAGE); } #endif break; case 'b' : benchmark = atoi(myoptarg); if (benchmark < 0 || benchmark > 1000000) { Usage(); exit(MY_EX_USAGE); } break; case 'B' : throughput = atoi(myoptarg); if (throughput <= 0) { Usage(); exit(MY_EX_USAGE); } break; case 'N' : nonBlocking = 1; break; case 'r' : resumeSession = 1; break; case 'w' : wc_shutdown = 1; break; case 'R' : #ifdef HAVE_SECURE_RENEGOTIATION scr = 1; #endif break; case 'i' : #ifdef HAVE_SECURE_RENEGOTIATION scr = 1; forceScr = 1; #endif break; case 'z' : #ifndef WOLFSSL_LEANPSK wolfSSL_GetObjectSize(); #endif break; case 'S' : #ifdef HAVE_SNI sniHostName = myoptarg; #endif break; case 'F' : #ifdef HAVE_MAX_FRAGMENT maxFragment = atoi(myoptarg); if (maxFragment < WOLFSSL_MFL_2_9 || maxFragment > WOLFSSL_MFL_2_13) { Usage(); exit(MY_EX_USAGE); } #endif break; case 'T' : #ifdef HAVE_TRUNCATED_HMAC truncatedHMAC = 1; #endif break; case 'W' : #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) statusRequest = atoi(myoptarg); #endif break; case 'o' : #ifdef HAVE_OCSP useOcsp = 1; #endif break; case 'O' : #ifdef HAVE_OCSP useOcsp = 1; ocspUrl = myoptarg; #endif break; case 'a' : #ifdef HAVE_ANON useAnon = 1; #endif break; case 'L' : #ifdef HAVE_ALPN alpnList = myoptarg; if (alpnList[0] == 'C' && alpnList[1] == ':') alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH; else if (alpnList[0] == 'F' && alpnList[1] == ':') alpn_opt = WOLFSSL_ALPN_FAILED_ON_MISMATCH; else { Usage(); exit(MY_EX_USAGE); } alpnList += 2; #endif break; default: Usage(); exit(MY_EX_USAGE); } } myoptind = 0; /* reset for test cases */ #endif /* !WOLFSSL_VXWORKS */ if (externalTest) { /* detect build cases that wouldn't allow test against wolfssl.com */ int done = 0; (void)done; #ifdef NO_RSA done = 1; #endif /* www.globalsign.com does not respond to ipv6 ocsp requests */ #if defined(TEST_IPV6) && defined(HAVE_OCSP) done = 1; #endif /* www.globalsign.com has limited supported cipher suites */ #if defined(NO_AES) && defined(HAVE_OCSP) done = 1; #endif /* www.globalsign.com only supports static RSA or ECDHE with AES */ /* We cannot expect users to have on static RSA so test for ECC only * as some users will most likely be on 32-bit systems where ECC * is not enabled by default */ #if defined(HAVE_OCSP) && !defined(HAVE_ECC) done = 1; #endif #ifndef NO_PSK done = 1; #endif #ifdef NO_SHA done = 1; /* external cert chain most likely has SHA */ #endif #if !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) if (!XSTRNCMP(domain, "www.google.com", 14) || !XSTRNCMP(domain, "www.wolfssl.com", 15)) { done = 1; /* google/wolfssl need ECDHE or static RSA */ } #endif #if !defined(WOLFSSL_SHA384) if (!XSTRNCMP(domain, "www.wolfssl.com", 15)) { done = 1; /* wolfssl need sha384 for cert chain verify */ } #endif #if !defined(HAVE_AESGCM) && defined(NO_AES) && \ !(defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) done = 1; /* need at least on of these for external tests */ #endif if (done) { printf("external test can't be run in this mode"); ((func_args*)args)->return_code = 0; exit(EXIT_SUCCESS); } } /* sort out DTLS versus TLS versions */ if (version == CLIENT_INVALID_VERSION) { if (doDTLS) version = CLIENT_DTLS_DEFAULT_VERSION; else version = CLIENT_DEFAULT_VERSION; } else { if (doDTLS) { if (version == 3) version = -2; else version = -1; } } #ifdef USE_WOLFSSL_MEMORY if (trackMemory) InitMemoryTracker(); #endif switch (version) { #ifndef NO_OLD_TLS #ifdef WOLFSSL_ALLOW_SSLV3 case 0: method = wolfSSLv3_client_method(); break; #endif #ifndef NO_TLS case 1: method = wolfTLSv1_client_method(); break; case 2: method = wolfTLSv1_1_client_method(); break; #endif /* NO_TLS */ #endif /* NO_OLD_TLS */ #ifndef NO_TLS case 3: method = wolfTLSv1_2_client_method(); break; #endif #ifdef WOLFSSL_DTLS #ifndef NO_OLD_TLS case -1: method = wolfDTLSv1_client_method(); break; #endif case -2: method = wolfDTLSv1_2_client_method(); break; #endif default: err_sys("Bad SSL version"); break; } if (method == NULL) err_sys("unable to get method"); ctx = wolfSSL_CTX_new(method); if (ctx == NULL) err_sys("unable to get ctx"); if (cipherList) { if (wolfSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS) err_sys("client can't set cipher list 1"); } #ifdef WOLFSSL_LEANPSK usePsk = 1; #endif #if defined(NO_RSA) && !defined(HAVE_ECC) usePsk = 1; #endif if (fewerPackets) wolfSSL_CTX_set_group_messages(ctx); #ifndef NO_DH wolfSSL_CTX_SetMinDhKey_Sz(ctx, (word16)minDhKeyBits); #endif if (usePsk) { #ifndef NO_PSK wolfSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb); if (cipherList == NULL) { const char *defaultCipherList; #if defined(HAVE_AESGCM) && !defined(NO_DH) defaultCipherList = "DHE-PSK-AES128-GCM-SHA256"; #elif defined(HAVE_NULL_CIPHER) defaultCipherList = "PSK-NULL-SHA256"; #else defaultCipherList = "PSK-AES128-CBC-SHA256"; #endif if (wolfSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS) err_sys("client can't set cipher list 2"); } #endif useClientCert = 0; } if (useAnon) { #ifdef HAVE_ANON if (cipherList == NULL) { wolfSSL_CTX_allow_anon_cipher(ctx); if (wolfSSL_CTX_set_cipher_list(ctx,"ADH-AES128-SHA") != SSL_SUCCESS) err_sys("client can't set cipher list 4"); } #endif useClientCert = 0; } #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); #endif #if defined(WOLFSSL_SNIFFER) if (cipherList == NULL) { /* don't use EDH, can't sniff tmp keys */ if (wolfSSL_CTX_set_cipher_list(ctx, "AES128-SHA") != SSL_SUCCESS) { err_sys("client can't set cipher list 3"); } } #endif #ifdef HAVE_OCSP if (useOcsp) { if (ocspUrl != NULL) { wolfSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl); wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE | WOLFSSL_OCSP_URL_OVERRIDE); } else wolfSSL_CTX_EnableOCSP(ctx, 0); } #endif #ifdef USER_CA_CB wolfSSL_CTX_SetCACb(ctx, CaCb); #endif #ifdef VERIFY_CALLBACK wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); #endif #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) if (useClientCert){ if (wolfSSL_CTX_use_certificate_chain_file(ctx, ourCert) != SSL_SUCCESS) err_sys("can't load client cert file, check file and run from" " wolfSSL home dir"); if (wolfSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM) != SSL_SUCCESS) err_sys("can't load client private key file, check file and run " "from wolfSSL home dir"); } if (!usePsk && !useAnon) { if (wolfSSL_CTX_load_verify_locations(ctx, verifyCert,0) != SSL_SUCCESS) err_sys("can't load ca file, Please run from wolfSSL home dir"); #ifdef HAVE_ECC /* load ecc verify too, echoserver uses it by default w/ ecc */ if (wolfSSL_CTX_load_verify_locations(ctx, eccCert, 0) != SSL_SUCCESS) err_sys("can't load ecc ca file, Please run from wolfSSL home dir"); #endif /* HAVE_ECC */ } #endif /* !NO_FILESYSTEM && !NO_CERTS */ #if !defined(NO_CERTS) if (!usePsk && !useAnon && doPeerCheck == 0) wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0); if (!usePsk && !useAnon && overrideDateErrors == 1) wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myDateCb); #endif #ifdef HAVE_CAVIUM wolfSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID); #endif #ifdef HAVE_SNI if (sniHostName) if (wolfSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName)) != SSL_SUCCESS) err_sys("UseSNI failed"); #endif #ifdef HAVE_MAX_FRAGMENT if (maxFragment) if (wolfSSL_CTX_UseMaxFragment(ctx, maxFragment) != SSL_SUCCESS) err_sys("UseMaxFragment failed"); #endif #ifdef HAVE_TRUNCATED_HMAC if (truncatedHMAC) if (wolfSSL_CTX_UseTruncatedHMAC(ctx) != SSL_SUCCESS) err_sys("UseTruncatedHMAC failed"); #endif #ifdef HAVE_SESSION_TICKET if (wolfSSL_CTX_UseSessionTicket(ctx) != SSL_SUCCESS) err_sys("UseSessionTicket failed"); #endif if (benchmark) { ((func_args*)args)->return_code = ClientBenchmarkConnections(ctx, host, port, doDTLS, benchmark, resumeSession); wolfSSL_CTX_free(ctx); exit(EXIT_SUCCESS); } if(throughput) { ((func_args*)args)->return_code = ClientBenchmarkThroughput(ctx, host, port, doDTLS, throughput); wolfSSL_CTX_free(ctx); exit(EXIT_SUCCESS); } #if defined(WOLFSSL_MDK_ARM) wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0); #endif ssl = wolfSSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL object"); #ifdef HAVE_SUPPORTED_CURVES /* add curves to supported curves extension */ if (wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP256R1) != SSL_SUCCESS) { err_sys("unable to set curve secp256r1"); } if (wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP384R1) != SSL_SUCCESS) { err_sys("unable to set curve secp384r1"); } if (wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP521R1) != SSL_SUCCESS) { err_sys("unable to set curve secp521r1"); } if (wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP224R1) != SSL_SUCCESS) { err_sys("unable to set curve secp224r1"); } if (wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP192R1) != SSL_SUCCESS) { err_sys("unable to set curve secp192r1"); } if (wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP160R1) != SSL_SUCCESS) { err_sys("unable to set curve secp160r1"); } #endif #ifdef HAVE_SESSION_TICKET wolfSSL_set_SessionTicket_cb(ssl, sessionTicketCB, (void*)"initial session"); #endif #ifdef HAVE_ALPN if (alpnList != NULL) { printf("ALPN accepted protocols list : %s\n", alpnList); wolfSSL_UseALPN(ssl, alpnList, (word32)XSTRLEN(alpnList), alpn_opt); } #endif #ifdef HAVE_CERTIFICATE_STATUS_REQUEST if (statusRequest) { switch (statusRequest) { case WOLFSSL_CSR_OCSP: if (wolfSSL_UseOCSPStapling(ssl, WOLFSSL_CSR_OCSP, WOLFSSL_CSR_OCSP_USE_NONCE) != SSL_SUCCESS) err_sys("UseCertificateStatusRequest failed"); break; } wolfSSL_CTX_EnableOCSP(ctx, 0); } #endif #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 if (statusRequest) { switch (statusRequest) { case WOLFSSL_CSR2_OCSP: if (wolfSSL_UseOCSPStaplingV2(ssl, WOLFSSL_CSR2_OCSP, WOLFSSL_CSR2_OCSP_USE_NONCE) != SSL_SUCCESS) err_sys("UseCertificateStatusRequest failed"); break; case WOLFSSL_CSR2_OCSP_MULTI: if (wolfSSL_UseOCSPStaplingV2(ssl, WOLFSSL_CSR2_OCSP_MULTI, 0) != SSL_SUCCESS) err_sys("UseCertificateStatusRequest failed"); break; } wolfSSL_CTX_EnableOCSP(ctx, 0); } #endif tcp_connect(&sockfd, host, port, doDTLS, ssl); wolfSSL_set_fd(ssl, sockfd); #ifdef HAVE_CRL if (disableCRL == 0) { if (wolfSSL_EnableCRL(ssl, WOLFSSL_CRL_CHECKALL) != SSL_SUCCESS) err_sys("can't enable crl check"); if (wolfSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS) err_sys("can't load crl, check crlfile and date validity"); if (wolfSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS) err_sys("can't set crl callback"); } #endif #ifdef HAVE_SECURE_RENEGOTIATION if (scr) { if (wolfSSL_UseSecureRenegotiation(ssl) != SSL_SUCCESS) err_sys("can't enable secure renegotiation"); } #endif #ifdef ATOMIC_USER if (atomicUser) SetupAtomicUser(ctx, ssl); #endif #ifdef HAVE_PK_CALLBACKS if (pkCallbacks) SetupPkCallbacks(ctx, ssl); #endif if (matchName && doPeerCheck) wolfSSL_check_domain_name(ssl, domain); #ifndef WOLFSSL_CALLBACKS if (nonBlocking) { wolfSSL_set_using_nonblock(ssl, 1); tcp_set_nonblocking(&sockfd); NonBlockingSSL_Connect(ssl); } else if (wolfSSL_connect(ssl) != SSL_SUCCESS) { /* see note at top of README */ int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("err = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); err_sys("SSL_connect failed"); /* if you're getting an error here */ } #else timeout.tv_sec = 2; timeout.tv_usec = 0; NonBlockingSSL_Connect(ssl); /* will keep retrying on timeout */ #endif showPeer(ssl); #ifdef HAVE_ALPN if (alpnList != NULL) { int err; char *protocol_name = NULL; word16 protocol_nameSz = 0; err = wolfSSL_ALPN_GetProtocol(ssl, &protocol_name, &protocol_nameSz); if (err == SSL_SUCCESS) printf("Received ALPN protocol : %s (%d)\n", protocol_name, protocol_nameSz); else if (err == SSL_ALPN_NOT_FOUND) printf("No ALPN response received (no match with server)\n"); else printf("Getting ALPN protocol name failed\n"); } #endif #ifdef HAVE_SECURE_RENEGOTIATION if (scr && forceScr) { if (nonBlocking) { printf("not doing secure renegotiation on example with" " nonblocking yet"); } else { if (wolfSSL_Rehandshake(ssl) != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, 0); char buffer[WOLFSSL_MAX_ERROR_SZ]; printf("err = %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); err_sys("wolfSSL_Rehandshake failed"); } } } #endif /* HAVE_SECURE_RENEGOTIATION */ if (sendGET) { printf("SSL connect ok, sending GET...\n"); msgSz = 28; strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz); msg[msgSz] = '\0'; resumeSz = msgSz; strncpy(resumeMsg, "GET /index.html HTTP/1.0\r\n\r\n", resumeSz); resumeMsg[resumeSz] = '\0'; } if (wolfSSL_write(ssl, msg, msgSz) != msgSz) err_sys("SSL_write failed"); input = wolfSSL_read(ssl, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("Server response: %s\n", reply); if (sendGET) { /* get html */ while (1) { input = wolfSSL_read(ssl, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("%s\n", reply); } else break; } } } else if (input < 0) { int readErr = wolfSSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) err_sys("wolfSSL_read failed"); } #ifndef NO_SESSION_CACHE if (resumeSession) { session = wolfSSL_get_session(ssl); sslResume = wolfSSL_new(ctx); if (sslResume == NULL) err_sys("unable to get SSL object"); } #endif if (doDTLS == 0) { /* don't send alert after "break" command */ ret = wolfSSL_shutdown(ssl); if (wc_shutdown && ret == SSL_SHUTDOWN_NOT_DONE) wolfSSL_shutdown(ssl); /* bidirectional shutdown */ } #ifdef ATOMIC_USER if (atomicUser) FreeAtomicUser(ssl); #endif wolfSSL_free(ssl); CloseSocket(sockfd); #ifndef NO_SESSION_CACHE if (resumeSession) { if (doDTLS) { #ifdef USE_WINDOWS_API Sleep(500); #elif defined(WOLFSSL_TIRTOS) Task_sleep(1); #else sleep(1); #endif } tcp_connect(&sockfd, host, port, doDTLS, sslResume); wolfSSL_set_fd(sslResume, sockfd); #ifdef HAVE_ALPN if (alpnList != NULL) { printf("ALPN accepted protocols list : %s\n", alpnList); wolfSSL_UseALPN(sslResume, alpnList, (word32)XSTRLEN(alpnList), alpn_opt); } #endif #ifdef HAVE_SECURE_RENEGOTIATION if (scr) { if (wolfSSL_UseSecureRenegotiation(sslResume) != SSL_SUCCESS) err_sys("can't enable secure renegotiation"); } #endif wolfSSL_set_session(sslResume, session); #ifdef HAVE_SESSION_TICKET wolfSSL_set_SessionTicket_cb(sslResume, sessionTicketCB, (void*)"resumed session"); #endif #ifndef WOLFSSL_CALLBACKS if (nonBlocking) { wolfSSL_set_using_nonblock(sslResume, 1); tcp_set_nonblocking(&sockfd); NonBlockingSSL_Connect(sslResume); } else if (wolfSSL_connect(sslResume) != SSL_SUCCESS) err_sys("SSL resume failed"); #else timeout.tv_sec = 2; timeout.tv_usec = 0; NonBlockingSSL_Connect(ssl); /* will keep retrying on timeout */ #endif showPeer(sslResume); if (wolfSSL_session_reused(sslResume)) printf("reused session id\n"); else printf("didn't reuse session id!!!\n"); #ifdef HAVE_ALPN if (alpnList != NULL) { int err; char *protocol_name = NULL; word16 protocol_nameSz = 0; printf("Sending ALPN accepted list : %s\n", alpnList); err = wolfSSL_ALPN_GetProtocol(sslResume, &protocol_name, &protocol_nameSz); if (err == SSL_SUCCESS) printf("Received ALPN protocol : %s (%d)\n", protocol_name, protocol_nameSz); else if (err == SSL_ALPN_NOT_FOUND) printf("Not received ALPN response (no match with server)\n"); else printf("Getting ALPN protocol name failed\n"); } #endif if (wolfSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz) err_sys("SSL_write failed"); if (nonBlocking) { /* give server a chance to bounce a message back to client */ #ifdef USE_WINDOWS_API Sleep(500); #elif defined(WOLFSSL_TIRTOS) Task_sleep(1); #else sleep(1); #endif } input = wolfSSL_read(sslResume, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("Server resume response: %s\n", reply); if (sendGET) { /* get html */ while (1) { input = wolfSSL_read(sslResume, reply, sizeof(reply)-1); if (input > 0) { reply[input] = 0; printf("%s\n", reply); } else break; } } } else if (input < 0) { int readErr = wolfSSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) err_sys("wolfSSL_read failed"); } /* try to send session break */ wolfSSL_write(sslResume, msg, msgSz); ret = wolfSSL_shutdown(sslResume); if (wc_shutdown && ret == SSL_SHUTDOWN_NOT_DONE) wolfSSL_shutdown(sslResume); /* bidirectional shutdown */ wolfSSL_free(sslResume); CloseSocket(sockfd); } #endif /* NO_SESSION_CACHE */ wolfSSL_CTX_free(ctx); ((func_args*)args)->return_code = 0; #ifdef USE_WOLFSSL_MEMORY if (trackMemory) ShowMemoryTracker(); #endif /* USE_WOLFSSL_MEMORY */ #if !defined(WOLFSSL_TIRTOS) return 0; #endif }
int main() { int sd = socket(PF_INET, SOCK_STREAM, IPPROTO_SCTP); if (sd < 0) err_sys("sctp socket error"); struct sockaddr_in sa; memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = htons(12345); int ret = bind(sd, (struct sockaddr*)&sa, sizeof(sa)); if (ret < 0) err_sys("sctp bind error"); listen(sd, 3); int client_sd = accept(sd, NULL, NULL); if (client_sd < 0) err_sys("sctp accept error"); const char* response = "well hello to you"; char buffer[80]; WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method()); if (ctx == NULL) err_sys("ctx new dtls server failed"); ret = wolfSSL_CTX_dtls_set_sctp(ctx); if (ret != SSL_SUCCESS) err_sys("set sctp mode failed"); ret = wolfSSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM); if (ret != SSL_SUCCESS) err_sys("use private key error"); ret = wolfSSL_CTX_use_certificate_file(ctx, cert, SSL_FILETYPE_PEM); if (ret != SSL_SUCCESS) err_sys("use cert error"); WOLFSSL* ssl = wolfSSL_new(ctx); if (ssl == NULL) err_sys("ssl new dtls server failed"); wolfSSL_set_fd(ssl, client_sd); ret = wolfSSL_accept(ssl); if (ret != SSL_SUCCESS) err_sys("ssl accept failed"); printf("TLS version is %s\n", wolfSSL_get_version(ssl)); printf("Cipher Suite is %s\n", wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl))); int got = wolfSSL_read(ssl, buffer, sizeof(buffer)); if (got > 0) { buffer[got] = 0; printf("client said: %s\n", buffer); } wolfSSL_write(ssl, response, (int)strlen(response)); unsigned char bigBuf[4096]; wolfSSL_read(ssl, bigBuf, sizeof(bigBuf)); wolfSSL_write(ssl, bigBuf, sizeof(bigBuf)); wolfSSL_shutdown(ssl); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); close(sd); return 0; }
int ClientBenchmarkThroughput(WOLFSSL_CTX* ctx, char* host, word16 port, int doDTLS, int throughput) { double start, conn_time = 0, tx_time = 0, rx_time = 0; SOCKET_T sockfd; WOLFSSL* ssl; int ret; start = current_time(); ssl = wolfSSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL object"); tcp_connect(&sockfd, host, port, doDTLS, ssl); wolfSSL_set_fd(ssl, sockfd); if (wolfSSL_connect(ssl) == SSL_SUCCESS) { /* Perform throughput test */ char *tx_buffer, *rx_buffer; /* Record connection time */ conn_time = current_time() - start; /* Allocate TX/RX buffers */ tx_buffer = (char*)malloc(TEST_BUFFER_SIZE); rx_buffer = (char*)malloc(TEST_BUFFER_SIZE); if(tx_buffer && rx_buffer) { WC_RNG rng; /* Startup the RNG */ ret = wc_InitRng(&rng); if(ret == 0) { int xfer_bytes; /* Generate random data to send */ ret = wc_RNG_GenerateBlock(&rng, (byte*)tx_buffer, TEST_BUFFER_SIZE); wc_FreeRng(&rng); if(ret != 0) { err_sys("wc_RNG_GenerateBlock failed"); } /* Perform TX and RX of bytes */ xfer_bytes = 0; while(throughput > xfer_bytes) { int len, rx_pos, select_ret; /* Determine packet size */ len = min(TEST_BUFFER_SIZE, throughput - xfer_bytes); /* Perform TX */ start = current_time(); if (wolfSSL_write(ssl, tx_buffer, len) != len) { int writeErr = wolfSSL_get_error(ssl, 0); printf("wolfSSL_write error %d!\n", writeErr); err_sys("wolfSSL_write failed"); } tx_time += current_time() - start; /* Perform RX */ select_ret = tcp_select(sockfd, 1); /* Timeout=1 second */ if (select_ret == TEST_RECV_READY) { start = current_time(); rx_pos = 0; while(rx_pos < len) { ret = wolfSSL_read(ssl, &rx_buffer[rx_pos], len - rx_pos); if(ret <= 0) { int readErr = wolfSSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) { printf("wolfSSL_read error %d!\n", readErr); err_sys("wolfSSL_read failed"); } } else { rx_pos += ret; } } rx_time += current_time() - start; } /* Compare TX and RX buffers */ if(XMEMCMP(tx_buffer, rx_buffer, len) != 0) { err_sys("Compare TX and RX buffers failed"); } /* Update overall position */ xfer_bytes += len; } } else { err_sys("wc_InitRng failed"); } } else { err_sys("Client buffer malloc failed"); } if(tx_buffer) free(tx_buffer); if(rx_buffer) free(rx_buffer); } else { err_sys("wolfSSL_connect failed"); } wolfSSL_shutdown(ssl); wolfSSL_free(ssl); CloseSocket(sockfd); printf("wolfSSL Client Benchmark %d bytes\n" "\tConnect %8.3f ms\n" "\tTX %8.3f ms (%8.3f MBps)\n" "\tRX %8.3f ms (%8.3f MBps)\n", throughput, conn_time * 1000, tx_time * 1000, throughput / tx_time / 1024 / 1024, rx_time * 1000, throughput / rx_time / 1024 / 1024 ); return EXIT_SUCCESS; }