Example TLS client with wolfSSL, with cert

Dependencies:   EthernetInterface NTPClient SDFileSystem mbed-rtos mbed wolfSSL

client-tls.cpp

Committer:
wolfSSL
Date:
2015-07-24
Revision:
6:e636986882e8
Parent:
5:26b87ccd43d1

File content as of revision 6:e636986882e8:

/* client-tcp.c
 *
 * Copyright (C) 2006-2015 wolfSSL Inc.
 *
 * This file is part of wolfSSL. (formerly known as CyaSSL)
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include    "mbed.h"
#include    "EthernetInterface.h"
#include    "NTPClient.h"
#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include    <wolfssl/ssl.h>          /* wolfSSL security library */
#include    <wolfssl/wolfcrypt/error-crypt.h>
#include    <user_settings.h>

#define MAXDATASIZE (1024*4)

#if defined(NO_FILESYSTEM)
    #define     USE_CERT_BUFFERS_2048
    #include    <wolfssl/certs_test.h>
#else
    #include    "SDFileSystem.h"
    SDFileSystem sdCard(PTE3, PTE1, PTE2, PTE4, "sd");
    const char* certFile = "/sd/ca-cert.pem";
#endif

static int SocketReceive(WOLFSSL* ssl, char *buf, int sz, void *sock)
{
    return ((TCPSocketConnection *)sock)->receive(buf, sz) ;
}

static int SocketSend(WOLFSSL* ssl, char *buf, int sz, void *sock)
{
    return ((TCPSocketConnection *)sock)->send(buf, sz);
}

static int getline(char *prompt, char *buff, int size)
{
    int sz ;
    
    printf("%s", prompt) ;
    for(sz = 0 ;  (sz < size) && ((*buff = getchar()) != '\r'); sz++, buff++) {
        putchar(*buff) ;
        if(*buff == '\\') {
            if(++sz >= size)break ;
            *buff = getchar() ;
            putchar(*buff) ;
            switch(*buff) {
                case 'n' :
                    *buff = '\n' ;
                    break ;
                case 'r' :
                    *buff = '\r' ;
                    break ;
                case 't' :
                    *buff = '\t' ;
                    break ;
                case '\\':
                    *buff = '\\' ;
                    break ;
                default:
                    buff[1] = buff[0] ;
                    buff[0] = '\\' ;
                    buff++ ;
            }
        } else if(*buff == '\b') {
            if(sz >= 2) {
                buff-=2 ;
                sz-=2;
            }
        }
    } ;
    putchar('\n') ;
    *buff = '\0' ;
    return sz ;
}

/*
 *  clients initial contact with server. Socket to connect to: sock
 */
 int ClientGreet(TCPSocketConnection *socket, WOLFSSL *ssl)
{
    /* data to send to the server, data recieved from the server */
    char    sendBuff[MAXDATASIZE], rcvBuff[MAXDATASIZE] = {0};
    int     ret ;

    ret = getline("Message for server: ", sendBuff, MAXDATASIZE);
    printf("Send[%d]:\n%s\n", ret, sendBuff) ;
    if (wolfSSL_write(ssl, sendBuff, strlen(sendBuff)) < 0) {
        /* the message is not able to send, or error trying */
        ret = wolfSSL_get_error(ssl, 0);
        printf("Write error[%d]\n", ret, wc_GetErrorString(ret));
        return EXIT_FAILURE;
    }
    printf("Recieved:\n");
    while(1) {
        if ((ret = wolfSSL_read(ssl, rcvBuff, sizeof(rcvBuff)-1)) < 0) {
            if(ret == 0)break ;
            /* the server failed to send data, or error trying */
            ret = wolfSSL_get_error(ssl, 0);
            printf("Read error[%d], %s\n", ret, wc_GetErrorString(ret));
            return EXIT_FAILURE;
        }
        rcvBuff[ret] = '\0' ;
        printf("%s", rcvBuff);
        if((rcvBuff[ret-3] == '\n')&&
           (rcvBuff[ret-2] == '\n')&&
           (rcvBuff[ret-1] == '\n'))break ;
    }
    return ret;
}


/*
 * applies TLS 1.2 security layer to data being sent.
 */
int Security(TCPSocketConnection *socket)
{
    WOLFSSL_CTX* ctx;
    WOLFSSL*     ssl;    /* create WOLFSSL object */
    int         ret = 0;

    /* 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;
    }

    wolfSSL_SetIORecv(ctx, SocketReceive) ;
    wolfSSL_SetIOSend(ctx, SocketSend) ;

#ifndef NO_FILESYSTEM
    if (wolfSSL_CTX_load_verify_locations(ctx, certFile,0) != SSL_SUCCESS)
            printf("can't load ca file\n");
#else
    if (wolfSSL_CTX_load_verify_buffer(ctx,  ca_cert_der_2048,
                sizeof_ca_cert_der_2048, SSL_FILETYPE_ASN1) != SSL_SUCCESS)
            printf("can't load ca data");            
#endif

    if ((ssl = wolfSSL_new(ctx)) == NULL) {
        printf("wolfSSL_new error.\n");
        return EXIT_FAILURE;
    }
    wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
    wolfSSL_SetIOReadCtx(ssl, (void *)socket) ;
    wolfSSL_SetIOWriteCtx(ssl, (void *)socket) ;

    ret = wolfSSL_connect(ssl);
    if (ret == SSL_SUCCESS) {
        printf("TLS Connected\n") ;
        ret = ClientGreet(socket, ssl);
    } else {
        ret = wolfSSL_get_error(ssl, 0);
        printf("TLS Connect error[%d], %s\n", ret, wc_GetErrorString(ret));
        return EXIT_FAILURE;
    }
    /* frees all data before client termination */
    wolfSSL_free(ssl);
    wolfSSL_CTX_free(ctx);
    wolfSSL_Cleanup();

    return ret;
}

/*
 * command line argumentCount and argumentValues
 */
void net_main(const void *av)
{
    char server_addr[40] ;
    char server_port[10] ;
    
    wolfSSL_Init();      /* initialize wolfSSL */
    /* wolfSSL_Debugging_ON(); */
    EthernetInterface eth;
    TCPSocketConnection socket;

    eth.init(); //Use DHCP
    while(1) {
        if(eth.connect() == 0)break ;
        printf("Retry\n") ;
    }
    printf("Client Addr: %s\n", eth.getIPAddress());

    NTPClient ntp;   
    if(ntp.setTime("ntp.jst.mfeed.ad.jp") != 0){
       printf("NTP Error\n") ;
       return ;
    }

    getline("Server Addr: ", server_addr, sizeof(server_addr)) ;
    getline("Server Port: ", server_port, sizeof(server_port)) ;
    
    while (socket.connect(server_addr, atoi(server_port)) < 0) {
        printf("Unable to connect to (%s) on port (%s)\n", server_addr, server_port);
        wait(1.0);
    }
    printf("TCP Connected\n") ;

    Security(&socket);
    return ;
}

int main(void)
{
#define STACK_SIZE 24000
    Thread t(net_main, NULL, osPriorityNormal, STACK_SIZE);
    while(1)wait(1.0) ;
}