![](/media/cache/group/Mbed-100-mk2.png.50x50_q85.png)
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!
HelloHttpsClient.h
- Committer:
- mbed_official
- Date:
- 2018-05-10
- Revision:
- 69:ffefb2e2d149
- Parent:
- 66:ce8709d9912c
- Child:
- 76:b8c07be20122
File content as of revision 69:ffefb2e2d149:
/* * Hello world example of a TLS client: fetch an HTTPS page * * Copyright (C) 2006-2018, Arm Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef _HELLOHTTPSCLIENT_H_ #define _HELLOHTTPSCLIENT_H_ #include "TCPSocket.h" #include "mbedtls/config.h" #include "mbedtls/platform.h" #include "mbedtls/ssl.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/error.h" #include "mbedtls/debug.h" #include <stdint.h> /** * Change to a number between 1 and 4 to debug the TLS connection */ #define HELLO_HTTPS_CLIENT_DEBUG_LEVEL 0 /** * Length (in bytes) for generic buffers used to hold debug or HTTP * request/response strings */ #define GENERAL_PURPOSE_BUFFER_LENGTH 1024 /** * This class implements the logic for fetching a file from a webserver using * a TCP socket and parsing the result. */ class HelloHttpsClient { public: /** * Construct an HelloHttpsClient instance * * \param[in] in_server_name * The server domain/IP address * \param[in] in_server_port * The server port */ HelloHttpsClient(const char *in_server_name, const uint16_t in_server_port, mbedtls_platform_context* in_platform_ctx); /** * Free any allocated resources */ ~HelloHttpsClient(); /** * Start the connection to the server and request to read the file at * HTTP_REQUEST_FILE_PATH * * \return 0 if successful */ int run(); private: /** * Create a TCPSocket object that can be used to communicate with the server */ int configureTCPSocket(); /** * Configure the Mbed TLS structures required to establish a TLS connection * with the server */ int configureTlsContexts(); /** * Wrapper function around TCPSocket that gets called by Mbed TLS whenever * we call mbedtls_ssl_read() * * \param[in] ctx * The TCPSocket object * \param[in] buf * Buffer where data received will be stored * \param[in] len * The length (in bytes) of the buffer * * \return If successful, the number of bytes received, a negative value * otherwise. */ static int sslRecv(void *ctx, unsigned char *buf, size_t len); /** * Wrapper function around TCPSocket that gets called by Mbed TLS whenever * we call mbedtls_ssl_write() * * \param[in] ctx * The TCPSocket object * \param[in] buf * Buffer containing the data to be sent * \param[in] len * The number of bytes to send * * \return If successful, the number of bytes sent, a negative value * otherwise */ static int sslSend(void *ctx, const unsigned char *buf, size_t len); /** * Callback to handle debug prints to serial * * \param[in] ctx * The context (unused in this case) * \param[in] level * The current debug level * \param[in] file * The C file that is logging this message * \param[in] line * The line number in the file * \param[in] str * The string to log to serial */ static void sslDebug(void *ctx, int level, const char *file, int line, const char *str); /** * Callback to handle certificate verification * * /param[in] data * (unused) * /param[in] crt * The crt in the chain that we are verifying * /param[in] depth * The depth of the current certificate in the chain * /param[in/out] flags * The flags resulting from the verification * * /return 0 if successful */ static int sslVerify(void *ctx, mbedtls_x509_crt *crt, int depth, uint32_t *flags); private: /** * Personalization string for the drbg */ static const char *DRBG_PERSONALIZED_STR; /** * Length of error string buffer for logging failures related to Mbed TLS */ static const size_t ERROR_LOG_BUFFER_LENGTH; /** * Chain of trusted CAs in PEM format */ static const char *TLS_PEM_CA; /** * Path to the file that will be requested from the server */ static const char *HTTP_REQUEST_FILE_PATH; /** * Expected strings in the HTTP response from the server */ static const char *HTTP_OK_STR; /** * Expected strings in the HTTP response from the server */ static const char *HTTP_HELLO_STR; /** * Instance of TCPSocket used to communicate with the server */ TCPSocket socket; /** * The domain/IP address of the server to contact */ const char *server_name; /** * The port number to use in the connection */ const uint16_t server_port; /** * A generic buffer used to hold debug or HTTP request/response strings */ char gp_buf[GENERAL_PURPOSE_BUFFER_LENGTH]; /** * Entropy context used to seed the DRBG to use in the TLS connection */ mbedtls_entropy_context entropy; /** * The DRBG used throughout the TLS connection */ mbedtls_ctr_drbg_context ctr_drbg; /** * The parsed chain of trusted CAs */ mbedtls_x509_crt cacert; /** * THe TLS context */ mbedtls_ssl_context ssl; /** * The TLS configuration in use */ mbedtls_ssl_config ssl_conf; mbedtls_platform_context* platform_ctx; }; #endif /* _HELLOHTTPSCLIENT_H_ */