Hello world example of a TLS client: fetch an HTTPS page. The canonical source for this example lives at https://github.com/ARMmbed/mbed-os-example-tls

HTTPS File Download Example for TLS Client on mbed OS

This application downloads a file from an HTTPS server (developer.mbed.org) and looks for a specific string in that file.

Getting started

Building with mbed CLI

If you'd like to use mbed CLI to build this, then you should set up your environment if you have not done so already. For instructions, refer to the main readme. The instructions here relate to using the developer.mbed.org Online Compiler

Import the program in to the Online Compiler, select your board from the drop down in the top right hand corner and then compile the application. Once it has built, you can drag and drop the binary onto your device.

Required hardware

This example also requires an Ethernet cable an connection to the internet additional to the hardware requirements in the main readme.

Monitoring the application

NOTE: Make sure that the Ethernet cable is plugged in correctly before running the application.

The output in the terminal window should be similar to this:

terminal output

Using Ethernet LWIP
Client IP Address is 10.2.203.43
Connecting with developer.mbed.org
Starting the TLS handshake...
TLS connection to developer.mbed.org established
Server certificate:
    cert. version     : 3
    serial number     : 11:21:B8:47:9B:21:6C:B1:C6:AF:BC:5D:0C:19:52:DC:D7:C3
    issuer name       : C=BE, O=GlobalSign nv-sa, CN=GlobalSign Organization Validation CA - SHA256 - G2
    subject name      : C=GB, ST=Cambridgeshire, L=Cambridge, O=ARM Ltd, CN=*.mbed.com
    issued  on        : 2016-03-03 12:26:08
    expires on        : 2017-04-05 10:31:02
    signed using      : RSA with SHA-256
    RSA key size      : 2048 bits
    basic constraints : CA=false
    subject alt name  : *.mbed.com, mbed.org, *.mbed.org, mbed.com
    key usage         : Digital Signature, Key Encipherment
    ext key usage     : TLS Web Server Authentication, TLS Web Client Authentication
Certificate verification passed

HTTPS: Received 439 chars from server
HTTPS: Received 200 OK status ... [OK]
HTTPS: Received 'Hello world!' status ... [OK]
HTTPS: Received message:

HTTP/1.1 200 OK
Server: nginx/1.7.10
Date: Wed, 20 Jul 2016 10:00:35 GMT
Content-Type: text/plain
Content-Length: 14
Connection: keep-alive
Last-Modified: Fri, 27 Jul 2012 13:30:34 GMT
Accept-Ranges: bytes
Cache-Control: max-age=36000
Expires: Wed, 20 Jul 2016 20:00:35 GMT
X-Upstream-L3: 172.17.0.3:80
X-Upstream-L2: developer-sjc-indigo-1-nginx
Strict-Transport-Security: max-age=31536000; includeSubdomains

Hello world!

Debugging the TLS connection

To print out more debug information about the TLS connection, edit the file `main.cpp` and change the definition of `DEBUG_LEVEL` (near the top of the file) from 0 to a positive number:

  • Level 1 only prints non-zero return codes from SSL functions and information about the full certificate chain being verified.
  • Level 2 prints more information about internal state updates.
  • Level 3 is intermediate.
  • Level 4 (the maximum) includes full binary dumps of the packets.

The TLS connection can fail with an error similar to:

error message

    mbedtls_ssl_write() failed: -0x2700 (-9984): X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
    Failed to fetch /media/uploads/mbed_official/hello.txt from developer.mbed.org:443

This probably means you need to update the contents of the SSL_CA_PEM constant (this can happen if you modify HTTPS_SERVER_NAME, or when developer.mbed.org switches to a new CA when updating its certificate).

Another possible reason for this error is a proxy providing a different certificate. Proxies can be used in some network configurations or for performing man-in-the-middle attacks. If you choose to ignore this error and proceed with the connection anyway, you can change the definition of UNSAFE near the top of the file from 0 to 1.

Warning: this removes all security against a possible active attacker, so use at your own risk or for debugging only!

Revision:
47:c84bc63913c6
Parent:
42:5236ebc3d12a
Child:
50:b6870173bcac
--- a/main.cpp	Tue Oct 24 13:30:21 2017 +0100
+++ b/main.cpp	Thu Nov 02 20:45:19 2017 +0000
@@ -33,10 +33,7 @@
 #define DEBUG_LEVEL 0
 
 #include "mbed.h"
-#include "NetworkStack.h"
-
-#include "EthernetInterface.h"
-#include "TCPSocket.h"
+#include "easy-connect.h"
 
 #include "mbedtls/platform.h"
 #include "mbedtls/ssl.h"
@@ -201,17 +198,17 @@
 
 
         /* Connect to the server */
-        mbedtls_printf("Connecting with %s\r\n", _domain);
+        mbedtls_printf("Connecting with %s\n", _domain);
         ret = _tcpsocket->connect(_domain, _port);
         if (ret != NSAPI_ERROR_OK) {
-            mbedtls_printf("Failed to connect\r\n");
-            printf("MBED: Socket Error: %d\r\n", ret);
+            mbedtls_printf("Failed to connect\n");
+            printf("MBED: Socket Error: %d\n", ret);
             _tcpsocket->close();
             return;
         }
 
        /* Start the handshake, the rest will be done in onReceive() */
-        mbedtls_printf("Starting the TLS handshake...\r\n");
+        mbedtls_printf("Starting the TLS handshake...\n");
         do {
             ret = mbedtls_ssl_handshake(&_ssl);
         } while (ret != 0 && (ret == MBEDTLS_ERR_SSL_WANT_READ ||
@@ -242,22 +239,22 @@
         }
 
         /* It also means the handshake is done, time to print info */
-        printf("TLS connection to %s established\r\n", HTTPS_SERVER_NAME);
+        printf("TLS connection to %s established\n", HTTPS_SERVER_NAME);
 
         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));
-        mbedtls_printf("Server certificate:\r\n%s\r", buf);
+        mbedtls_printf("Server certificate:\n%s", 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);
+            printf("Certificate verification failed:\n%s\n", buf);
         }
         else
-            printf("Certificate verification passed\r\n\r\n");
+            printf("Certificate verification passed\n\n");
 
 
         /* Read data out of the socket */
@@ -289,10 +286,10 @@
         _tcpsocket->close();
 
         /* Print status messages */
-        mbedtls_printf("HTTPS: Received %d chars from server\r\n", _bpos);
-        mbedtls_printf("HTTPS: Received 200 OK status ... %s\r\n", _got200 ? "[OK]" : "[FAIL]");
-        mbedtls_printf("HTTPS: Received '%s' status ... %s\r\n", HTTPS_HELLO_STR, _gothello ? "[OK]" : "[FAIL]");
-        mbedtls_printf("HTTPS: Received message:\r\n\r\n");
+        mbedtls_printf("HTTPS: Received %d chars from server\n", _bpos);
+        mbedtls_printf("HTTPS: Received 200 OK status ... %s\n", _got200 ? "[OK]" : "[FAIL]");
+        mbedtls_printf("HTTPS: Received '%s' status ... %s\n", HTTPS_HELLO_STR, _gothello ? "[OK]" : "[FAIL]");
+        mbedtls_printf("HTTPS: Received message:\n\n");
         mbedtls_printf("%s", _buffer);
 
         delete[] buf;
@@ -305,7 +302,7 @@
     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);
+        mbedtls_printf("%s() failed: -0x%04x (%d): %s\n", name, -err, err, buf);
     }
 
 #if DEBUG_LEVEL > 0
@@ -367,7 +364,7 @@
         if(NSAPI_ERROR_WOULD_BLOCK == recv){
             return MBEDTLS_ERR_SSL_WANT_READ;
         }else if(recv < 0){
-            mbedtls_printf("Socket recv error %d\r\n", recv);
+            mbedtls_printf("Socket recv error %d\n", recv);
             return -1;
         }else{
             return recv;
@@ -385,7 +382,7 @@
         if(NSAPI_ERROR_WOULD_BLOCK == size){
             return MBEDTLS_ERR_SSL_WANT_WRITE;
         }else if(size < 0){
-            mbedtls_printf("Socket send error %d\r\n", size);
+            mbedtls_printf("Socket send error %d\n", size);
             return -1;
         }else{
             return size;
@@ -418,18 +415,27 @@
     /* The default 9600 bps is too slow to print full TLS debug info and could
      * cause the other party to time out. */
 
-    /* Inititalise with DHCP, connect, and start up the stack */
-    EthernetInterface eth_iface;
-    eth_iface.connect();
-    mbedtls_printf("Using Ethernet LWIP\r\n");
-    const char *ip_addr = eth_iface.get_ip_address();
-    if (ip_addr) {
-        mbedtls_printf("Client IP Address is %s\r\n", ip_addr);
-    } else {
-        mbedtls_printf("No Client IP Address\r\n");
+    printf("\nStarting mbed-os-example-tls/tls-client\n");
+#if defined(MBED_MAJOR_VERSION)
+    printf("Using Mbed OS %d.%d.%d\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
+#else
+    printf("Using Mbed OS from master.\n");
+#endif
+
+    /* Use the easy-connect lib to support multiple network bearers.   */
+    /* See https://github.com/ARMmbed/easy-connect README.md for info. */
+
+#if DEBUG_LEVEL > 0
+    NetworkInterface* network = easy_connect(true);
+#else
+    NetworkInterface* network = easy_connect(false);
+#endif /* DEBUG_LEVEL > 0 */
+    if (NULL == network) {
+        printf("Connecting to the network failed... See serial output.\n");
+        return 1;
     }
 
-    HelloHTTPS *hello = new HelloHTTPS(HTTPS_SERVER_NAME, HTTPS_SERVER_PORT, &eth_iface);
+    HelloHTTPS *hello = new HelloHTTPS(HTTPS_SERVER_NAME, HTTPS_SERVER_PORT, network);
     hello->startTest(HTTPS_PATH);
     delete hello;
 }