A fork of the TLS_cyassl embedded SSL library with certificate validation disabled.

Dependencies:   cyassl-lib

Fork of TLS_cyassl by Francois Berder

TLSConnection.cpp

Committer:
feb11
Date:
2013-09-13
Revision:
1:9494492e9bf7
Parent:
0:815067fd66c9
Child:
2:63ad554f6ca4

File content as of revision 1:9494492e9bf7:

#define __DEBUG__ 4 //Maximum verbosity
#ifndef __MODULE__
#define __MODULE__ "TLSConnection.cpp"
#endif

#define DEBUG_CYASSL 1
#include "dbg.h"
#include "TLSConnection.h"
#include <stdlib.h>
#include <stdio.h>
#include "bsd_socket.h"
#include "cert.h"
#undef NO_CERTS
#undef NO_FILESYSTEM
#include "ssl.h"
#include "logging.h"


const static int HTTPS_PORT = 443;

void printError(CYASSL *ssl, int resultCode) {

   int err = CyaSSL_get_error(ssl, resultCode);
   char errorString[80];
   CyaSSL_ERR_error_string(err, errorString);
   printf("Error: CyaSSL_write %s\n", errorString);

}

TLSConnection::TLSConnection():
    Socket(),
    Endpoint(),
    _is_connected(false),
    _ssl_ctx(),
    _ssl()
{
}

void debugCallback(const int logLevel,const char *const logMessage) {
   DBG(logMessage);
}

bool TLSConnection::connect(const char *host)
{
    if (init_socket(SOCK_STREAM) < 0)
        return false;

    if (set_address(host, HTTPS_PORT) != 0)
        return false;

    if (lwip_connect(_sock_fd, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)) < 0) {
        close();
        return false;
    }

    CyaSSL_Init();
    CyaSSL_Debugging_ON();

    CyaSSL_SetLoggingCb(&debugCallback);
    CYASSL_METHOD* method = CyaTLSv1_2_client_method();
    if(method == NULL)
    {
        return false;
    }

    _ssl_ctx = CyaSSL_CTX_new(method);
    if(_ssl_ctx == NULL)
    {
        return false;
    }    
    CyaSSL_CTX_load_verify_buffer(_ssl_ctx,(unsigned char*)root_cert, root_cert_len,SSL_FILETYPE_ASN1);

    _ssl = CyaSSL_new(_ssl_ctx);
    if(_ssl == NULL) 
    {
        return false;
    }
    CyaSSL_set_fd(_ssl, _sock_fd);

    int result = CyaSSL_connect(_ssl);
    if(result!=SSL_SUCCESS) 
    {
        printError(_ssl,result);
        return false;
    }  

    _is_connected = true;

    return true;
}

bool TLSConnection::is_connected(void)
{
    return _is_connected;
}

int TLSConnection::send_all(char *data, int length)
{
    if(!_is_connected)
        return 0;
        
    return CyaSSL_write(_ssl, data, length);
}

int TLSConnection::receive(char *data, int length)
{
    if(!_is_connected)
        return 0;
        
    return CyaSSL_read(_ssl, data, length);
}

bool TLSConnection::close(bool shutdown)
{
    if(!_is_connected)
        return true;

    _is_connected = false;

    CyaSSL_CTX_free(_ssl_ctx);
    CyaSSL_Cleanup();  

    return Socket::close(shutdown) == 0;
}