blob: b499b608e61e40bb9a853ce393320c07a692e4b8 [file] [log] [blame]
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +02001/*
2 * Hello world example of a TLS client: fetch an HTTPS page
3 *
4 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5 *
6 * This file is part of mbed TLS (https://tls.mbed.org)
7 */
8
9#if !defined(TARGET_LIKE_MBED)
10
11#include <stdio.h>
12
13int main() {
14 printf("this program only works on mbed OS\n");
15 return 0;
16}
17
18#else
19
20/** \file main.cpp
21 * \brief An example TLS Client application
22 * This application sends an HTTPS request to developer.mbed.org and searches for a string in
23 * the result.
24 *
25 * This example is implemented as a logic class (HelloHTTPS) wrapping a TCP socket.
26 * The logic class handles all events, leaving the main loop to just check if the process
27 * has finished.
28 */
29
30/* Change to a number between 1 and 4 to debug the TLS connection */
31#define DEBUG_LEVEL 0
32
33/* Change to 1 to skip certificate verification (UNSAFE, for debug only!) */
34#define UNSAFE 0
35
36#include "mbed.h"
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +020037#include "mbed-net-lwip-eth/EthernetInterface.h"
38#include "mbed-net-sockets/TCPStream.h"
39#include "minar/minar.h"
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +020040
41#include "mbedtls/ssl.h"
42#include "mbedtls/entropy.h"
43#include "mbedtls/ctr_drbg.h"
44#include "mbedtls/error.h"
45#if DEBUG_LEVEL > 0
46#include "mbedtls/debug.h"
47#endif
48
49#include "lwipv4_init.h"
50
51namespace {
52const char *HTTPS_SERVER_NAME = "developer.mbed.org";
53const int HTTPS_SERVER_PORT = 443;
54const int RECV_BUFFER_SIZE = 600;
55
56const char HTTPS_PATH[] = "/media/uploads/mbed_official/hello.txt";
57const size_t HTTPS_PATH_LEN = sizeof(HTTPS_PATH) - 1;
58
59/* Test related data */
60const char *HTTPS_OK_STR = "200 OK";
61const char *HTTPS_HELLO_STR = "Hello world!";
62
63/* personalization string for the drbg */
64const char *DRBG_PERS = "mbed TLS helloword client";
65
66/* List of trusted root CA certificates
67 * currently just Verisign since it's the root used by developer.mbed.org
68 * If you want to trust more that one root, just concatenate them.
69 */
70const char SSL_CA_PEM[] =
71"-----BEGIN CERTIFICATE-----\n"
72"MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\n"
73"A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\n"
74"b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\n"
75"MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\n"
76"YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\n"
77"aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\n"
78"jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\n"
79"xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\n"
80"1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\n"
81"snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\n"
82"U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\n"
83"9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\n"
84"BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\n"
85"AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\n"
86"yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\n"
87"38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\n"
88"AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\n"
89"DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\n"
90"HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
91"-----END CERTIFICATE-----\n";
92}
93
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +020094using namespace mbed::Sockets::v0;
95
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +020096/**
97 * \brief HelloHTTPS implements the logic for fetching a file from a webserver
98 * using a TCP socket and parsing the result.
99 */
100class HelloHTTPS {
101public:
102 /**
103 * HelloHTTPS Constructor
104 * Initializes the TCP socket, sets up event handlers and flags.
105 *
106 * Note that CThunk is used for event handlers. This will be changed to a C++
107 * function pointer in an upcoming release.
108 *
109 *
110 * @param[in] domain The domain name to fetch from
111 * @param[in] port The port of the HTTPS server
112 */
113 HelloHTTPS(const char * domain, const uint16_t port) :
114 _stream(SOCKET_STACK_LWIP_IPV4), _domain(domain), _port(port)
115 {
116
117 _error = false;
118 _gothello = false;
119 _got200 = false;
120 _bpos = 0;
121 _request_sent = 0;
122 _stream.open(SOCKET_AF_INET4);
123
124 mbedtls_entropy_init(&_entropy);
125 mbedtls_ctr_drbg_init(&_ctr_drbg);
126 mbedtls_x509_crt_init(&_cacert);
127 mbedtls_ssl_init(&_ssl);
128 mbedtls_ssl_config_init(&_ssl_conf);
129 }
130 /**
131 * Initiate the test.
132 *
133 * Starts by clearing test flags, then resolves the address with DNS.
134 *
135 * @param[in] path The path of the file to fetch from the HTTPS server
136 * @return SOCKET_ERROR_NONE on success, or an error code on failure
137 */
138 socket_error_t startTest(const char *path) {
139 /* Initialize the flags */
140 _got200 = false;
141 _gothello = false;
142 _error = false;
143 _disconnected = false;
144 _request_sent = false;
145 /* Fill the request buffer */
146 _bpos = snprintf(_buffer, sizeof(_buffer) - 1, "GET %s HTTP/1.1\nHost: %s\n\n", path, HTTPS_SERVER_NAME);
147
148 /*
149 * Initialize TLS-related stuf.
150 */
151 int ret;
152 if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy,
153 (const unsigned char *) DRBG_PERS,
154 sizeof (DRBG_PERS))) != 0) {
155 print_mbedtls_error("mbedtls_crt_drbg_init", ret);
156 return SOCKET_ERROR_UNKNOWN;
157 }
158
159 if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *) SSL_CA_PEM,
160 sizeof (SSL_CA_PEM))) != 0) {
161 print_mbedtls_error("mbedtls_x509_crt_parse", ret);
162 return SOCKET_ERROR_UNKNOWN;
163 }
164
165 if ((ret = mbedtls_ssl_config_defaults(&_ssl_conf,
166 MBEDTLS_SSL_IS_CLIENT,
167 MBEDTLS_SSL_TRANSPORT_STREAM,
168 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
169 print_mbedtls_error("mbedtls_ssl_config_defaults", ret);
170 return SOCKET_ERROR_UNKNOWN;
171 }
172
173 mbedtls_ssl_conf_ca_chain(&_ssl_conf, &_cacert, NULL);
174 mbedtls_ssl_conf_rng(&_ssl_conf, mbedtls_ctr_drbg_random, &_ctr_drbg);
175
176#if UNSAFE
177 mbedtls_ssl_conf_authmode(&_ssl_conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
178#endif
179
180#if DEBUG_LEVEL > 0
181 mbedtls_ssl_conf_verify(&_ssl_conf, my_verify, NULL);
182 mbedtls_ssl_conf_dbg(&_ssl_conf, my_debug, NULL);
183 mbedtls_debug_set_threshold(DEBUG_LEVEL);
184#endif
185
186 if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) {
187 print_mbedtls_error("mbedtls_ssl_setup", ret);
188 return SOCKET_ERROR_UNKNOWN;
189 }
190
191 mbedtls_ssl_set_hostname(&_ssl, HTTPS_SERVER_NAME);
192
193 mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(&_stream),
194 ssl_send, ssl_recv, NULL );
195
196
197 /* Connect to the server */
198 printf("Connecting to %s:%d\r\n", _domain, _port);
199 /* Resolve the domain name: */
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200200 socket_error_t err = _stream.resolve(_domain, TCPStream::DNSHandler_t(this, &HelloHTTPS::onDNS));
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200201 return err;
202 }
203 /**
204 * Check if the test has completed.
205 * @return Returns true if done, false otherwise.
206 */
207 bool done() {
208 return _error || (_got200 && _gothello);
209 }
210 /**
211 * Check if there was an error
212 * @return Returns true if there was an error, false otherwise.
213 */
214 bool error() {
215 return _error;
216 }
217 /**
218 * Closes the TCP socket
219 */
220 void close() {
221 _stream.close();
222 while (!_disconnected)
223 __WFI();
224 }
225protected:
226 /**
227 * Helper for pretty-printing mbed TLS error codes
228 */
229 static void print_mbedtls_error(const char *name, int err) {
230 char buf[128];
231 mbedtls_strerror(err, buf, sizeof (buf));
232 printf("%s() failed: -0x%04x (%d): %s\r\n", name, -err, err, buf);
233 }
234
235#if DEBUG_LEVEL > 0
236 /**
237 * Debug callback for mbed TLS
238 * Just prints on the USB serial port
239 */
240 static void my_debug(void *ctx, int level, const char *str)
241 {
242 (void) ctx;
243 (void) level;
244
245 printf("%s", str);
246 }
247
248 /**
249 * Certificate verification callback for mbed TLS
250 * Here we only use it to display information on each cert in the chain
251 */
252 static int my_verify(void *data, mbedtls_x509_crt *crt, int depth, int *flags)
253 {
254 char buf[1024];
255 (void) data;
256
257 printf("\nVerifying certificate at depth %d:\n", depth);
258 mbedtls_x509_crt_info(buf, sizeof (buf) - 1, " ", crt);
259 printf("%s", buf);
260
261 if (*flags == 0)
262 printf("No verification issue for this certificate\n");
263 else
264 {
265 mbedtls_x509_crt_verify_info(buf, sizeof (buf), " ! ", *flags);
266 printf("%s\n", buf);
267 }
268
269 return 0;
270 }
271#endif
272
273 /**
274 * Receive callback for mbed TLS
275 */
276 static int ssl_recv(void *ctx, unsigned char *buf, size_t len) {
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200277 TCPStream *stream = static_cast<TCPStream *>(ctx);
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200278 socket_error_t err = stream->recv(buf, &len);
279
280 if (err == SOCKET_ERROR_NONE) {
281 return static_cast<int>(len);
282 } else if (err == SOCKET_ERROR_WOULD_BLOCK) {
283 return MBEDTLS_ERR_SSL_WANT_READ;
284 } else {
285 return -1;
286 }
287 }
288
289 /**
290 * Send callback for mbed TLS
291 */
292 static int ssl_send(void *ctx, const unsigned char *buf, size_t len) {
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200293 TCPStream *stream = static_cast<TCPStream *>(ctx);
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200294
295 socket_error_t err = stream->send(buf, len);
296
297 if (err == SOCKET_ERROR_NONE) {
298 return static_cast<int>(len);
299 } else if (err == SOCKET_ERROR_WOULD_BLOCK) {
300 return MBEDTLS_ERR_SSL_WANT_WRITE;
301 } else {
302 return -1;
303 }
304 }
305
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200306 void onError(Socket *s, socket_error_t err) {
307 (void) s;
308 printf("MBED: Socket Error: %s (%d)\r\n", socket_strerror(err), err);
309 _stream.close();
310 _error = true;
311 minar::Scheduler::stop();
312 }
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200313 /**
314 * On Connect handler
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200315 * Starts the TLS handshake
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200316 */
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200317 void onConnect(TCPStream *s) {
318 s->setOnReadable(TCPStream::ReadableHandler_t(this, &HelloHTTPS::onReceive));
319 s->setOnDisconnect(TCPStream::DisconnectHandler_t(this, &HelloHTTPS::onDisconnect));
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200320
321 /* Start the handshake, the rest will be done in onReceive() */
322 int ret = mbedtls_ssl_handshake(&_ssl);
323 if (ret < 0) {
324 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
325 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
326 print_mbedtls_error("mbedtls_ssl_handshake", ret);
327 _error = true;
328 }
329 return;
330 }
331 }
332 /**
333 * On Receive handler
334 * Parses the response from the server, to check for the HTTPS 200 status code and the expected response ("Hello World!")
335 */
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200336 void onReceive(Socket *s) {
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200337 if (_error)
338 return;
339
340 /* Send request if not done yet */
341 if (!_request_sent) {
342 int ret = mbedtls_ssl_write(&_ssl, (const unsigned char *) _buffer, _bpos);
343 if (ret < 0) {
344 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
345 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
346 print_mbedtls_error("mbedtls_ssl_write", ret);
347 _error = true;
348 }
349 return;
350 }
351
352 /* If we get here, the request was sent */
353 _request_sent = 1;
354
355 /* It also means the handshake is done, time to print info */
356 printf("TLS connection to %s established\r\n", HTTPS_SERVER_NAME);
357 {
358 char buf[1024];
359 mbedtls_x509_crt_info(buf, sizeof(buf), "\r ",
360 mbedtls_ssl_get_peer_cert(&_ssl));
361 printf("Server certificate:\r\n%s\r", buf);
362
363#if defined(UNSAFE)
364 uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl);
365 if( flags != 0 )
366 {
367 mbedtls_x509_crt_verify_info(buf, sizeof (buf), "\r ! ", flags);
368 printf("Certificate verification failed:\r\n%s\r\r\n", buf);
369 }
370 else
371#endif
372 printf("Certificate verification passed\r\n\r\n");
373 }
374 }
375
376 /* Read data out of the socket */
377 int ret = mbedtls_ssl_read(&_ssl, (unsigned char *) _buffer, sizeof(_buffer));
378 if (ret < 0) {
379 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
380 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
381 print_mbedtls_error("mbedtls_ssl_read", ret);
382 _error = true;
383 }
384 return;
385 }
386 _bpos = static_cast<size_t>(ret);
387
388 _buffer[_bpos] = 0;
389
390 /* Check each of the flags */
391 _got200 = _got200 || strstr(_buffer, HTTPS_OK_STR) != NULL;
392 _gothello = _gothello || strstr(_buffer, HTTPS_HELLO_STR) != NULL;
393
394 /* Print status messages */
395 printf("HTTPS: Received %d chars from server\r\n", _bpos);
396 printf("HTTPS: Received 200 OK status ... %s\r\n", _got200 ? "[OK]" : "[FAIL]");
397 printf("HTTPS: Received '%s' status ... %s\r\n", HTTPS_HELLO_STR, _gothello ? "[OK]" : "[FAIL]");
398 printf("HTTPS: Received message:\r\n\r\n");
399 printf("%s", _buffer);
400 _error = !(_got200 && _gothello);
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200401
402 s->close();
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200403 }
404 /**
405 * On DNS Handler
406 * Reads the address returned by DNS, then starts the connect process.
407 */
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200408 void onDNS(Socket *s, struct socket_addr addr, const char *domain) {
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200409 /* Check that the result is a valid DNS response */
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200410 if (socket_addr_is_any(&addr)) {
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200411 /* Could not find DNS entry */
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200412 printf("Could not find DNS entry for %s", HTTPS_SERVER_NAME);
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200413 onError(s, SOCKET_ERROR_DNS_FAILED);
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200414 } else {
415 /* Start connecting to the remote host */
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200416 char buf[16];
417 _remoteAddr.setAddr(&addr);
418 _remoteAddr.fmtIPv4(buf,sizeof(buf));
419 printf("%s address: %s\r\n",domain, buf);
420 socket_error_t err = _stream.connect(_remoteAddr, _port, TCPStream::ConnectHandler_t(this, &HelloHTTPS::onConnect));
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200421
422 if (err != SOCKET_ERROR_NONE) {
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200423 onError(s, err);
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200424 }
425 }
426 }
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200427 void onDisconnect(TCPStream *s) {
428 s->close();
429 minar::Scheduler::stop();
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200430 }
431
432protected:
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200433 TCPStream _stream; /**< The TCP Socket */
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200434 const char *_domain; /**< The domain name of the HTTPS server */
435 const uint16_t _port; /**< The HTTPS server port */
436 char _buffer[RECV_BUFFER_SIZE]; /**< The response buffer */
437 size_t _bpos; /**< The current offset in the response buffer */
Manuel Pégourié-Gonnardae5398a2015-08-04 14:10:28 +0200438 SocketAddr _remoteAddr; /**< The remote address */
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200439 volatile bool _got200; /**< Status flag for HTTPS 200 */
440 volatile bool _gothello; /**< Status flag for finding the test string */
441 volatile bool _error; /**< Status flag for an error */
442 volatile bool _disconnected;
443 volatile bool _request_sent;
444
445 mbedtls_entropy_context _entropy;
446 mbedtls_ctr_drbg_context _ctr_drbg;
447 mbedtls_x509_crt _cacert;
448 mbedtls_ssl_context _ssl;
449 mbedtls_ssl_config _ssl_conf;
450};
451
452/**
453 * The main loop of the HTTPS Hello World test
454 */
455int example_client() {
456 EthernetInterface eth;
457 /* Initialise with DHCP, connect, and start up the stack */
458 eth.init();
459 eth.connect();
460 lwipv4_socket_init();
461
462 printf("\r\n\r\n");
463 printf("Client IP Address is %s\r\n", eth.getIPAddress());
464
465 HelloHTTPS hello(HTTPS_SERVER_NAME, HTTPS_SERVER_PORT);
466 socket_error_t rc = hello.startTest(HTTPS_PATH);
467 if (rc != SOCKET_ERROR_NONE) {
468 return 1;
469 }
470 while (!hello.done()) {
471 __WFI();
472 }
473 if (hello.error()) {
474 printf("Failed to fetch %s from %s:%d\r\n", HTTPS_PATH, HTTPS_SERVER_NAME, HTTPS_SERVER_PORT);
475 }
476 /* Shut down the socket before the ethernet interface */
477 hello.close();
478 eth.disconnect();
479 return static_cast<int>(hello.error());
480}
481
482#include "mbed/test_env.h"
483
484int main() {
485 /* The default 9600 bps is too slow to print full TLS debug info and could
486 * cause the other party to time out. Select a higher baud rate for
487 * printf(), regardless of debug level for the sake of uniformity. */
488 Serial pc(USBTX, USBRX);
489 pc.baud(115200);
490
491 MBED_HOSTTEST_TIMEOUT(120);
492 MBED_HOSTTEST_SELECT(default);
493 MBED_HOSTTEST_DESCRIPTION(mbed TLS example HTTPS client);
494 MBED_HOSTTEST_START("MBEDTLS_EX_HTTPS_CLIENT");
495 MBED_HOSTTEST_RESULT(example_client() == 0);
496}
497
498#endif /* TARGET_LIKE_MBED */