Exemplo n.º 1
0
    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;
    }
Exemplo n.º 2
0
bool NET_PRES_EncProviderStreamClientInit0(NET_PRES_TransportObject * transObject)
{
    const uint8_t * caCertsPtr;
    int32_t caCertsLen;
    if (!NET_PRES_CertStoreGetCACerts(&caCertsPtr, &caCertsLen, 0))
    {
        return false;
    }
    if (_net_pres_wolfsslUsers == 0)
    {
        wolfSSL_Init();
        _net_pres_wolfsslUsers++;
    }
    net_pres_wolfSSLInfoStreamClient0.transObject = transObject;
    net_pres_wolfSSLInfoStreamClient0.context = wolfSSL_CTX_new(wolfSSLv23_client_method());
    if (net_pres_wolfSSLInfoStreamClient0.context == 0)
    {
        return false;
    }
    wolfSSL_SetIORecv(net_pres_wolfSSLInfoStreamClient0.context, (CallbackIORecv)&NET_PRES_EncGlue_StreamClientReceiveCb0);
    wolfSSL_SetIOSend(net_pres_wolfSSLInfoStreamClient0.context, (CallbackIOSend)&NET_PRES_EncGlue_StreamClientSendCb0);
    if (wolfSSL_CTX_load_verify_buffer(net_pres_wolfSSLInfoStreamClient0.context, caCertsPtr, caCertsLen, SSL_FILETYPE_ASN1) != SSL_SUCCESS)
    {
        // Couldn't load the certificates
        //SYS_CONSOLE_MESSAGE("Something went wrong loading the certificates\r\n");
        wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context);
        return false;
    }
    // Turn off verification, because SNTP is usually blocked by a firewall
    wolfSSL_CTX_set_verify(net_pres_wolfSSLInfoStreamClient0.context, SSL_VERIFY_NONE, 0);
    net_pres_wolfSSLInfoStreamClient0.isInited = true;
    return true;
}
Exemplo n.º 3
0
static void prvInitialiseWolfSSL( void )
{
int32_t iReturn;

	#ifdef DEBUG_WOLFSSL
	{
		wolfSSL_Debugging_ON();
	}
	#endif

    /* Initialise wolfSSL.  This must be done before any other wolfSSL functions
    are called. */
    wolfSSL_Init();

    /* Attempt to create a context that uses the TLS 1.2 server protocol. */
    xWolfSSL_ServerContext = wolfSSL_CTX_new( wolfTLSv1_2_server_method() );

    if( xWolfSSL_ServerContext != NULL )
    {
        /* Load the CA certificate.  Real applications should ensure that
        wolfSSL_CTX_load_verify_locations() returns SSL_SUCCESS before
		proceeding. */
        iReturn = wolfSSL_CTX_load_verify_locations( xWolfSSL_ServerContext, "ca-cert.pem", 0 );
		configASSERT( iReturn == SSL_SUCCESS );

		iReturn = wolfSSL_CTX_use_certificate_file( xWolfSSL_ServerContext, "server-cert.pem", SSL_FILETYPE_PEM );
		configASSERT( iReturn == SSL_SUCCESS );

		iReturn = wolfSSL_CTX_use_PrivateKey_file( xWolfSSL_ServerContext, "server-key.pem", SSL_FILETYPE_PEM );
		configASSERT( iReturn == SSL_SUCCESS );
    }
}
Exemplo n.º 4
0
static int test_wolfSSL_Init(void)
{
    int result;

    printf(testingFmt, "wolfSSL_Init()");
    result = wolfSSL_Init();
    printf(resultFmt, result == SSL_SUCCESS ? passed : failed);

    return result;
}
Exemplo n.º 5
0
void *mod_wolftls_create(http_server_t *server, char *unused, mod_tls_t *modconfig)
{
	int ret;
	_mod_wolftls_t *mod;

	if (!modconfig)
		return NULL;

	mod = calloc(1, sizeof(*mod));

	wolfSSL_Init();
	mod->method = wolfTLSv1_2_server_method();

	if ( (mod->ctx = wolfSSL_CTX_new(mod->method)) == NULL)
		goto wolfftls_out_ctx;

	if (modconfig->crtfile)
	{
		ret = wolfSSL_CTX_use_certificate_file(mod->ctx, modconfig->crtfile, SSL_FILETYPE_PEM);
		if (ret != WOLFSSL_SUCCESS)
		{
			err("wolftls: CTX_use_certificate_file %d %d\n", ret, WOLFSSL_SUCCESS);
			goto wolfftls_out_certfile;
		}
	}

	if (modconfig->pemfile)
	{
		ret =  wolfSSL_CTX_use_PrivateKey_file(mod->ctx, modconfig->pemfile, SSL_FILETYPE_PEM);
		if (ret != WOLFSSL_SUCCESS)
		{
			err("wolftls: CTX_use_PrivateKey_file pem %d\n", ret);
			goto wolfftls_out_certfile;
		}
	}
	if (modconfig->cachain)
	{
		ret = wolfSSL_CTX_use_certificate_chain_file(mod->ctx, modconfig->cachain);
		if (ret != WOLFSSL_SUCCESS)
		{
			err("wolftls: CTX_use_certificate_chain_file cachain %d\n", ret);
			goto wolfftls_out_certfile;
		}
	}

	httpserver_addmod(server, _mod_wolftls_getctx, _mod_wolftls_freectx, mod, str_wolftls);

	return mod;
wolfftls_out_certfile:
	wolfSSL_CTX_free(mod->ctx);
wolfftls_out_ctx:
	free(mod);
	return NULL;
}
bool NET_PRES_EncProviderStreamClientInit0(NET_PRES_TransportObject * transObject)
{
    const uint8_t * caCertsPtr;
    int32_t caCertsLen;
    if (!NET_PRES_CertStoreGetCACerts(&caCertsPtr, &caCertsLen, 0))
    {
        return false;
    }
    if (_net_pres_wolfsslUsers == 0)
    {
        wolfSSL_Init();
        _net_pres_wolfsslUsers++;
    }
    net_pres_wolfSSLInfoStreamClient0.transObject = transObject;
    net_pres_wolfSSLInfoStreamClient0.context = wolfSSL_CTX_new(wolfSSLv23_client_method());
    if (net_pres_wolfSSLInfoStreamClient0.context == 0)
    {
        return false;
    }
    wolfSSL_SetIORecv(net_pres_wolfSSLInfoStreamClient0.context, (CallbackIORecv)&NET_PRES_EncGlue_StreamClientReceiveCb0);
    wolfSSL_SetIOSend(net_pres_wolfSSLInfoStreamClient0.context, (CallbackIOSend)&NET_PRES_EncGlue_StreamClientSendCb0);
    
    // Turn off verification, because SNTP is usually blocked by a firewall
    wolfSSL_CTX_set_verify(net_pres_wolfSSLInfoStreamClient0.context, SSL_VERIFY_NONE, 0);
    
    if (wolfSSL_CTX_load_verify_buffer(net_pres_wolfSSLInfoStreamClient0.context, caCertsPtr, caCertsLen, SSL_FILETYPE_ASN1) != SSL_SUCCESS)
    {
        // Couldn't load the certificates
        wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context);
        return false;
    }
    
    if(wolfSSL_CTX_use_PrivateKey_buffer(net_pres_wolfSSLInfoStreamClient0.context, (unsigned char *)appData.clientKey, strlen((char *)appData.clientKey), SSL_FILETYPE_PEM) != SSL_SUCCESS)
    {
        // Couldn't load the private key
        wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context);
        return false;
    }
    
    // Loading the client cert so that the server can authenticate us (client authentication))
    if(wolfSSL_CTX_use_certificate_buffer(net_pres_wolfSSLInfoStreamClient0.context, (unsigned char *)appData.clientCert, strlen((char *)appData.clientCert), SSL_FILETYPE_PEM) != SSL_SUCCESS)
    {
        // Couldn't load the client certificate
        wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context);
        return false;
    }
    
    // Turn off verification, because SNTP is usually blocked by a firewall
    wolfSSL_CTX_set_verify(net_pres_wolfSSLInfoStreamClient0.context, SSL_VERIFY_NONE, 0);
    net_pres_wolfSSLInfoStreamClient0.isInited = true;
    return true;
}
Exemplo n.º 7
0
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();
}
Exemplo n.º 8
0
WolfSSLConnection::WolfSSLConnection()
{
    wolfSSL_Init();

    WOLFSSL_METHOD* method = wolfTLSv1_2_client_method();
    if(method != NULL)
    {
        sslContext = wolfSSL_CTX_new(method);
    }
	else
	{
		sslContext = NULL;
	}
    
    isConnected = false;
}
Exemplo n.º 9
0
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);
}
Exemplo n.º 10
0
/*
 * 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;
}
Exemplo n.º 11
0
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){
    
    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;
}
Exemplo n.º 13
0
/* 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                 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;
}
Exemplo n.º 15
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);
}
Exemplo n.º 16
0
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;
}
Exemplo n.º 17
0
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;
}
Exemplo n.º 18
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;
}
Exemplo n.º 19
0
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;
}
/* 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);
}
Exemplo n.º 21
0
/*
 *  ======== 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);
	}
}
Exemplo n.º 22
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               */
}
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;
}
Exemplo n.º 24
0
bool NET_PRES_EncProviderStreamClientInit0(NET_PRES_TransportObject * transObject)
{
    const uint8_t * caCertsPtr;
    const uint8_t * clientCertPtr;
    const uint8_t * clientKeyPtr;
    int32_t caCertsLen;
    int32_t clientCertLen;
    int32_t clientKeyLen;
    
    
    if (!NET_PRES_CertStoreGetCACerts(&caCertsPtr, &caCertsLen, 0))
    {
        return false;
    }
    if (!NET_PRES_CertStoreGetClientCerts(&clientCertPtr, &clientCertLen, 0))
    {
        return false;
    }
    if (!NET_PRES_CertStoreGetClientKey(&clientKeyPtr, &clientKeyLen, 0))
    {
        return false;
    }
    if (_net_pres_wolfsslUsers == 0)
    {
        wolfSSL_Init();
        _net_pres_wolfsslUsers++;
    }
    net_pres_wolfSSLInfoStreamClient0.transObject = transObject;
    net_pres_wolfSSLInfoStreamClient0.context = wolfSSL_CTX_new(wolfSSLv23_client_method());
    if (net_pres_wolfSSLInfoStreamClient0.context == 0)
    {
        return false;
    }
    wolfSSL_SetIORecv(net_pres_wolfSSLInfoStreamClient0.context, (CallbackIORecv)&NET_PRES_EncGlue_StreamClientReceiveCb0);
    wolfSSL_SetIOSend(net_pres_wolfSSLInfoStreamClient0.context, (CallbackIOSend)&NET_PRES_EncGlue_StreamClientSendCb0);
    
    // Loading the rootCA cert so we can authenticate the server certificate given to us
    if (wolfSSL_CTX_load_verify_buffer(net_pres_wolfSSLInfoStreamClient0.context, caCertsPtr, caCertsLen, SSL_FILETYPE_ASN1) != SSL_SUCCESS)
    {
        // Couldn't load the certificates
        //SYS_CONSOLE_MESSAGE("Something went wrong loading the certificates\r\n");
        wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context);
        return false;
    }
     
    // Loading the private key for client authentication use
    if(wolfSSL_CTX_use_PrivateKey_buffer(net_pres_wolfSSLInfoStreamClient0.context, clientKeyPtr, clientKeyLen, SSL_FILETYPE_ASN1) != SSL_SUCCESS)
    {
        // Couldn't load the private key
        //SYS_CONSOLE_MESSAGE("Something went wrong loading the private key\r\n");
        wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context);
        return false;
    }
    
    // Loading the client cert so that the server can authenticate us (client authentication))
    if(wolfSSL_CTX_use_certificate_buffer(net_pres_wolfSSLInfoStreamClient0.context, clientCertPtr, clientCertLen, SSL_FILETYPE_ASN1) != SSL_SUCCESS)
    {
        // Couldn't load the client certificate
        //SYS_CONSOLE_MESSAGE("Something went wrong loading the client certificate\r\n");
        wolfSSL_CTX_free(net_pres_wolfSSLInfoStreamClient0.context);
        return false;
    }
    
    // Turn on verification, ensure SNTP is not blocked by firewall
    // SSL_VERIFY_PEER:  This option is turned on by default so technically this
    // is not needed
    wolfSSL_CTX_set_verify(net_pres_wolfSSLInfoStreamClient0.context, SSL_VERIFY_NONE, 0);
    net_pres_wolfSSLInfoStreamClient0.isInited = true;
    return true;
}
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;
}
Exemplo n.º 26
0
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 MqttSocket_Connect(MqttClient *client, const char* host, word16 port,
    int timeout_ms, int use_tls, MqttTlsCb cb)
{
    int rc;

    /* Validate arguments */
    if (client == NULL || client->net == NULL ||
        client->net->connect == NULL) {
        return MQTT_CODE_ERROR_BAD_ARG;
    }

    /* Validate port */
    if (port == 0) {
        port = (use_tls) ? MQTT_SECURE_PORT : MQTT_DEFAULT_PORT;
    }

    /* Connect to host */
    rc = client->net->connect(client->net->context, host, port, timeout_ms);
    if (rc != 0) {
        return rc;
    }
    client->flags |= MQTT_CLIENT_FLAG_IS_CONNECTED;

#ifdef ENABLE_MQTT_TLS
    if (use_tls) {
        /* Setup the WolfSSL library */
        wolfSSL_Init();
        
        /* Issue callback to allow setup of the wolfSSL_CTX and cert 
           verification settings */
        rc = SSL_SUCCESS;
        if (cb) {
            rc = cb(client);
        }
        if (rc == SSL_SUCCESS) {
            /* Create and initialize the WOLFSSL_CTX structure */
            if (client->tls.ctx == NULL) {
                /* Use defaults */
                client->tls.ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
                if (client->tls.ctx) {
                    wolfSSL_CTX_set_verify(client->tls.ctx, SSL_VERIFY_NONE, 0);
                }
            }
            if (client->tls.ctx) {
                /* Seutp the async IO callbacks */
                wolfSSL_SetIORecv(client->tls.ctx,
                    MqttSocket_TlsSocketReceive);
                wolfSSL_SetIOSend(client->tls.ctx,
                    MqttSocket_TlsSocketSend);

                client->tls.ssl = wolfSSL_new(client->tls.ctx);
                if (client->tls.ssl) {
                    wolfSSL_SetIOReadCtx(client->tls.ssl, (void *)client);
                    wolfSSL_SetIOWriteCtx(client->tls.ssl, (void *)client);

                    rc = wolfSSL_connect(client->tls.ssl);
                    if (rc == SSL_SUCCESS) {
                        client->flags |= MQTT_CLIENT_FLAG_IS_TLS;
                        rc = MQTT_CODE_SUCCESS;
                    }
                }
                else {
#ifndef WOLFMQTT_NO_STDIO
                    printf("MqttSocket_TlsConnect: wolfSSL_new error!\n");
#endif
                    rc = -1;
                }
            }
            else {
#ifndef WOLFMQTT_NO_STDIO
                printf("MqttSocket_TlsConnect: wolfSSL_CTX_new error!\n");
#endif
                rc = -1;
            }
        }
        else {
#ifndef WOLFMQTT_NO_STDIO
            printf("MqttSocket_TlsConnect: TLS callback error!\n");
#endif
            rc = -1;
        }

        /* Handle error case */
        if (rc) {
#ifndef WOLFMQTT_NO_STDIO
        	const char* errstr = NULL;
            int errnum = 0;
            if (client->tls.ssl) {
                errnum = wolfSSL_get_error(client->tls.ssl, 0);
                errstr = wolfSSL_ERR_reason_error_string(errnum);
            }

            printf("MqttSocket_TlsConnect Error %d: Num %d, %s\n",
                rc, errnum, errstr);
#endif

            /* Make sure we cleanup on error */
            MqttSocket_Disconnect(client);

            rc = MQTT_CODE_ERROR_TLS_CONNECT;
        }
    }
#else
    (void)cb;
#endif /* ENABLE_MQTT_TLS */

#ifdef WOLFMQTT_DEBUG_SOCKET
    printf("MqttSocket_Connect: Rc=%d\n", rc);
#endif

    /* Check for error */
    if (rc < 0) {
        rc = MQTT_CODE_ERROR_NETWORK;
    }

    return rc;
}
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                 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;
}
Exemplo n.º 30
0
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;
}