Exemplo n.º 1
0
static void test_client_wolfSSL_new(void)
{
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA)
    WOLFSSL_CTX *ctx;
    WOLFSSL_CTX *ctx_nocert;
    WOLFSSL *ssl;

    AssertNotNull(ctx_nocert = wolfSSL_CTX_new(wolfSSLv23_client_method()));
    AssertNotNull(ctx        = wolfSSL_CTX_new(wolfSSLv23_client_method()));

    AssertTrue(wolfSSL_CTX_load_verify_locations(ctx, caCert, 0));

    /* invalid context */
    AssertNull(ssl = wolfSSL_new(NULL));

    /* success */
    AssertNotNull(ssl = wolfSSL_new(ctx_nocert));
    wolfSSL_free(ssl);

    /* success */
    AssertNotNull(ssl = wolfSSL_new(ctx));
    wolfSSL_free(ssl);

    wolfSSL_CTX_free(ctx);
    wolfSSL_CTX_free(ctx_nocert);
#endif
}
/* Free the SSL/TLS connection data.
 *
 * ctx  The connection data.
 */
static void SSLConn_Free(SSLConn_CTX* ctx)
{
    int i;

    if (ctx == NULL)
        return;

    if (ctx->sslConn != NULL) {
        for (i = 0; i < ctx->numConns; i++)
            if (ctx->sslConn[i].ssl != NULL) {
                wolfSSL_free(ctx->sslConn[i].ssl);
                close(ctx->sslConn[i].sockfd);
            }

        if (ctx->sslConn != NULL)
            free(ctx->sslConn);
    }

    if (ctx->buffer != NULL)
        free(ctx->buffer);

    if (ctx->reply != NULL)
        free(ctx->reply);

    free(ctx);
}
Exemplo n.º 3
0
static void test_wolfSSL_UseSupportedCurve(void)
{
#ifdef HAVE_SUPPORTED_CURVES
    WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
    WOLFSSL     *ssl = wolfSSL_new(ctx);

    AssertNotNull(ctx);
    AssertNotNull(ssl);

#ifndef NO_WOLFSSL_CLIENT
    /* error cases */
    AssertIntNE(SSL_SUCCESS,
                      wolfSSL_CTX_UseSupportedCurve(NULL, WOLFSSL_ECC_SECP256R1));
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseSupportedCurve(ctx,  0));

    AssertIntNE(SSL_SUCCESS,
                          wolfSSL_UseSupportedCurve(NULL, WOLFSSL_ECC_SECP256R1));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseSupportedCurve(ssl,  0));

    /* success case */
    AssertIntEQ(SSL_SUCCESS,
                       wolfSSL_CTX_UseSupportedCurve(ctx, WOLFSSL_ECC_SECP256R1));
    AssertIntEQ(SSL_SUCCESS,
                           wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP256R1));
#endif

    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);
#endif
}
Exemplo n.º 4
0
static void test_server_wolfSSL_new(void)
{
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA)
    WOLFSSL_CTX *ctx;
    WOLFSSL_CTX *ctx_nocert;
    WOLFSSL *ssl;

    AssertNotNull(ctx_nocert = wolfSSL_CTX_new(wolfSSLv23_server_method()));
    AssertNotNull(ctx        = wolfSSL_CTX_new(wolfSSLv23_server_method()));

    AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCert, SSL_FILETYPE_PEM));
    AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKey, SSL_FILETYPE_PEM));

    /* invalid context */
    AssertNull(ssl = wolfSSL_new(NULL));
    AssertNull(ssl = wolfSSL_new(ctx_nocert));

    /* success */
    AssertNotNull(ssl = wolfSSL_new(ctx));

    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);
    wolfSSL_CTX_free(ctx_nocert);
#endif
}
Exemplo n.º 5
0
static void test_wolfSSL_UseMaxFragment(void)
{
#ifdef HAVE_MAX_FRAGMENT
    WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
    WOLFSSL     *ssl = wolfSSL_new(ctx);

    AssertNotNull(ctx);
    AssertNotNull(ssl);

    /* error cases */
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(NULL, WOLFSSL_MFL_2_9));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseMaxFragment(    NULL, WOLFSSL_MFL_2_9));
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(ctx, 0));
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(ctx, 6));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseMaxFragment(ssl, 0));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseMaxFragment(ssl, 6));

    /* success case */
    AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(ctx,  WOLFSSL_MFL_2_9));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(ctx,  WOLFSSL_MFL_2_10));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(ctx,  WOLFSSL_MFL_2_11));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(ctx,  WOLFSSL_MFL_2_12));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_UseMaxFragment(ctx,  WOLFSSL_MFL_2_13));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_UseMaxFragment(    ssl,  WOLFSSL_MFL_2_9));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_UseMaxFragment(    ssl,  WOLFSSL_MFL_2_10));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_UseMaxFragment(    ssl,  WOLFSSL_MFL_2_11));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_UseMaxFragment(    ssl,  WOLFSSL_MFL_2_12));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_UseMaxFragment(    ssl,  WOLFSSL_MFL_2_13));

    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);
#endif
}
Exemplo n.º 6
0
/* Free the WOLFSSL object and context. */
static void wolfssl_free(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
{
    if (ssl != NULL)
        wolfSSL_free(ssl);
    if (ctx != NULL)
        wolfSSL_CTX_free(ctx);
}
Exemplo n.º 7
0
static void* client_thread(void* args)
{
    /* set up client */
    WOLFSSL_CTX* cli_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
    if (cli_ctx == NULL) err_sys("bad client ctx new");

    int ret = wolfSSL_CTX_load_verify_locations(cli_ctx, cacert, NULL);
    if (ret != SSL_SUCCESS) err_sys("bad ca load");

    wolfSSL_SetIOSend(cli_ctx, ClientSend);
    wolfSSL_SetIORecv(cli_ctx, ClientRecv);

    WOLFSSL* cli_ssl = wolfSSL_new(cli_ctx);
    if (cli_ctx == NULL) err_sys("bad client new");

    ret = wolfSSL_connect(cli_ssl);
    if (ret != SSL_SUCCESS) err_sys("bad client tls connect");
    printf("wolfSSL client success!\n");

    ret = wolfSSL_write(cli_ssl, "hello memory wolfSSL!", 21);

    /* clean up */
    wolfSSL_free(cli_ssl);
    wolfSSL_CTX_free(cli_ctx);

    return NULL;
}
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;
}
NET_PRES_EncSessionStatus NET_PRES_EncProviderConnectionClose0(void * providerData)
{
    WOLFSSL* ssl;
    memcpy(&ssl, providerData, sizeof(WOLFSSL*));
    wolfSSL_free(ssl);
    return NET_PRES_ENC_SS_CLOSED;
}
Exemplo n.º 10
0
int ClientBenchmarkConnections(WOLFSSL_CTX* ctx, char* host, word16 port,
    int doDTLS, int benchmark, int resumeSession)
{
    /* time passed in number of connects give average */
    int times = benchmark;
    int loops = resumeSession ? 2 : 1;
    int i = 0;    
#ifndef NO_SESSION_CACHE
    WOLFSSL_SESSION* benchSession = NULL;
#endif
    (void)resumeSession;

    while (loops--) {
    #ifndef NO_SESSION_CACHE
        int benchResume = resumeSession && loops == 0;
    #endif
        double start = current_time(), avg;

        for (i = 0; i < times; i++) {
            SOCKET_T sockfd;
            WOLFSSL* ssl = wolfSSL_new(ctx);
            if (ssl == NULL)
                err_sys("unable to get SSL object");

            tcp_connect(&sockfd, host, port, doDTLS, ssl);

    #ifndef NO_SESSION_CACHE
            if (benchResume)
                wolfSSL_set_session(ssl, benchSession);
    #endif
            wolfSSL_set_fd(ssl, sockfd);
            if (wolfSSL_connect(ssl) != SSL_SUCCESS)
                err_sys("SSL_connect failed");

            wolfSSL_shutdown(ssl);
    #ifndef NO_SESSION_CACHE
            if (i == (times-1) && resumeSession) {
                benchSession = wolfSSL_get_session(ssl);
            }
    #endif
            wolfSSL_free(ssl);
            CloseSocket(sockfd);
        }
        avg = current_time() - start;
        avg /= times;
        avg *= 1000;   /* milliseconds */
    #ifndef NO_SESSION_CACHE
        if (benchResume)
            printf("wolfSSL_resume  avg took: %8.3f milliseconds\n", avg);
        else
    #endif
            printf("wolfSSL_connect avg took: %8.3f milliseconds\n", avg);
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 11
0
static void _mod_wolftls_freectx(void *vctx)
{
	int ret;
	_mod_wolftls_ctx_t *ctx = (_mod_wolftls_ctx_t *)vctx;
	dbg("TLS Close");
	wolfSSL_free(ctx->ssl);
	httpclient_addreceiver(ctx->ctl, ctx->recvreq, ctx->ctx);
	httpclient_addsender(ctx->ctl, ctx->sendresp, ctx->ctx);
	free(ctx);
}
Exemplo n.º 12
0
/* Create a new wolfSSL client with a server CA certificate. */
static int wolfssl_client_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl)
{
    int          ret = 0;
    WOLFSSL_CTX* client_ctx = NULL;
    WOLFSSL*     client_ssl = NULL;

    /* Create and initialize WOLFSSL_CTX */
    if ((client_ctx = wolfSSL_CTX_new_ex(wolfTLSv1_2_client_method(),
                                                   HEAP_HINT_CLIENT)) == NULL) {
        printf("ERROR: failed to create WOLFSSL_CTX\n");
        ret = -1;
    }

    if (ret == 0) {
        /* Load CA certificates into WOLFSSL_CTX */
        if (wolfSSL_CTX_load_verify_buffer(client_ctx, CA_CERTS, CA_CERTS_LEN,
                 WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) {
            printf("ERROR: failed to load CA certificate\n");
            ret = -1;
        }
    }

    if (ret == 0) {
        /* Register callbacks */
        wolfSSL_SetIORecv(client_ctx, recv_client);
        wolfSSL_SetIOSend(client_ctx, send_client);
    }

    if (ret == 0) {
        /* Create a WOLFSSL object */
        if ((client_ssl = wolfSSL_new(client_ctx)) == NULL) {
            printf("ERROR: failed to create WOLFSSL object\n");
            ret = -1;
        }
    }

    if (ret == 0) {
        /* make wolfSSL object nonblocking */
        wolfSSL_set_using_nonblock(client_ssl, 1);
    }

    if (ret == 0) {
        *ctx = client_ctx;
        *ssl = client_ssl;
    }
    else {
        if (client_ssl != NULL)
            wolfSSL_free(client_ssl);
        if (client_ctx != NULL)
            wolfSSL_CTX_free(client_ctx);
    }

    return ret;
}
Exemplo n.º 13
0
int Client(const char* ip, word16 port)
{
    int  n;
    char msg[] = "hello wolfssl";
    char reply[MAXSZ]; 
    int  msgSz = strlen(msg);
    SOCKET_T    fd;
    WOLFSSL_CTX* ctx;
    WOLFSSL*     ssl;

    if ((ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())) == NULL)
        err_sys("Error in setting client ctx\n");
    
    if (wolfSSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS)
        err_sys("trouble loading client cert");
    if (wolfSSL_CTX_use_certificate_file(ctx, cliCert, SSL_FILETYPE_PEM)
            != SSL_SUCCESS)
        err_sys("trouble loading client cert");
    if (wolfSSL_CTX_use_PrivateKey_file(ctx, cliKey, SSL_FILETYPE_PEM)
            != SSL_SUCCESS)
        err_sys("trouble loading client cert");

    /*sets the IO callback methods*/
    wolfSSL_SetIORecv(ctx, CbIORecv);
    wolfSSL_SetIOSend(ctx, CbIOSend);

    if ((ssl = wolfSSL_new(ctx)) == NULL)
        err_sys("issue when creating ssl");

    tcp_connect(&fd, ip, port, 0);
    wolfSSL_set_fd(ssl, fd);
    if (wolfSSL_connect(ssl) != SSL_SUCCESS)
        err_sys("client connect failed");

    if (wolfSSL_write(ssl, msg, msgSz) != msgSz)
        err_sys("client write failed");

    memset(reply, 0, MAXSZ);
    if ((n = wolfSSL_read(ssl, reply, MAXSZ - 1)) > 0) {
        reply[n] = '\0';
    }
    else {
        printf("client read returned %d\n", n);
        return -1;
    }
    printf("Server sent : %s\n", reply);

    wolfSSL_shutdown(ssl);
    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);

    return 0;
}
void *ThreadHandler(void* socketDesc)
{
    int     connd = *(int*)socketDesc;
    WOLFSSL* ssl;
    /* Create our reply message */
    const char reply[] = "I hear ya fa shizzle!\n";

    printf("Client connected successfully\n");

    if ( (ssl = wolfSSL_new(ctx)) == NULL) {
        fprintf(stderr, "wolfSSL_new error.\n");
        exit(EXIT_FAILURE);
    }

    /* Direct our ssl to our clients connection */
    wolfSSL_set_fd(ssl, connd);

    for ( ; ; ) {
        char buff[256];
        int  ret = 0;

        /* Clear the buffer memory for anything  possibly left over */
        memset(&buff, 0, sizeof(buff));

        /* Read the client data into our buff array */
        if ((ret = wolfSSL_read(ssl, buff, sizeof(buff)-1)) > 0) {
            /* Print any data the client sends to the console */
            printf("Client on Socket %d: %s\n", connd, buff);
            
            /* Reply back to the client */
            if ((ret = wolfSSL_write(ssl, reply, sizeof(reply)-1)) 
                < 0) {
                printf("wolfSSL_write error = %d\n", wolfSSL_get_error(ssl, ret));
            }
        }
        /* if the client disconnects break the loop */
        else {
            if (ret < 0)
                printf("wolfSSL_read error = %d\n", wolfSSL_get_error(ssl
                    ,ret));
            else if (ret == 0)
                printf("The client has closed the connection.\n");

            wolfSSL_free(ssl);           /* Free the WOLFSSL object */
            close(connd);               /* close the connected socket */
            break;
        }
    }

    exit(EXIT_SUCCESS);
}
Exemplo n.º 15
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();
}
bool NET_PRES_EncProviderStreamClientOpen0(uintptr_t transHandle, void * providerData)
{
        WOLFSSL* ssl = wolfSSL_new(net_pres_wolfSSLInfoStreamClient0.context);
        if (ssl == NULL)
        {
            return false;
        }
        if (wolfSSL_set_fd(ssl, transHandle) != SSL_SUCCESS)
        {
            wolfSSL_free(ssl);
            return false;
        }
        memcpy(providerData, &ssl, sizeof(WOLFSSL*));
        return true;
}
Exemplo n.º 17
0
/* Close an active connection.
 *
 * ctx      The SSL/TLS connection data.
 * sslConn  The SSL connection to close.
 */
static void SSLConn_Close(SSLConn_CTX* ctx, SSLConn* sslConn)
{
    if (wolfSSL_session_reused(sslConn->ssl))
        ctx->numResumed++;
    ctx->numConnections++;

    if (ctx->resume)
        sslConn->session = wolfSSL_get_session(sslConn->ssl);
    wolfSSL_free(sslConn->ssl);
    sslConn->ssl = NULL;

    close(sslConn->sockfd);
    sslConn->sockfd = -1;

    sslConn->state = INIT;

    ctx->cnt--;
}
/*
 * Process handled by a thread.
 */
void* wolfssl_thread(void* fd)
{
    WOLFSSL* ssl;
    int connfd = *((int*)fd);
    int  n;
    char buf[MAXLINE];
    char response[] = "I hear ya for shizzle";

    memset(buf, 0, MAXLINE);

    /* create WOLFSSL object */
    if ((ssl = wolfSSL_new(ctx)) == NULL) {
        printf("Fatal error : wolfSSL_new error");
        /* place signal for forced error exit here */
    }

    wolfSSL_set_fd(ssl, connfd);

    /* respond to client */
    n = wolfSSL_read(ssl, buf, MAXLINE);
    if (n > 0) {
        printf("%s\n", buf);
        if (wolfSSL_write(ssl, response, strlen(response))
                                      != strlen(response)) {
            printf("Fatal error :respond: write error\n");
            /* place signal for forced error exit here */
        }
    }
    if (n < 0) {
        printf("Fatal error : respond: read error\n");
        /* place signal for forced error exit here */
    }

    /* closes the connections after responding */
    wolfSSL_shutdown(ssl);
    wolfSSL_free(ssl);
    if (close(connfd) == -1) {
        printf("Fatal error : close error\n");
        /* place signal for forced error exit here */
    }

    pthread_exit(NULL);
}
/* Free the SSL/TLS connections that are closed.
 *
 * threadData  The SSL/TLS connection data for the thread.
 */
static void SSLConn_FreeSSLConn(ThreadData* threadData)
{
    SSLConn* sslConn = threadData->freeSSLConn;

    threadData->freeSSLConn = NULL;

    while (sslConn != NULL) {
        SSLConn* next = sslConn->next;

#ifdef WOLFSSL_ASYNC_CRYPT
        /* Clear out any events. */
        while (wolfSSL_AsyncPoll(sslConn->ssl, WOLF_POLL_FLAG_CHECK_HW) == 1)
             ;
#endif
        wolfSSL_free(sslConn->ssl);
        close(sslConn->sockfd);
        free(sslConn);

        sslConn = next;
    }
}
Exemplo n.º 20
0
static void test_wolfSSL_UseTruncatedHMAC(void)
{
#ifdef HAVE_TRUNCATED_HMAC
    WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
    WOLFSSL     *ssl = wolfSSL_new(ctx);

    AssertNotNull(ctx);
    AssertNotNull(ssl);

    /* error cases */
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseTruncatedHMAC(NULL));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseTruncatedHMAC(NULL));

    /* success case */
    AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_UseTruncatedHMAC(ctx));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_UseTruncatedHMAC(ssl));

    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);
#endif
}
Exemplo n.º 21
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.º 22
0
int main()
{
    /* set up server */
    WOLFSSL_CTX* srv_ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method());
    if (srv_ctx == NULL) err_sys("bad server ctx new");

    int ret = wolfSSL_CTX_use_PrivateKey_file(srv_ctx, key, SSL_FILETYPE_PEM);
    if (ret != SSL_SUCCESS) err_sys("bad server key file load");

    ret = wolfSSL_CTX_use_certificate_file(srv_ctx, cert, SSL_FILETYPE_PEM);
    if (ret != SSL_SUCCESS) err_sys("bad server cert file load");

    wolfSSL_SetIOSend(srv_ctx, ServerSend);
    wolfSSL_SetIORecv(srv_ctx, ServerRecv);

    WOLFSSL* srv_ssl = wolfSSL_new(srv_ctx);
    if (srv_ctx == NULL) err_sys("bad server new");

    /* start client thread */
    pthread_t tid;
    pthread_create(&tid, 0, client_thread, NULL);

    /* accept tls connection without tcp sockets */
    ret = wolfSSL_accept(srv_ssl);
    if (ret != SSL_SUCCESS) err_sys("bad server tls accept");
    printf("wolfSSL accept success!\n");

    /* read msg post handshake from client */
    unsigned char buf[80];
    memset(buf, 0, sizeof(buf));
    ret = wolfSSL_read(srv_ssl, buf, sizeof(buf)-1);
    printf("client msg = %s\n", buf);

    /* clean up */
    wolfSSL_free(srv_ssl);
    wolfSSL_CTX_free(srv_ctx);

    return 0;
}
Exemplo n.º 23
0
int main()
{
    int sd = socket(PF_INET, SOCK_STREAM, IPPROTO_SCTP);

    if (sd < 0)
        err_sys("sctp socket error");

    struct sockaddr_in sa;
    memset(&sa, 0, sizeof(sa));
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = htonl(INADDR_ANY);
    sa.sin_port = htons(12345);

    int ret = bind(sd, (struct sockaddr*)&sa, sizeof(sa));
    if (ret < 0)
        err_sys("sctp bind error");

    listen(sd, 3);

    int client_sd = accept(sd, NULL, NULL);
    if (client_sd < 0)
        err_sys("sctp accept error");

    const char* response = "well hello to you";
    char buffer[80];

    WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method());
    if (ctx == NULL)
        err_sys("ctx new dtls server failed");

    ret = wolfSSL_CTX_dtls_set_sctp(ctx);
    if (ret != SSL_SUCCESS)
        err_sys("set sctp mode failed");

    ret = wolfSSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM);
    if (ret != SSL_SUCCESS)
        err_sys("use private key error");

    ret = wolfSSL_CTX_use_certificate_file(ctx, cert, SSL_FILETYPE_PEM);
    if (ret != SSL_SUCCESS)
        err_sys("use cert error");

    WOLFSSL* ssl = wolfSSL_new(ctx);
    if (ssl == NULL)
        err_sys("ssl new dtls server failed");

    wolfSSL_set_fd(ssl, client_sd);

    ret = wolfSSL_accept(ssl);
    if (ret != SSL_SUCCESS)
        err_sys("ssl accept failed");

    printf("TLS version is %s\n", wolfSSL_get_version(ssl));
    printf("Cipher Suite is %s\n",
           wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl))); 

    int got = wolfSSL_read(ssl, buffer, sizeof(buffer));
    if (got > 0) {
        buffer[got] = 0;
        printf("client said: %s\n", buffer);
    }
    wolfSSL_write(ssl, response, (int)strlen(response));

    unsigned char bigBuf[4096];

    wolfSSL_read(ssl, bigBuf, sizeof(bigBuf));
    wolfSSL_write(ssl, bigBuf, sizeof(bigBuf));

    wolfSSL_shutdown(ssl);
    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);

    close(sd);

    return 0;
}
Exemplo n.º 24
0
/* See the comments at the top of main.c. */
void vSecureTCPServerTask( void *pvParameters )
{
BaseType_t xReturned;
long lBytes;
uint8_t cReceivedString[ 60 ];
struct sockaddr_in xClient;
int xClientAddressLength = sizeof( struct sockaddr_in );
SOCKET xListeningSocket, xConnectedSocket;
WOLFSSL* xWolfSSL_Object; /* Only one connection is accepted at a time, so only one object is needed at a time. */

	/* Just to prevent compiler warnings. */
	( void ) pvParameters;

	/* Perform the initialisation necessary before wolfSSL can be used. */
	prvInitialiseWolfSSL();
	configASSERT( xWolfSSL_ServerContext );

	/* Attempt to open the socket. */
	xListeningSocket = prvOpenServerSocket();

	/* Now the server socket has been created and the wolfSSL library has been
	initialised, the task that implements the client side can be created. */
	xTaskCreate( vSecureTCPClientTask, "Client", configMINIMAL_STACK_SIZE, NULL, sstSECURE_CLIENT_TASK_PRIORITY, NULL );

	if( xListeningSocket != INVALID_SOCKET )
	{
		for( ;; )
		{
			/* Wait until the client connects. */
			printf( "Waiting for new connection\r\n" );
			xConnectedSocket = accept( xListeningSocket, ( struct sockaddr * ) &xClient, &xClientAddressLength );

			if( xConnectedSocket != INVALID_SOCKET )
			{
				printf( "Connection established\r\n" );

				/* A connection has been accepted by the server.  Create a
				wolfSSL object for use with the newly connected socket. */
				xWolfSSL_Object = NULL;
				xWolfSSL_Object = wolfSSL_new( xWolfSSL_ServerContext );

				if( xWolfSSL_Object != NULL )
				{
					/* Associate the created wolfSSL object with the connected
					socket. */
					xReturned = wolfSSL_set_fd( xWolfSSL_Object, xConnectedSocket );
					configASSERT( xReturned == SSL_SUCCESS );

					do
					{
						/* The next line is the secure equivalent to the
						standard sockets call:
						lBytes = recv( xConnectedSocket, cReceivedString, 50, 0 ); */
						lBytes = wolfSSL_read( xWolfSSL_Object, cReceivedString, sizeof( cReceivedString ) );

						/* Print the received characters. */
						if( lBytes > 0 )
						{
							printf( "Received by the secure server: %s\r\n", cReceivedString );
						}

					} while ( lBytes > 0 );

					/* The connection was closed, close the socket and free the
					wolfSSL object. */
					closesocket( xConnectedSocket );
					wolfSSL_free( xWolfSSL_Object );
					printf( "Connection closed, back to start\r\n\r\n" );
				}
			}
		}
	}
	else
	{
		/* The socket could not be opened. */
		vTaskDelete( NULL );
	}
}
Exemplo n.º 25
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.º 26
0
static void destroy_wolfssl_instance(TLS_IO_INSTANCE* tls_io_instance)
{
    wolfSSL_free(tls_io_instance->ssl);
}
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.º 28
0
THREAD_RETURN WOLFSSL_THREAD client_test(void* args)
{
    SOCKET_T sockfd = 0;

    WOLFSSL_METHOD*  method  = 0;
    WOLFSSL_CTX*     ctx     = 0;
    WOLFSSL*         ssl     = 0;
    
    WOLFSSL*         sslResume = 0;
    WOLFSSL_SESSION* session = 0;
    char         resumeMsg[] = "resuming wolfssl!";
    int          resumeSz    = sizeof(resumeMsg);

    char msg[32] = "hello wolfssl!";   /* GET may make bigger */
    char reply[80];
    int  input;
    int  msgSz = (int)strlen(msg);

    word16 port   = yasslPort;
    char* host   = (char*)yasslIP;
    const char* domain = "www.yassl.com";

    int    ch;
    int    version = CLIENT_INVALID_VERSION;
    int    usePsk   = 0;
    int    useAnon  = 0;
    int    sendGET  = 0;
    int    benchmark = 0;
    int    doDTLS    = 0;
    int    matchName = 0;
    int    doPeerCheck = 1;
    int    nonBlocking = 0;
    int    resumeSession = 0;
    int    scr           = 0;    /* allow secure renegotiation */
    int    forceScr      = 0;    /* force client initiaed scr */
    int    trackMemory   = 0;
    int    useClientCert = 1;
    int    fewerPackets  = 0;
    int    atomicUser    = 0;
    int    pkCallbacks   = 0;
    int    overrideDateErrors = 0;
    char*  cipherList = NULL;
    const char* verifyCert = caCert;
    const char* ourCert    = cliCert;
    const char* ourKey     = cliKey;

#ifdef HAVE_SNI
    char*  sniHostName = NULL;
#endif
#ifdef HAVE_MAX_FRAGMENT
    byte maxFragment = 0;
#endif
#ifdef HAVE_TRUNCATED_HMAC
    byte  truncatedHMAC = 0;
#endif


#ifdef HAVE_OCSP
    int    useOcsp  = 0;
    char*  ocspUrl  = NULL;
#endif

    int     argc = ((func_args*)args)->argc;
    char**  argv = ((func_args*)args)->argv;

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)eccCert;
    ourCert    = (char*)cliEccCert;
    ourKey     = (char*)cliEccKey;
#endif
    (void)resumeSz;
    (void)session;
    (void)sslResume;
    (void)trackMemory;
    (void)atomicUser;
    (void)pkCallbacks;
    (void)scr;
    (void)forceScr;

    StackTrap();

    while ((ch = mygetopt(argc, argv,
                          "?gdDusmNrRitfxUPh:p:v:l:A:c:k:b:zS:L:ToO:a")) != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'g' :
                sendGET = 1;
                break;

            case 'd' :
                doPeerCheck = 0;
                break;

            case 'D' :
                overrideDateErrors = 1;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_WOLFSSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'm' :
                matchName = 1;
                break;

            case 'x' :
                useClientCert = 0;
                break;

            case 'f' :
                fewerPackets = 1;
                break;

            case 'U' :
            #ifdef ATOMIC_USER
                atomicUser = 1;
            #endif
                break;

            case 'P' :
            #ifdef HAVE_PK_CALLBACKS 
                pkCallbacks = 1;
            #endif
                break;

            case 'h' :
                host   = myoptarg;
                domain = myoptarg;
                break;

            case 'p' :
                port = (word16)atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'b' :
                benchmark = atoi(myoptarg);
                if (benchmark < 0 || benchmark > 1000000) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'N' :
                nonBlocking = 1;
                break;

            case 'r' :
                resumeSession = 1;
                break;

            case 'R' :
                #ifdef HAVE_SECURE_RENEGOTIATION
                    scr = 1;
                #endif
                break;

            case 'i' :
                #ifdef HAVE_SECURE_RENEGOTIATION
                    scr      = 1;
                    forceScr = 1;
                #endif
                break;

            case 'z' :
                #ifndef WOLFSSL_LEANPSK
                    wolfSSL_GetObjectSize();
                #endif
                break;

            case 'S' :
                #ifdef HAVE_SNI
                    sniHostName = myoptarg;
                #endif
                break;

            case 'L' :
                #ifdef HAVE_MAX_FRAGMENT
                    maxFragment = atoi(myoptarg);
                    if (maxFragment < WOLFSSL_MFL_2_9 ||
                                                maxFragment > WOLFSSL_MFL_2_13) {
                        Usage();
                        exit(MY_EX_USAGE);
                    }
                #endif
                break;

            case 'T' :
                #ifdef HAVE_TRUNCATED_HMAC
                    truncatedHMAC = 1;
                #endif
                break;

            case 'o' :
                #ifdef HAVE_OCSP
                    useOcsp = 1;
                #endif
                break;

            case 'O' :
                #ifdef HAVE_OCSP
                    useOcsp = 1;
                    ocspUrl = myoptarg;
                #endif
                break;

            case 'a' :
                #ifdef HAVE_ANON
                    useAnon = 1;
                #endif
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_WOLFSSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = wolfSSLv3_client_method();
            break;
                
                
    #ifndef NO_TLS
        case 1:
            method = wolfTLSv1_client_method();
            break;

        case 2:
            method = wolfTLSv1_1_client_method();
            break;
    #endif /* NO_TLS */
                
#endif  /* NO_OLD_TLS */
                
#ifndef NO_TLS
        case 3:
            method = wolfTLSv1_2_client_method();
            break;
#endif

#ifdef WOLFSSL_DTLS
        case -1:
            method = wolfDTLSv1_client_method();
            break;

        case -2:
            method = wolfDTLSv1_2_client_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
            break;
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = wolfSSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

    if (cipherList)
        if (wolfSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("client can't set cipher list 1");

#ifdef WOLFSSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

    if (fewerPackets)
        wolfSSL_CTX_set_group_messages(ctx);

    if (usePsk) {
#ifndef NO_PSK
        wolfSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (wolfSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS)
                err_sys("client can't set cipher list 2");
        }
#endif
        useClientCert = 0;
    }

    if (useAnon) {
#ifdef HAVE_ANON
        if (cipherList == NULL) {
            wolfSSL_CTX_allow_anon_cipher(ctx);
            if (wolfSSL_CTX_set_cipher_list(ctx,"ADH-AES128-SHA") != SSL_SUCCESS)
                err_sys("client can't set cipher list 4");
        }
#endif
        useClientCert = 0;
    }

#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
    wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(WOLFSSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    if (cipherList == NULL) {
        /* don't use EDH, can't sniff tmp keys */
        if (wolfSSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS) {
            err_sys("client can't set cipher list 3");
        }
    }
#endif

#ifdef HAVE_OCSP
    if (useOcsp) {
        if (ocspUrl != NULL) {
            wolfSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl);
            wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE
                                                    | WOLFSSL_OCSP_URL_OVERRIDE);
        }
        else
            wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE);
    }
#endif

#ifdef USER_CA_CB
    wolfSSL_CTX_SetCACb(ctx, CaCb);
#endif

#ifdef VERIFY_CALLBACK
    wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify);
#endif
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (useClientCert){
        if (wolfSSL_CTX_use_certificate_chain_file(ctx, ourCert) != SSL_SUCCESS)
            err_sys("can't load client cert file, check file and run from"
                    " wolfSSL home dir");

        if (wolfSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load client private key file, check file and run "
                    "from wolfSSL home dir");
    }

    if (!usePsk && !useAnon) {
        if (wolfSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
                err_sys("can't load ca file, Please run from wolfSSL home dir");
    }
#endif
#if !defined(NO_CERTS)
    if (!usePsk && !useAnon && doPeerCheck == 0)
        wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
    if (!usePsk && !useAnon && overrideDateErrors == 1)
        wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myDateCb);
#endif

#ifdef HAVE_CAVIUM
    wolfSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID);
#endif

#ifdef HAVE_SNI
    if (sniHostName)
        if (wolfSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName))
                                                                 != SSL_SUCCESS)
            err_sys("UseSNI failed");
#endif
#ifdef HAVE_MAX_FRAGMENT
    if (maxFragment)
        if (wolfSSL_CTX_UseMaxFragment(ctx, maxFragment) != SSL_SUCCESS)
            err_sys("UseMaxFragment failed");
#endif
#ifdef HAVE_TRUNCATED_HMAC
    if (truncatedHMAC)
        if (wolfSSL_CTX_UseTruncatedHMAC(ctx) != SSL_SUCCESS)
            err_sys("UseTruncatedHMAC failed");
#endif
#ifdef HAVE_SESSION_TICKET
    if (wolfSSL_CTX_UseSessionTicket(ctx) != SSL_SUCCESS)
        err_sys("UseSessionTicket failed");
#endif

    if (benchmark) {
        /* time passed in number of connects give average */
        int times = benchmark;
        int i = 0;

        double start = current_time(), avg;

        for (i = 0; i < times; i++) {
            tcp_connect(&sockfd, host, port, doDTLS);

            ssl = wolfSSL_new(ctx);
            wolfSSL_set_fd(ssl, sockfd);
            if (wolfSSL_connect(ssl) != SSL_SUCCESS)
                err_sys("SSL_connect failed");

            wolfSSL_shutdown(ssl);
            wolfSSL_free(ssl);
            CloseSocket(sockfd);
        }
        avg = current_time() - start;
        avg /= times;
        avg *= 1000;   /* milliseconds */
        printf("wolfSSL_connect avg took: %8.3f milliseconds\n", avg);

        wolfSSL_CTX_free(ctx);
        ((func_args*)args)->return_code = 0;

        exit(EXIT_SUCCESS);
    }
    
    #if defined(WOLFSSL_MDK_ARM)
    wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
    #endif
    
    ssl = wolfSSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL object");
    #ifdef HAVE_SESSION_TICKET
    wolfSSL_set_SessionTicket_cb(ssl, sessionTicketCB, (void*)"initial session");
    #endif
    if (doDTLS) {
        SOCKADDR_IN_T addr;
        build_addr(&addr, host, port, 1);
        wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
        tcp_socket(&sockfd, 1);
    }
    else {
        tcp_connect(&sockfd, host, port, 0);
    }

#ifdef HAVE_POLY1305
    /* use old poly to connect with google server */
    if (!XSTRNCMP(domain, "www.google.com", 14)) {
        if (wolfSSL_use_old_poly(ssl, 1) != 0)
            err_sys("unable to set to old poly");
    }
#endif

    wolfSSL_set_fd(ssl, sockfd);
#ifdef HAVE_CRL
    if (wolfSSL_EnableCRL(ssl, WOLFSSL_CRL_CHECKALL) != SSL_SUCCESS)
        err_sys("can't enable crl check");
    if (wolfSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS)
        err_sys("can't load crl, check crlfile and date validity");
    if (wolfSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
        err_sys("can't set crl callback");
#endif
#ifdef HAVE_SECURE_RENEGOTIATION
    if (scr) {
        if (wolfSSL_UseSecureRenegotiation(ssl) != SSL_SUCCESS)
            err_sys("can't enable secure renegotiation");
    }
#endif
#ifdef ATOMIC_USER
    if (atomicUser)
        SetupAtomicUser(ctx, ssl);
#endif
#ifdef HAVE_PK_CALLBACKS
    if (pkCallbacks)
        SetupPkCallbacks(ctx, ssl);
#endif
    if (matchName && doPeerCheck)
        wolfSSL_check_domain_name(ssl, domain);
#ifndef WOLFSSL_CALLBACKS
    if (nonBlocking) {
        wolfSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&sockfd);
        NonBlockingSSL_Connect(ssl);
    }
    else if (wolfSSL_connect(ssl) != SSL_SUCCESS) {
        /* see note at top of README */
        int  err = wolfSSL_get_error(ssl, 0);
        char buffer[WOLFSSL_MAX_ERROR_SZ];
        printf("err = %d, %s\n", err,
                                wolfSSL_ERR_error_string(err, buffer));
        err_sys("SSL_connect failed");
        /* if you're getting an error here  */
    }
#else
    timeout.tv_sec  = 2;
    timeout.tv_usec = 0;
    NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif
    showPeer(ssl);

#ifdef HAVE_SECURE_RENEGOTIATION
    if (scr && forceScr) {
        if (nonBlocking) {
            printf("not doing secure renegotiation on example with"
                   " nonblocking yet");
        } else {
            #ifndef NO_SESSION_CACHE
                if (resumeSession) {
                    session = wolfSSL_get_session(ssl);
                    wolfSSL_set_session(ssl, session);
                    resumeSession = 0;  /* only resume once */
                }
            #endif
            if (wolfSSL_Rehandshake(ssl) != SSL_SUCCESS) {
                int  err = wolfSSL_get_error(ssl, 0);
                char buffer[WOLFSSL_MAX_ERROR_SZ];
                printf("err = %d, %s\n", err,
                                wolfSSL_ERR_error_string(err, buffer));
                err_sys("wolfSSL_Rehandshake failed");
            }
        }
    }
#endif /* HAVE_SECURE_RENEGOTIATION */

    if (sendGET) {
        printf("SSL connect ok, sending GET...\n");
        msgSz = 28;
        strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz);
        msg[msgSz] = '\0';
    }
    if (wolfSSL_write(ssl, msg, msgSz) != msgSz)
        err_sys("SSL_write failed");

    input = wolfSSL_read(ssl, reply, sizeof(reply)-1);
    if (input > 0) {
        reply[input] = 0;
        printf("Server response: %s\n", reply);

        if (sendGET) {  /* get html */
            while (1) {
                input = wolfSSL_read(ssl, reply, sizeof(reply)-1);
                if (input > 0) {
                    reply[input] = 0;
                    printf("%s\n", reply);
                }
                else
                    break;
            }
        }
    }
    else if (input < 0) {
        int readErr = wolfSSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("wolfSSL_read failed");
    }

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            strncpy(msg, "break", 6);
            msgSz = (int)strlen(msg);
            /* try to send session close */
            wolfSSL_write(ssl, msg, msgSz);
        }
        session   = wolfSSL_get_session(ssl);
        sslResume = wolfSSL_new(ctx);
    }
#endif

    if (doDTLS == 0)            /* don't send alert after "break" command */
        wolfSSL_shutdown(ssl);  /* echoserver will interpret as new conn */
#ifdef ATOMIC_USER
    if (atomicUser)
        FreeAtomicUser(ssl);
#endif
    wolfSSL_free(ssl);
    CloseSocket(sockfd);

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            SOCKADDR_IN_T addr;
            #ifdef USE_WINDOWS_API 
                Sleep(500);
            #elif defined(WOLFSSL_TIRTOS)
                Task_sleep(1);
            #else
                sleep(1);
            #endif
            build_addr(&addr, host, port, 1);
            wolfSSL_dtls_set_peer(sslResume, &addr, sizeof(addr));
            tcp_socket(&sockfd, 1);
        }
        else {
            tcp_connect(&sockfd, host, port, 0);
        }
        wolfSSL_set_fd(sslResume, sockfd);
        wolfSSL_set_session(sslResume, session);
#ifdef HAVE_SESSION_TICKET
        wolfSSL_set_SessionTicket_cb(sslResume, sessionTicketCB,
                                    (void*)"resumed session");
#endif
       
        showPeer(sslResume);
#ifndef WOLFSSL_CALLBACKS
        if (nonBlocking) {
            wolfSSL_set_using_nonblock(sslResume, 1);
            tcp_set_nonblocking(&sockfd);
            NonBlockingSSL_Connect(sslResume);
        }
        else if (wolfSSL_connect(sslResume) != SSL_SUCCESS)
            err_sys("SSL resume failed");
#else
        timeout.tv_sec  = 2;
        timeout.tv_usec = 0;
        NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif

        if (wolfSSL_session_reused(sslResume))
            printf("reused session id\n");
        else
            printf("didn't reuse session id!!!\n");

        if (wolfSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz)
            err_sys("SSL_write failed");

        if (nonBlocking) {
            /* give server a chance to bounce a message back to client */
            #ifdef USE_WINDOWS_API
                Sleep(500);
            #elif defined(WOLFSSL_TIRTOS)
                Task_sleep(1);
            #else
                sleep(1);
            #endif
        }

        input = wolfSSL_read(sslResume, reply, sizeof(reply)-1);
        if (input > 0) {
            reply[input] = 0;
            printf("Server resume response: %s\n", reply);
        }

        /* try to send session break */
        wolfSSL_write(sslResume, msg, msgSz); 

        wolfSSL_shutdown(sslResume);
        wolfSSL_free(sslResume);
        CloseSocket(sockfd);
    }
#endif /* NO_SESSION_CACHE */

    wolfSSL_CTX_free(ctx);

    ((func_args*)args)->return_code = 0;

#ifdef USE_WOLFSSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_WOLFSSL_MEMORY */

#if !defined(WOLFSSL_TIRTOS)
    return 0;
#endif
}
Exemplo n.º 29
0
/* See the comments at the top of main.c. */
void vSecureTCPClientTask( void *pvParameters )
{
SOCKET xClientSocket;
struct sockaddr_in xConnection;
WOLFSSL* xWolfSSL_Object;
WORD wVersionRequested;
WSADATA xWSAData;
char cString[ 50 ];
BaseType_t lReturned;
uint32_t ulCount = 0UL;

	/* Remove compiler warning about unused parameters. */
	( void ) pvParameters;

	/* Prepare to use WinSock. */
	wVersionRequested = MAKEWORD( 2, 2 );
	configASSERT( WSAStartup( wVersionRequested, &xWSAData ) == 0 );

	/* Set family and port for client socket. */
	memset( ( void * ) &xConnection, 0x00, sizeof( struct sockaddr_in ) );
	xConnection.sin_family = AF_INET;
	xConnection.sin_addr.s_addr = inet_addr("127.0.0.1");
	xConnection.sin_port = htons( configTCP_PORT_NUMBER );

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

    /* Load the CA certificate. */
    lReturned = wolfSSL_CTX_load_verify_locations( xWolfSSL_ClientContext, "ca-cert.pem", 0 );
	configASSERT( lReturned == SSL_SUCCESS );

	for( ;; )
	{
		/* Create the socket. */
		xClientSocket = socket( AF_INET, SOCK_STREAM, 0 );
		configASSERT( xClientSocket != INVALID_SOCKET );

		/* Connect to the secure server. */
		if( connect( xClientSocket, ( SOCKADDR * ) &xConnection, sizeof( xConnection ) ) == 0 )
		{
			/* The connect was successful.  Create a wolfSSL object to associate
			with this connection. */
			xWolfSSL_Object = wolfSSL_new( xWolfSSL_ClientContext );

			if( xWolfSSL_Object != NULL )
			{
				/* Associate the created wolfSSL object with the connected
				socket. */
				lReturned = wolfSSL_set_fd( xWolfSSL_Object, xClientSocket );
				configASSERT( lReturned == SSL_SUCCESS );

				/* The count is used to differentiate between messages sent to
				the server, and to break out of the do while loop below. */
				ulCount = 0UL;

				do
				{
					/* Create the string that is sent to the secure server. */
					sprintf( cString, "Message number %lu\r\n", ulCount );

					/* The next line is the secure equivalent of the standard
					sockets call:
					lReturned = send( xClientSocket, cString, strlen( cString ) + 1, 0 ); */
					lReturned = wolfSSL_write( xWolfSSL_Object, cString, strlen( cString ) + 1 );


					/* Short delay to prevent the messages streaming up the
					console too quickly. */
					vTaskDelay( 50 );
					ulCount++;

				} while( ( lReturned != SOCKET_ERROR ) && ( ulCount < 10UL ) );
			}

			wolfSSL_free( xWolfSSL_Object );
			closesocket( xClientSocket );

			/* Delay for a short time before starting over. */
			vTaskDelay( 250 );
		}
	}
}
Exemplo n.º 30
-1
static void test_wolfSSL_UseSNI_params(void)
{
    WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
    WOLFSSL     *ssl = wolfSSL_new(ctx);

    AssertNotNull(ctx);
    AssertNotNull(ssl);

    /* invalid [ctx|ssl] */
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseSNI(NULL, 0, "ctx", 3));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseSNI(    NULL, 0, "ssl", 3));
    /* invalid type */
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx, -1, "ctx", 3));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseSNI(    ssl, -1, "ssl", 3));
    /* invalid data */
    AssertIntNE(SSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx,  0, NULL,  3));
    AssertIntNE(SSL_SUCCESS, wolfSSL_UseSNI(    ssl,  0, NULL,  3));
    /* success case */
    AssertIntEQ(SSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx,  0, "ctx", 3));
    AssertIntEQ(SSL_SUCCESS, wolfSSL_UseSNI(    ssl,  0, "ssl", 3));

    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);
}