int MqttSocket_Disconnect(MqttClient *client) { int rc = MQTT_CODE_SUCCESS; if (client) { #ifdef ENABLE_MQTT_TLS if (client->tls.ssl) wolfSSL_free(client->tls.ssl); if (client->tls.ctx) wolfSSL_CTX_free(client->tls.ctx); wolfSSL_Cleanup(); client->flags &= ~MQTT_CLIENT_FLAG_IS_TLS; #endif /* Make sure socket is closed */ if (client->net && client->net->disconnect) { rc = client->net->disconnect(client->net->context); } client->flags &= ~MQTT_CLIENT_FLAG_IS_CONNECTED; } #ifdef WOLFMQTT_DEBUG_SOCKET printf("MqttSocket_Disconnect: Rc=%d\n", rc); #endif /* Check for error */ if (rc < 0) { rc = MQTT_CODE_ERROR_NETWORK; } return rc; }
int main(int argc, char** argv) { func_args args; #ifdef HAVE_CAVIUM int ret = OpenNitroxDevice(CAVIUM_DIRECT, CAVIUM_DEV_ID); if (ret != 0) err_sys("Cavium OpenNitroxDevice failed"); #endif /* HAVE_CAVIUM */ StartTCP(); args.argc = argc; args.argv = argv; wolfSSL_Init(); #if defined(DEBUG_WOLFSSL) && !defined(WOLFSSL_MDK_SHELL) && !defined(STACK_TRAP) wolfSSL_Debugging_ON(); #endif ChangeToWolfRoot(); #ifdef HAVE_STACK_SIZE StackSizeCheck(&args, client_test); #else client_test(&args); #endif wolfSSL_Cleanup(); #ifdef HAVE_CAVIUM CspShutdown(CAVIUM_DEV_ID); #endif return args.return_code; }
/* * ======== exitApp ======== * Cleans up the SSL context and exits the application */ void exitApp(WOLFSSL_CTX* ctx) { if (ctx != NULL) { wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); } BIOS_exit(-1); }
static int test_wolfSSL_Cleanup(void) { int result; printf(testingFmt, "wolfSSL_Cleanup()"); result = wolfSSL_Cleanup(); printf(resultFmt, result == SSL_SUCCESS ? passed : failed); return result; }
WolfSSLConnection::~WolfSSLConnection() { if (sslContext != NULL) { wolfSSL_CTX_free(sslContext); sslContext = NULL; } wolfSSL_Cleanup(); }
bool NET_PRES_EncProviderStreamClientDeinit0() { wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context); net_pres_wolfSSLInfoStreamClient0.isInited = false; _net_pres_wolfsslUsers--; if (_net_pres_wolfsslUsers == 0) { wolfSSL_Cleanup(); } return true; }
int SuiteTest(void) { func_args args; char argv0[2][80]; char* myArgv[2]; printf(" Begin Cipher Suite Tests\n"); /* setup */ myArgv[0] = argv0[0]; myArgv[1] = argv0[1]; args.argv = myArgv; strcpy(argv0[0], "SuiteTest"); (void)test_harness; cipherSuiteCtx = wolfSSL_CTX_new(wolfTLSv1_2_client_method()); if (cipherSuiteCtx == NULL) { printf("can't get cipher suite ctx\n"); exit(EXIT_FAILURE); } /* default case */ args.argc = 1; printf("starting default cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } /* any extra cases will need another argument */ args.argc = 2; #ifdef WOLFSSL_DTLS /* add dtls extra suites */ strcpy(argv0[1], "tests/test-dtls.conf"); printf("starting dtls extra cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } #endif printf(" End Cipher Suite Tests\n"); wolfSSL_CTX_free(cipherSuiteCtx); wolfSSL_Cleanup(); return args.return_code; }
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(); }
int main(int argc, char** argv) { func_args server_args; server_args.argc = argc; server_args.argv = argv; wolfSSL_Init(); ChangeToWolfRoot(); wolfcrypt_test(&server_args); if (server_args.return_code != 0) return server_args.return_code; wolfSSL_Cleanup(); printf("\nAll tests passed!\n"); EXIT_TEST(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; }
int main(int argc, char* argv[]) { if (argc < 2 || argc > 3) { printf("please specifiy ip address\n" "Use case ./client 127.0.0.1\n" "or with port ./client 127.0.0.1 1111\n"); return 1; } wolfSSL_Init(); if (argc < 3) { if (Client(argv[1], YASSLPORT) != 0) err_sys("error creating client"); } else { if (Client(argv[1], (word16)atoi(argv[2])) != 0) err_sys("error creating client"); } wolfSSL_Cleanup(); return 0; }
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; }
/* Main entry point for the program. * * argc The count of command line arguments. * argv The command line arguments. * returns 0 on success and 1 otherwise. */ int main(int argc, char* argv[]) { socklen_t socketfd = -1; int ch; WOLFSSL_CTX* ctx = NULL; SSLConn_CTX* sslConnCtx; word16 port = wolfSSLPort; int resumeSession = 0; char* cipherList = NULL; char* ourCert = CLI_CERT; char* ourKey = CLI_KEY; char* verifyCert = CA_CERT; int version = SERVER_DEFAULT_VERSION; int numConns = SSL_NUM_CONN; int numBytesRead = NUM_READ_BYTES; int numBytesWrite = NUM_WRITE_BYTES; int maxBytes = MAX_BYTES; int maxConns = MAX_CONNECTIONS; int i; /* Parse the command line arguments. */ while ((ch = mygetopt(argc, argv, OPTIONS)) != -1) { switch (ch) { /* Help with command line options. */ case '?': Usage(); exit(EXIT_SUCCESS); /* Port number to connect to. */ case 'p': port = (word16)atoi(myoptarg); break; /* Version of SSL/TLS to use. */ case 'v': version = atoi(myoptarg); if (version < 0 || version > 3) { Usage(); exit(MY_EX_USAGE); } break; /* List of cipher suites to use. */ case 'l': cipherList = myoptarg; break; /* File name of client certificate for client authentication. */ case 'c': ourCert = myoptarg; break; /* File name of client private key for client authentication. */ case 'k': ourKey = myoptarg; break; /* File name of server certificate/CA for peer verification. */ case 'A': verifyCert = myoptarg; break; /* Resume sessions. */ case 'r': resumeSession = 1; break; /* Number of connections to make. */ case 'n': maxConns = atoi(myoptarg); if (maxConns < 0 || maxConns > 1000000) { Usage(); exit(MY_EX_USAGE); } maxBytes = 0; break; /* Number of conncurrent connections to use. */ case 'N': numConns = atoi(myoptarg); if (numConns < 0 || numConns > 1000000) { Usage(); exit(MY_EX_USAGE); } break; /* Number of bytes to read each call. */ case 'R': numBytesRead = atoi(myoptarg); if (numBytesRead <= 0) { Usage(); exit(MY_EX_USAGE); } break; /* Number of bytes to write each call. */ case 'W': numBytesWrite = atoi(myoptarg); if (numBytesWrite <= 0) { Usage(); exit(MY_EX_USAGE); } break; /* Maximum number of read and write bytes (separate counts). */ case 'B': maxBytes = atoi(myoptarg); if (maxBytes <= 0) { Usage(); exit(MY_EX_USAGE); } maxConns = 0; break; /* Unrecognized command line argument. */ default: Usage(); exit(MY_EX_USAGE); } } #ifdef DEBUG_WOLFSSL wolfSSL_Debugging_ON(); #endif /* Initialize wolfSSL */ wolfSSL_Init(); /* Initialize wolfSSL and create a context object. */ if (WolfSSLCtx_Init(version, ourCert, ourKey, verifyCert, cipherList, &ctx) == EXIT_FAILURE) exit(EXIT_FAILURE); /* Create SSL/TLS connection data object. */ sslConnCtx = SSLConn_New(numConns, numBytesRead, numBytesWrite, maxConns, maxBytes, resumeSession); if (sslConnCtx == NULL) exit(EXIT_FAILURE); /* Keep handling connections until all done. */ for (i = 0; !SSLConn_Done(sslConnCtx); i = (i + 1) % numConns) { SSLConn* sslConn = &sslConnCtx->sslConn[i]; /* Perform close if in CLOSE state. */ if (sslConn->state == CLOSE) { if (sslConnCtx->numConnections == 0) { WOLFSSL_CIPHER* cipher; cipher = wolfSSL_get_current_cipher(sslConn->ssl); printf("SSL cipher suite is %s\n", wolfSSL_CIPHER_get_name(cipher)); } SSLConn_Close(sslConnCtx, sslConn); } /* Create TCP connection and connect if in INIT state. */ if ((sslConn->state == INIT) && ((sslConnCtx->maxConnections <= 0) || (sslConnCtx->numCreated < sslConnCtx->maxConnections))) { if (CreateSocketConnect(port, &socketfd) == EXIT_FAILURE) { printf("ERROR: failed to connect to server\n"); exit(EXIT_FAILURE); } SSLConn_Connect(sslConnCtx, ctx, socketfd, sslConn); } #ifdef WOLFSSL_ASYNC_CRYPT if (sslConn->err == 4) { int ret; double start; start = current_time(1); ret = wolfSSL_AsyncPoll(sslConn->ssl, WOLF_POLL_FLAG_CHECK_HW); sslConnCtx->asyncTime += current_time(0) - start; if (ret < 0) { printf("ERROR: failed in async polling\n"); break; } if (ret == 0) continue; } sslConn->err = 0; #endif /* Handle other SSL states. */ if (sslConnCtx->totalTime == 0) sslConnCtx->totalTime = current_time(1); if (SSLConn_ReadWrite(sslConnCtx, sslConn) == EXIT_FAILURE) { if (sslConnCtx->maxConnections > 0) sslConn->state = CLOSE; } } sslConnCtx->totalTime = current_time(0) - sslConnCtx->totalTime; SSLConn_PrintStats(sslConnCtx); SSLConn_Free(sslConnCtx); WolfSSLCtx_Final(ctx); wolfSSL_Cleanup(); exit(EXIT_SUCCESS); }
/* Main entry point for the program. * * argc The count of command line arguments. * argv The command line arguments. * returns 0 on success and 1 otherwise. */ int main(int argc, char* argv[]) { int i; int ch; /* Parse the command line arguments. */ while ((ch = mygetopt(argc, argv, OPTIONS)) != -1) { switch (ch) { /* Help with command line options. */ case '?': Usage(); exit(EXIT_SUCCESS); /* Port number to listen on. */ case 'p': port = (word16)atoi(myoptarg); break; /* Version of SSL/TLS to use. */ case 'v': version = atoi(myoptarg); if (version < 0 || version > 3) { Usage(); exit(MY_EX_USAGE); } break; /* List of cipher suites to use. */ case 'l': cipherList = myoptarg; break; /* File name of server certificate for authentication. */ case 'c': ourCert = myoptarg; break; /* File name of server private key for authentication. */ case 'k': ourKey = myoptarg; break; /* File name of client certificate/CA for peer verification. */ case 'A': verifyCert = myoptarg; break; /* Number of connections to make. */ case 't': numThreads = atoi(myoptarg); if (numThreads < 0 || numThreads > 100) { Usage(); exit(MY_EX_USAGE); } break; /* Number of connections to make. */ case 'n': maxConns = atoi(myoptarg); if (maxConns < 0 || maxConns > 1000000) { Usage(); exit(MY_EX_USAGE); } maxBytes = 0; break; /* Number of conncurrent connections to use. */ case 'N': numConns = atoi(myoptarg); if (numConns < 0 || numConns > 100000) { Usage(); exit(MY_EX_USAGE); } break; /* Number of bytes to read each call. */ case 'R': numBytesRead = atoi(myoptarg); if (numBytesRead <= 0) { Usage(); exit(MY_EX_USAGE); } break; /* Number of bytes to write each call. */ case 'W': numBytesWrite = atoi(myoptarg); if (numBytesWrite <= 0) { Usage(); exit(MY_EX_USAGE); } break; /* Maximum number of read and write bytes (separate counts). */ case 'B': maxBytes = atoi(myoptarg); if (maxBytes <= 0) { Usage(); exit(MY_EX_USAGE); } maxConns = 0; break; /* Unrecognized command line argument. */ default: Usage(); exit(MY_EX_USAGE); } } #ifdef DEBUG_WOLFSSL wolfSSL_Debugging_ON(); #endif /* Initialize wolfSSL */ wolfSSL_Init(); RandomReply(reply, sizeof(reply)); /* Create SSL/TLS connection data object. */ sslConnCtx = SSLConn_New(numThreads, numConns, numBytesRead, numBytesWrite, maxConns, maxBytes); if (sslConnCtx == NULL) exit(EXIT_FAILURE); for (i = 0; i < numThreads; i++) { if (pthread_create(&sslConnCtx->threadData[i].thread_id, NULL, ThreadHandler, &sslConnCtx->threadData[i]) < 0) { perror("ERRROR: could not create thread"); } } /* Start all the threads. */ for (i = 0; i < numThreads; i++) pthread_join(sslConnCtx->threadData[i].thread_id, NULL) ; sslConnCtx->totalTime = current_time(0) - sslConnCtx->totalTime; SSLConn_PrintStats(sslConnCtx); SSLConn_Free(sslConnCtx); wolfSSL_Cleanup(); exit(EXIT_SUCCESS); }
int SuiteTest(void) { func_args args; char argv0[2][80]; char* myArgv[2]; printf(" Begin Cipher Suite Tests\n"); /* setup */ myArgv[0] = argv0[0]; myArgv[1] = argv0[1]; args.argv = myArgv; strcpy(argv0[0], "SuiteTest"); #ifdef WOLFSSL_STATIC_MEMORY byte memory[200000]; #endif (void)test_harness; cipherSuiteCtx = wolfSSL_CTX_new(wolfTLSv1_2_client_method()); if (cipherSuiteCtx == NULL) { printf("can't get cipher suite ctx\n"); exit(EXIT_FAILURE); } /* load in static memory buffer if enabled */ #ifdef WOLFSSL_STATIC_MEMORY if (wolfSSL_CTX_load_static_memory(&cipherSuiteCtx, NULL, memory, sizeof(memory), 0, 1) != SSL_SUCCESS) { printf("unable to load static memory and create ctx"); exit(EXIT_FAILURE); } #endif /* default case */ args.argc = 1; printf("starting default cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } /* any extra cases will need another argument */ args.argc = 2; #ifdef WOLFSSL_DTLS /* add dtls extra suites */ strcpy(argv0[1], "tests/test-dtls.conf"); printf("starting dtls extra cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } #endif #ifdef WOLFSSL_SCTP /* add dtls-sctp extra suites */ strcpy(argv0[1], "tests/test-sctp.conf"); printf("starting dtls-sctp extra cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } #endif #ifndef WC_STRICT_SIG #if !defined(NO_RSA) && defined(HAVE_ECC) /* testing mixed ECC/RSA cert */ /* add extra signature test suites */ strcpy(argv0[1], "tests/test-sig.conf"); printf("starting sig extra cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } #endif /* HAVE_RSA and HAVE_ECC */ #endif /* !WC_STRICT_SIG */ #ifdef HAVE_QSH /* add QSH extra suites */ strcpy(argv0[1], "tests/test-qsh.conf"); printf("starting qsh extra cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } #endif #ifndef NO_PSK /* add psk extra suites */ strcpy(argv0[1], "tests/test-psk-no-id.conf"); printf("starting psk no identity extra cipher suite tests\n"); test_harness(&args); if (args.return_code != 0) { printf("error from script %d\n", args.return_code); exit(EXIT_FAILURE); } #endif printf(" End Cipher Suite Tests\n"); wolfSSL_CTX_free(cipherSuiteCtx); wolfSSL_Cleanup(); return args.return_code; }
/* Main entry point. */ int main(int argc, char* argv[]) { int ret = 0; WOLFSSL_CTX* client_ctx = NULL; WOLFSSL* client_ssl = NULL; WOLFSSL_CTX* server_ctx = NULL; WOLFSSL* server_ssl = NULL; #if defined(DEBUG_WOLFSSL) wolfSSL_Debugging_ON(); #endif /* Initialize wolfSSL library. */ wolfSSL_Init(); #ifdef WOLFSSL_STATIC_MEMORY if (wc_LoadStaticMemory(&HEAP_HINT_SERVER, gTestMemoryServer, sizeof(gTestMemoryServer), WOLFMEM_GENERAL | WOLFMEM_TRACK_STATS, 1) != 0) { printf("unable to load static memory"); ret = -1; } if (wc_LoadStaticMemory(&HEAP_HINT_CLIENT, gTestMemoryClient, sizeof(gTestMemoryClient), WOLFMEM_GENERAL | WOLFMEM_TRACK_STATS, 1) != 0) { printf("unable to load static memory"); ret = -1; } #endif /* Create server and client SSL objects. */ if (ret == 0) ret = wolfssl_server_new(&server_ctx, &server_ssl); if (ret == 0) ret = wolfssl_client_new(&client_ctx, &client_ssl); /* Loop to perform SSL handshake. */ while (ret == 0) { ret = wolfssl_client_connect(client_ssl); if (ret == 0) ret = wolfssl_server_accept(server_ssl); if (ret == 0 && wolfSSL_is_init_finished(client_ssl) && wolfSSL_is_init_finished(server_ssl)) { break; } } if (ret == 0) printf("Handshake complete\n"); /* Send and receive HTTP messages. */ if (ret == 0) { printf("\nClient Sending:\n"); ret = wolfssl_send(client_ssl, msgHTTPGet); } if (ret == 0) { printf("\nServer Received:\n"); ret = wolfssl_recv(server_ssl); } if (ret == 0) { printf("\nServer Sending:\n"); ret = wolfssl_send(server_ssl, msgHTTPIndex); } if (ret == 0) { printf("\nClient Received:\n"); ret = wolfssl_recv(client_ssl); } /* Display memory statistics. */ wolfssl_client_memstats(client_ssl); wolfssl_server_memstats(server_ssl); /* Dispose of SSL objects. */ wolfssl_free(client_ctx, client_ssl); wolfssl_free(server_ctx, server_ssl); /* Cleanup wolfSSL library. */ wolfSSL_Cleanup(); if (ret == 0) printf("Done\n"); else { char buffer[80]; printf("Error: %d, %s\n", ret, wolfSSL_ERR_error_string(ret, buffer)); } return (ret == 0) ? 0 : 1; }
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 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 */ }
int main (int argc, char** argv) { /* standard variables used in a dtls client */ int ret = 0, err; int sockfd = -1; WOLFSSL* ssl = NULL; WOLFSSL_CTX* ctx = NULL; const char* ca_cert = "../certs/ca-cert.pem"; char buff[MSGLEN]; int buffLen; SharedDtls shared; /* Program argument checking */ if (argc != 2) { printf("usage: udpcli <IP address>\n"); return 1; } /* 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); wolfSSL_Debugging_ON(); /* Initialize wolfSSL before assigning ctx */ wolfSSL_Init(); if ( (ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method())) == NULL) { fprintf(stderr, "wolfSSL_CTX_new error.\n"); goto exit; } /* Register callbacks */ wolfSSL_CTX_SetIORecv(ctx, my_IORecv); wolfSSL_CTX_SetIOSend(ctx, my_IOSend); /* Load CA certificates into ctx variable */ if (wolfSSL_CTX_load_verify_locations(ctx, ca_cert, 0) != SSL_SUCCESS) { fprintf(stderr, "Error loading %s, please check the file.\n", ca_cert); goto exit; } /* Assign ssl variable */ ssl = wolfSSL_new(ctx); if (ssl == NULL) { printf("unable to get ssl object"); goto exit; } memset(&shared, 0, sizeof(shared)); shared.ssl = ssl; /* servAddr setup */ shared.servSz = sizeof(shared.servAddr); shared.servAddr.sin_family = AF_INET; shared.servAddr.sin_port = htons(SERV_PORT); if (inet_pton(AF_INET, argv[1], &shared.servAddr.sin_addr) < 1) { printf("Error and/or invalid IP address"); goto exit; } if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { printf("cannot create a socket."); goto exit; } shared.sd = sockfd; wolfSSL_SetIOWriteCtx(ssl, &shared); wolfSSL_SetIOReadCtx(ssl, &shared); if (wolfSSL_connect(ssl) != SSL_SUCCESS) { err = wolfSSL_get_error(ssl, 0); printf("err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); printf("SSL_connect failed\n"); goto exit; } /**************************************************************************/ /* Code for sending datagram to server */ if (fgets(buff, sizeof(buff), stdin) != NULL) { /* Send buffer to the server */ buffLen = strlen(buff); if (( wolfSSL_write(ssl, buff, buffLen)) != buffLen) { err = wolfSSL_get_error(ssl, 0); if (err != SSL_ERROR_WANT_WRITE) { printf("err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); printf("SSL_write failed\n"); goto exit; } } /* Receive message from server */ ret = wolfSSL_read(ssl, buff, sizeof(buff)-1); if (ret < 0) { err = wolfSSL_get_error(ssl, 0); if (err != SSL_ERROR_WANT_READ) { printf("err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); printf("SSL_read failed\n"); goto exit; } } buffLen = ret; ret = 0; /* Add a terminating character to the generic server message */ buff[buffLen] = '\0'; fputs(buff, stdout); } /* End code for sending datagram to server */ /**************************************************************************/ exit: /* Housekeeping */ if (ssl) { wolfSSL_shutdown(ssl); wolfSSL_free(ssl); } if (sockfd != -1) { close(sockfd); } if (ctx) { wolfSSL_CTX_free(ctx); } wolfSSL_Cleanup(); return ret; }
int main() { /* * Creates a socket that uses an internet IP address, * Sets the type to be Stream based (TCP), * 0 means choose the default protocol. */ socklen_t sockfd = socket(AF_INET, SOCK_STREAM, 0); int ret = 0; /* Return Variable */ int loopExit = 0; /* 0 = False, 1 = True */ /* Server and Client socket address structures */ struct sockaddr_in serverAddr = {0}, clientAddr = {0}; /* Initialize the server address struct to zero */ memset((char *)&serverAddr, 0, sizeof(serverAddr)); /* Fill the server's address family */ serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_port = htons(DEFAULT_PORT); /* initialize wolfSSL */ wolfSSL_Init(); /* If positive value, the socket is valid */ if (sockfd == -1) { printf("ERROR: failed to create the socket\n"); return EXIT_FAILURE; } /* Create and initialize WOLFSSL_CTX structure */ if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method())) == NULL) { fprintf(stderr, "wolfSSL_CTX_new error.\n"); return EXIT_FAILURE; } /* Load server certificate into WOLFSSL_CTX */ if (wolfSSL_CTX_use_certificate_file(ctx, "../certs/server-cert.pem", SSL_FILETYPE_PEM) != SSL_SUCCESS) { fprintf(stderr, "Error loading certs/server-cert.pem, please check" "the file.\n"); return EXIT_FAILURE; } /* Load server key into WOLFSSL_CTX */ if (wolfSSL_CTX_use_PrivateKey_file(ctx, "../certs/server-key.pem", SSL_FILETYPE_PEM) != SSL_SUCCESS) { fprintf(stderr, "Error loading certs/server-key.pem, please check" "the file.\n"); return EXIT_FAILURE; } /* Attach the server socket to our port */ if (bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) { printf("ERROR: failed to bind\n"); return EXIT_FAILURE; } printf("Waiting for a connection...\n"); /* Continuously accept connects while not currently in an active connection or told to quit */ while (loopExit == 0) { /* Listen for a new connection, allow 5 pending connections */ ret = listen(sockfd, 5); if (ret == 0) { /* Accept client connections and read from them */ loopExit = AcceptAndRead(sockfd, clientAddr); } } wolfSSL_CTX_free(ctx); /* Free WOLFSSL_CTX */ wolfSSL_Cleanup(); /* Free wolfSSL */ return EXIT_SUCCESS; }
int testsuite_test(int argc, char** argv) { func_args server_args; tcp_ready ready; THREAD_TYPE serverThread; #ifndef USE_WINDOWS_API char tempName[] = "/tmp/output-XXXXXX"; int len = 18; int num = 6; #else char tempName[] = "fnXXXXXX"; int len = 8; int num = 6; #endif #ifdef HAVE_CAVIUM int ret = OpenNitroxDevice(CAVIUM_DIRECT, CAVIUM_DEV_ID); if (ret != 0) err_sys("Cavium OpenNitroxDevice failed"); #endif /* HAVE_CAVIUM */ #ifdef HAVE_WNR if (wc_InitNetRandom(wnrConfig, NULL, 5000) != 0) { err_sys("Whitewood netRandom global config failed"); return -1237; } #endif /* HAVE_WNR */ StartTCP(); server_args.argc = argc; server_args.argv = argv; wolfSSL_Init(); #if defined(DEBUG_WOLFSSL) && !defined(HAVE_VALGRIND) wolfSSL_Debugging_ON(); #endif #if !defined(WOLFSSL_TIRTOS) ChangeToWolfRoot(); #endif #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif server_args.signal = &ready; InitTcpReady(&ready); #ifndef NO_CRYPT_TEST /* wc_ test */ wolfcrypt_test(&server_args); if (server_args.return_code != 0) return server_args.return_code; #endif /* Simple wolfSSL client server test */ simple_test(&server_args); if (server_args.return_code != 0) return server_args.return_code; /* Echo input wolfSSL client server test */ start_thread(echoserver_test, &server_args, &serverThread); wait_tcp_ready(&server_args); { func_args echo_args; char* myArgv[NUMARGS]; char argc0[32]; char argc1[32]; char argc2[32]; myArgv[0] = argc0; myArgv[1] = argc1; myArgv[2] = argc2; echo_args.argc = 3; echo_args.argv = myArgv; /* Create unique file name */ outputName = mymktemp(tempName, len, num); if (outputName == NULL) { printf("Could not create unique file name"); return EXIT_FAILURE; } strcpy(echo_args.argv[0], "echoclient"); strcpy(echo_args.argv[1], "input"); strcpy(echo_args.argv[2], outputName); /* Share the signal, it has the new port number in it. */ echo_args.signal = server_args.signal; /* make sure OK */ echoclient_test(&echo_args); if (echo_args.return_code != 0) return echo_args.return_code; #ifdef WOLFSSL_DTLS wait_tcp_ready(&server_args); #endif /* send quit to echoserver */ echo_args.argc = 2; strcpy(echo_args.argv[1], "quit"); echoclient_test(&echo_args); if (echo_args.return_code != 0) return echo_args.return_code; join_thread(serverThread); if (server_args.return_code != 0) return server_args.return_code; } /* show ciphers */ { char ciphers[1024]; XMEMSET(ciphers, 0, sizeof(ciphers)); wolfSSL_get_ciphers(ciphers, sizeof(ciphers)-1); printf("ciphers = %s\n", ciphers); } /* validate output equals input */ { byte input[SHA256_DIGEST_SIZE]; byte output[SHA256_DIGEST_SIZE]; file_test("input", input); file_test(outputName, output); remove(outputName); if (memcmp(input, output, sizeof(input)) != 0) return EXIT_FAILURE; } wolfSSL_Cleanup(); FreeTcpReady(&ready); #ifdef WOLFSSL_TIRTOS fdCloseSession(Task_self()); #endif #ifdef HAVE_CAVIUM CspShutdown(CAVIUM_DEV_ID); #endif #ifdef HAVE_WNR if (wc_FreeNetRandom() < 0) err_sys("Failed to free netRandom context"); #endif /* HAVE_WNR */ printf("\nAll tests passed!\n"); return EXIT_SUCCESS; }
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 listenfd, connfd; int opt; struct sockaddr_in cliAddr, servAddr; char buff[MAXLINE]; socklen_t cliLen; pthread_t thread; void* wolfssl_thread(void*); wolfSSL_Init(); if ((ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())) == NULL) printf("Fatal error : wolfSSL_CTX_new error\n"); /* 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"); /* find a socket */ listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { printf("Fatal error : socket error"); } /* 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))) { return 1; } if (bind(listenfd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { printf("Fatal error : bind error"); return 1; } /* main loop for accepting and responding to clients */ for ( ; ; ) { /* listen to the socket */ if (listen(listenfd, LISTENQ) < 0) { printf("Fatal error : listen error"); return 1; } cliLen = sizeof(cliAddr); connfd = accept(listenfd, (struct sockaddr *) &cliAddr, &cliLen); if (connfd < 0) { printf("Fatal error : accept error"); return 1; } else { printf("Connection from %s, port %d\n", inet_ntop(AF_INET, &cliAddr.sin_addr, buff, sizeof(buff)), ntohs(cliAddr.sin_port)); if (pthread_create(&thread, NULL, &wolfssl_thread, (void*) &connfd) != 0) { return 1; } if (pthread_detach(thread) != 0) { return 1; } } } /* free up memory used by wolfssl */ 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; }
int main(int argc, char **argv) { struct sockaddr_in srvaddr, cliaddr; socklen_t socketfd,clisocketfd; socklen_t clilen; WOLFSSL_CTX *wsslctx; WOLFSSL *sslconn; int portnum; const char *certpath; const char *privpath; std::string cliipaddr; std::string data; std::string dbpath; pid_t pid; clilen = sizeof(cliaddr); wolfSSL_Init(); if (argc == 4) { if (prompt_y_n("Create new user database?", "")) { do { std::cout << "Please specify a filename for the new database: "; std::getline(std::cin, dbpath); if (!access(dbpath.c_str(), F_OK)) { if (prompt_y_n("File already exists, overwrite?", "")) { break; } } else { break; } } while (true); std::string jsondat = "{ \"users\" : { } }"; std::ofstream outputfile; outputfile.open(dbpath); if (outputfile.is_open()) { outputfile << jsondat; outputfile.close(); std::cout << "Created new database file!" << std::endl; } else { std::cout << "Failed to create new database file!" << std::endl; } } else { std::cout << "Ok, please specify an existing user database" << std::endl; std::cout<<"Usage: "<<argv[0]<<" <port #> <certfile> <privkey> [userdb]"<<std::endl; return -1; } } else if (argc < 5) { std::cout<<"Usage: "<<argv[0]<<" <port #> <certfile> <privkey> [userdb]"<<std::endl; std::cout<<"If [userdb] is unspecified, we will create a new one"<<std::endl; return 1; } portnum = atoi(argv[1]); certpath = argv[2]; privpath = argv[3]; if (argc == 5) dbpath = std::string(argv[4]); if (portnum < 1 || portnum > 65535) { std::cout<<"Please choose a port in the range: 1-65535"<<std::endl; return 1; } /*userdb_file.open(dbpath); if (!userdb_file.is_open()) { std::cout<<"[-] Could not open user database"<<std::endl; return 1; }*/ if ( (socketfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) { std::cout<<"Failed to initialize socket"<<std::endl; return -1; } memset((void*)&srvaddr,0,sizeof(srvaddr)); srvaddr.sin_family = AF_INET; srvaddr.sin_addr.s_addr = INADDR_ANY; srvaddr.sin_port = htons(portnum); if ( (wsslctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method())) == NULL ) { std::cout<<"Failed to create new WolfSSL CTX"<<std::endl; return -1; } if (wolfSSL_CTX_use_PrivateKey_file(wsslctx,privpath,SSL_FILETYPE_PEM) != SSL_SUCCESS) { std::cout<<"Failed to load SSL private key file"<<std::endl; return -2; } if (wolfSSL_CTX_use_certificate_file(wsslctx,certpath,SSL_FILETYPE_PEM) != SSL_SUCCESS) { std::cout<<"Failed to load SSL certificate file"<<std::endl; return -2; } if (bind(socketfd, (struct sockaddr *)&srvaddr, sizeof(srvaddr)) != 0) { std::cout<<"Failed to bind to port "<<portnum<<std::endl; return -3; } listen(socketfd,10); std::cout<<"[+] KeyLocker server started. Waiting for connections..."<<std::endl; while(1) { if ( (clisocketfd = accept(socketfd,(struct sockaddr *)&cliaddr,&clilen)) == -1 ) { std::cout<<"Failed to accept connection on socket"<<std::endl; //return -3; } if ( (pid=fork()) < 0 ) { std::cout<<"Fork failed"<<std::endl; return -4; } else if (pid > 0) { /* parent */ close(clisocketfd); waitpid(pid, 0, 0); continue; } else { /* child */ close(socketfd); //15 second timeout signal(SIGALRM,sighandler); alarm(15); cliipaddr = std::string(inet_ntoa(cliaddr.sin_addr)); std::cout<<"[+] Client connected from IP address: "<<cliipaddr <<std::endl; sslconn = start_ssl(wsslctx,clisocketfd,cliaddr); data = get_cli_data(sslconn); //shut alarm off alarm(0); process_data(data,dbpath,sslconn); close(clisocketfd); break; } usleep(1000); } //close(clisocketfd); wolfSSL_free(sslconn); wolfSSL_CTX_free(wsslctx); wolfSSL_Cleanup(); return 0; }
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 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; }
int main(int argc, char** argv) { int ret; WC_RNG rng; ecEncCtx* srvCtx = NULL; void* devCtx = NULL; const byte* mySalt; byte peerSalt[EXCHANGE_SALT_SZ]; byte buffer[BTLE_MSG_MAX_SIZE]; word32 bufferSz; byte plain[BTLE_MSG_MAX_SIZE]; word32 plainSz; ecc_key myKey, peerKey; int type; wolfSSL_Init(); #ifdef DEBUG_WOLFSSL wolfSSL_Debugging_ON(); #endif /* make my session key */ ret = wc_ecc_init(&myKey); ret |= wc_ecc_init(&peerKey); if (ret != 0) { printf("wc_ecc_init failed!\n"); goto cleanup; } /* open BTLE */ ret = btle_open(&devCtx, BTLE_ROLE_SERVER); if (ret != 0) { printf("btle_open failed %d! errno %d\n", ret, errno); goto cleanup; } ret = wc_InitRng(&rng); if (ret != 0) { printf("wc_InitRng failed! %d\n", ret); goto cleanup; } ret = wc_ecc_make_key(&rng, 32, &myKey); if (ret != 0) { printf("wc_ecc_make_key failed %d\n", ret); goto cleanup; } srvCtx = wc_ecc_ctx_new(REQ_RESP_SERVER, &rng); if (srvCtx == NULL) { printf("wc_ecc_ctx_new failed!\n"); ret = -1; goto cleanup; } /* exchange public keys */ /* Get peer key */ ret = btle_recv(buffer, sizeof(buffer), &type, devCtx); if (ret < 0) { printf("btle_recv key failed %d! errno %d\n", ret, errno); goto cleanup; } if (type != BTLE_PKT_TYPE_KEY) { printf("btle_recv expected key!\n"); ret = -1; goto cleanup; } bufferSz = ret; ret = wc_ecc_import_x963(buffer, bufferSz, &peerKey); if (ret != 0) { printf("wc_ecc_import_x963 failed %d!\n", ret); goto cleanup; } /* send my public key */ /* export my public key */ bufferSz = sizeof(buffer); ret = wc_ecc_export_x963(&myKey, buffer, &bufferSz); if (ret != 0) { printf("wc_ecc_export_x963 failed %d\n", ret); goto cleanup; } /* TODO: Server should hash and sign this public key with a trust ceritifcate (already exchanged) */ /* ECC signature is about 65 bytes */ ret = btle_send(buffer, bufferSz, BTLE_PKT_TYPE_KEY, devCtx); if (ret != bufferSz) { printf("btle_send key failed %d!\n", ret); goto cleanup; } while (1) { mySalt = wc_ecc_ctx_get_own_salt(srvCtx); if (mySalt == NULL) { printf("wc_ecc_ctx_get_own_salt failed!\n"); ret = -1; goto cleanup; } /* Get peer salt */ ret = btle_recv(peerSalt, EXCHANGE_SALT_SZ, &type, devCtx); if (ret <= 0) { printf("btle_recv salt failed %d! errno %d\n", ret, errno); goto cleanup; } if (type != BTLE_PKT_TYPE_SALT) { printf("btle_recv expected salt!\n"); ret = -1; goto cleanup; } /* Send my salt */ /* You must send mySalt before set_peer_salt, because buffer changes */ ret = btle_send(mySalt, EXCHANGE_SALT_SZ, BTLE_PKT_TYPE_SALT, devCtx); if (ret != EXCHANGE_SALT_SZ) { printf("btle_send salt failed %d!\n", ret); goto cleanup; } ret = wc_ecc_ctx_set_peer_salt(srvCtx, peerSalt); if (ret != 0) { printf("wc_ecc_ctx_set_peer_salt failed %d\n", ret); goto cleanup; } /* Get message */ bufferSz = sizeof(buffer); ret = btle_recv(buffer, bufferSz, &type, devCtx); if (ret <= 0) { printf("btle_recv msg failed %d! errno %d\n", ret, errno); goto cleanup; } if (type != BTLE_PKT_TYPE_MSG) { printf("btle_recv expected msg!\n"); ret = -1; goto cleanup; } /* Decrypt message */ bufferSz = ret; plainSz = sizeof(plain); ret = wc_ecc_decrypt(&myKey, &peerKey, buffer, bufferSz, plain, &plainSz, srvCtx); if (ret != 0) { printf("wc_ecc_decrypt failed %d!\n", ret); goto cleanup; } printf("Recv %d: %s\n", plainSz, plain); /* Encrypt message */ bufferSz = sizeof(buffer); ret = wc_ecc_encrypt(&myKey, &peerKey, plain, plainSz, buffer, &bufferSz, srvCtx); if (ret != 0) { printf("wc_ecc_encrypt failed %d!\n", ret); goto cleanup; } /* Send message */ ret = btle_send(buffer, bufferSz, BTLE_PKT_TYPE_MSG, devCtx); if (ret != bufferSz) { printf("btle_send failed %d!\n", ret); goto cleanup; } /* check for exit flag */ if (strstr((char*)plain, "EXIT")) break; /* reset context (reset my salt) */ ret = wc_ecc_ctx_reset(srvCtx, &rng); if (ret != 0) { printf("wc_ecc_ctx_reset failed %d\n", ret); goto cleanup; } } cleanup: if (devCtx != NULL) btle_close(devCtx); wolfSSL_Cleanup(); return ret; }