Fork of Hello MQTT, using mbed TLS for secure mqtt transport

Dependencies:   MQTT

Fork of HelloMQTT by MQTT

MQTTSNetwork.h

Committer:
vpcola
Date:
2017-03-17
Revision:
21:4534812bb94f
Child:
22:4d0628d13870

File content as of revision 21:4534812bb94f:

#ifndef _MQTTSNETWORK_H_
#define _MQTTSNETWORK_H_
 
#include "NetworkInterface.h"
#include "TCPSocket.h"
#include "mbedtls/platform.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"

#if DEBUG_LEVEL > 0
#include "mbedtls/debug.h"
#endif
 
class MQTTSNetwork {
public:
 
    MQTTSNetwork() 
        : tcpsocket(NULL)
        ,ssl_ca_pem(NULL)
        ,keepalive(1)
    {
        DRBG_PERS = "mbed TLS MQTT client";
                
        mbedtls_entropy_init(&_entropy);
        mbedtls_ctr_drbg_init(&_ctr_drbg);
        mbedtls_x509_crt_init(&_cacert);
        mbedtls_ssl_init(&_ssl);
        mbedtls_ssl_config_init(&_ssl_conf);        
        memset( &saved_session, 0, sizeof( mbedtls_ssl_session ) );
    }
    
    ~MQTTSNetwork() 
    {

        mbedtls_entropy_free(&_entropy);
        mbedtls_ctr_drbg_free(&_ctr_drbg);
        mbedtls_x509_crt_free(&_cacert);
        mbedtls_ssl_free(&_ssl);
        mbedtls_ssl_config_free(&_ssl_conf);        
        
        if (tcpsocket)
            delete tcpsocket;
                    
    }
    

    
    int setupTLS(NetworkInterface * net, const char * pem)
    {
        int ret;
        
        network = net;
        ssl_ca_pem = pem;
        
        printf("Initializing TLS ...\r\n");
        printf("mbedtls_ctr_drdbg_seed ...\r\n");
        if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy,
                          (const unsigned char *) DRBG_PERS,
                          sizeof (DRBG_PERS))) != 0) {
            print_mbedtls_error("mbedtls_crt_drbg_init", ret);
            _error = ret;
            return -1;
        }
        printf("mbedtls_x509_crt_parse ...\r\n");
        if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *) ssl_ca_pem,
                           strlen(ssl_ca_pem) + 1)) != 0) {
            print_mbedtls_error("mbedtls_x509_crt_parse", ret);
            _error = ret;
            return -1;
        }

        printf("mbedtls_ssl_config_defaults ...\r\n");
        if ((ret = mbedtls_ssl_config_defaults(&_ssl_conf,
                        MBEDTLS_SSL_IS_CLIENT,
                        MBEDTLS_SSL_TRANSPORT_STREAM,
                        MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
            print_mbedtls_error("mbedtls_ssl_config_defaults", ret);
            _error = ret;
            return -1;
        }

        printf("mbedtls_ssl_config_ca_chain ...\r\n");
        mbedtls_ssl_conf_ca_chain(&_ssl_conf, &_cacert, NULL);
        printf("mbedtls_ssl_conf_rng ...\r\n");
        mbedtls_ssl_conf_rng(&_ssl_conf, mbedtls_ctr_drbg_random, &_ctr_drbg);

        /* It is possible to disable authentication by passing
         * MBEDTLS_SSL_VERIFY_NONE in the call to mbedtls_ssl_conf_authmode()
         */
        printf("mbedtls_ssl_conf_authmode ...\r\n");         
        mbedtls_ssl_conf_authmode(&_ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED);

#if DEBUG_LEVEL > 0
        mbedtls_ssl_conf_verify(&_ssl_conf, my_verify, NULL);
        mbedtls_ssl_conf_dbg(&_ssl_conf, my_debug, NULL);
        mbedtls_debug_set_threshold(DEBUG_LEVEL);
#endif

        printf("mbedtls_ssl_setup ...\r\n");         
        if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) {
            print_mbedtls_error("mbedtls_ssl_setup", ret);
            _error = ret;
            return -1;
        }
        
        
        return ret;        
    }
 
    int read(unsigned char* buffer, int len, int timeout) 
    {
        int ret;
        printf("MQTTS client read ...\r\n");

        printf("read set timeout ... %d\r\n", timeout);
        tcpsocket->set_timeout(timeout);
        
        ret = mbedtls_ssl_read(&_ssl, buffer, len);
        printf("mbedtls_ssl_read returned %d\r\n", ret);
        if (ret < 0) {
            if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) 
            {
                // Some other error we can not recover from
                print_mbedtls_error("mbedtls_ssl_read", ret);
                onError(tcpsocket, -1 );
            }
            else {
                // timeout occurred ...
                printf("Timed out? ...\r\n");
                _error = ret;
            }
            printf("MQTTS client read returns with error!!!...\r\n");
            return -1;
        }
        printf("MQTS client read successfully!! ...\r\n");
        return ret ;
    }
 
    int write(unsigned char* buffer, int len, int timeout) 
    {
        int ret;
        
        printf("MQTTS client write ...\r\n");
        tcpsocket->set_timeout(timeout);
        
        ret =  mbedtls_ssl_write(&_ssl, (const unsigned char *) buffer, len);
        if (ret < 0) {
            if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
                print_mbedtls_error("mbedtls_ssl_write", ret);
                onError(tcpsocket, -1 );
            }
            else {
                _error = ret;
            }
            return -1;
        }
        
        return ret;        
    }
 
    int connect(const char* host, int port) 
    {
        // Do the TLS handshake here ...
        /* Initialize the flags */
        /*
         * Initialize TLS-related stuf.
         */
        int ret;
        
        // Save the hostname and port on first connect
        // Create the socket 
        if (tcpsocket == NULL)
            tcpsocket = new TCPSocket(network);
            
        if (tcpsocket == NULL)
            ret = -1;
           

        printf("mbedtls_ssl_set_hostname ...\r\n");         
        mbedtls_ssl_set_hostname(&_ssl, host);
        printf("mbedtls_ssl_set_bio ...\r\n");         
        mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(tcpsocket),
                                   ssl_send, ssl_recv, NULL );

        printf("Connecting to %s:%d\r\n", host, port);
        ret = tcpsocket->connect(host, port);
        if (ret != NSAPI_ERROR_OK) {
            if (_debug) mbedtls_printf("Failed to connect\r\n");
            onError(tcpsocket, -1);
            return -1;
        }

        /* Start the handshake, the rest will be done in onReceive() */
        printf("Starting the TLS handshake...\r\n");
        ret = mbedtls_ssl_handshake(&_ssl);
        if (ret < 0) {
            if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
                ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
                print_mbedtls_error("mbedtls_ssl_handshake", ret);
                onError(tcpsocket, -1);
            }
            else {
                _error = ret;
            }
            return -1;
        }

        /* Handshake done, time to print info */
        printf("TLS connection to %s:%d established\r\n", 
            host, port);

        const uint32_t buf_size = 1024;
        char *buf = new char[buf_size];
        mbedtls_x509_crt_info(buf, buf_size, "\r    ",
                        mbedtls_ssl_get_peer_cert(&_ssl));
        printf("Server certificate:\r\n%s\r", buf);

        uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl);
        if( flags != 0 )
        {
            mbedtls_x509_crt_verify_info(buf, buf_size, "\r  ! ", flags);
            printf("Certificate verification failed:\r\n%s\r\r\n", buf);
            return -1;
        }
        
        printf("Certificate verification passed\r\n\r\n");
        
        // TODO: Save the session here for reconnect.
        if( ( ret = mbedtls_ssl_get_session( &_ssl, &saved_session ) ) != 0 )
        {
            printf( "mbedtls_ssl_get_session returned -0x%x\n\n", -ret );
            return -1;
        }  
        printf("Session saved for reconnect ...\r\n"); 
        
        // Set socket to non-blocking mode ...

        return 0;
    }
 
    void disconnect() 
    {
        if (tcpsocket)
        {
            tcpsocket->close();
            delete tcpsocket;
            tcpsocket = NULL;
        }
    }
    
protected:
    /**
     * Helper for pretty-printing mbed TLS error codes
     */
    static void print_mbedtls_error(const char *name, int err) {
        char buf[128];
        mbedtls_strerror(err, buf, sizeof (buf));
        mbedtls_printf("%s() failed: -0x%04x (%d): %s\r\n", name, -err, err, buf);
    }

#if DEBUG_LEVEL > 0
    /**
     * Debug callback for mbed TLS
     * Just prints on the USB serial port
     */
    static void my_debug(void *ctx, int level, const char *file, int line,
                         const char *str)
    {
        const char *p, *basename;
        (void) ctx;

        /* Extract basename from file */
        for(p = basename = file; *p != '\0'; p++) {
            if(*p == '/' || *p == '\\') {
                basename = p + 1;
            }
        }

        if (_debug) {
            mbedtls_printf("%s:%04d: |%d| %s", basename, line, level, str);
        }
    }

    /**
     * Certificate verification callback for mbed TLS
     * Here we only use it to display information on each cert in the chain
     */
    static int my_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
    {
        const uint32_t buf_size = 1024;
        char *buf = new char[buf_size];
        (void) data;

        if (_debug) mbedtls_printf("\nVerifying certificate at depth %d:\n", depth);
        mbedtls_x509_crt_info(buf, buf_size - 1, "  ", crt);
        if (_debug) mbedtls_printf("%s", buf);

        if (*flags == 0)
            if (_debug) mbedtls_printf("No verification issue for this certificate\n");
        else
        {
            mbedtls_x509_crt_verify_info(buf, buf_size, "  ! ", *flags);
            if (_debug) mbedtls_printf("%s\n", buf);
        }

        delete[] buf;
        return 0;
    }
#endif

    /**
     * Receive callback for mbed TLS
     */
    static int ssl_recv(void *ctx, unsigned char *buf, size_t len) {
        int recv = -1;
        TCPSocket *socket = static_cast<TCPSocket *>(ctx);
        recv = socket->recv(buf, len);

        if (NSAPI_ERROR_WOULD_BLOCK == recv) {
            return MBEDTLS_ERR_SSL_WANT_READ;
        }
        else if (recv < 0) {
            return -1;
        }
        else {
            return recv;
        }
   }
   
    /**
     * Send callback for mbed TLS
     */
    static int ssl_send(void *ctx, const unsigned char *buf, size_t len) {
       int sent = -1;
        TCPSocket *socket = static_cast<TCPSocket *>(ctx);
        sent = socket->send(buf, len);

        if(NSAPI_ERROR_WOULD_BLOCK == sent) {
            return MBEDTLS_ERR_SSL_WANT_WRITE;
        }
        else if (sent < 0){
            return -1;
        }
        else {
            return sent;
        }
    }

    void onError(TCPSocket *s, int error) {
        s->close();
        _error = error;
    }
 
private:
    NetworkInterface * network;
    TCPSocket* tcpsocket;
    const char * ssl_ca_pem;
    bool _debug;
    nsapi_error_t _error;
    const char *DRBG_PERS;
    int keepalive;
    mbedtls_entropy_context _entropy;
    mbedtls_ctr_drbg_context _ctr_drbg;
    mbedtls_x509_crt _cacert;
    mbedtls_ssl_context _ssl;
    mbedtls_ssl_config _ssl_conf;    
    mbedtls_ssl_session saved_session;

};
 
#endif // _MQTTNETWORK_H_