blob: 970788c30951b75272e4870c1d38dc7a15db0054 [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"
37#include <mbed-net-lwip-eth/EthernetInterface.h>
38#include <mbed-net-sockets/TCPStream.h>
39
40#include "mbedtls/ssl.h"
41#include "mbedtls/entropy.h"
42#include "mbedtls/ctr_drbg.h"
43#include "mbedtls/error.h"
44#if DEBUG_LEVEL > 0
45#include "mbedtls/debug.h"
46#endif
47
48#include "lwipv4_init.h"
49
50namespace {
51const char *HTTPS_SERVER_NAME = "developer.mbed.org";
52const int HTTPS_SERVER_PORT = 443;
53const int RECV_BUFFER_SIZE = 600;
54
55const char HTTPS_PATH[] = "/media/uploads/mbed_official/hello.txt";
56const size_t HTTPS_PATH_LEN = sizeof(HTTPS_PATH) - 1;
57
58/* Test related data */
59const char *HTTPS_OK_STR = "200 OK";
60const char *HTTPS_HELLO_STR = "Hello world!";
61
62/* personalization string for the drbg */
63const char *DRBG_PERS = "mbed TLS helloword client";
64
65/* List of trusted root CA certificates
66 * currently just Verisign since it's the root used by developer.mbed.org
67 * If you want to trust more that one root, just concatenate them.
68 */
69const char SSL_CA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v04zcQLcFGUl5gE\n"
86"38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\n"
87"AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\n"
88"DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\n"
89"HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
90"-----END CERTIFICATE-----\n";
91}
92
93/**
94 * \brief HelloHTTPS implements the logic for fetching a file from a webserver
95 * using a TCP socket and parsing the result.
96 */
97class HelloHTTPS {
98public:
99 /**
100 * HelloHTTPS Constructor
101 * Initializes the TCP socket, sets up event handlers and flags.
102 *
103 * Note that CThunk is used for event handlers. This will be changed to a C++
104 * function pointer in an upcoming release.
105 *
106 *
107 * @param[in] domain The domain name to fetch from
108 * @param[in] port The port of the HTTPS server
109 */
110 HelloHTTPS(const char * domain, const uint16_t port) :
111 _stream(SOCKET_STACK_LWIP_IPV4), _domain(domain), _port(port)
112 {
113
114 _error = false;
115 _gothello = false;
116 _got200 = false;
117 _bpos = 0;
118 _request_sent = 0;
119 _stream.open(SOCKET_AF_INET4);
120
121 mbedtls_entropy_init(&_entropy);
122 mbedtls_ctr_drbg_init(&_ctr_drbg);
123 mbedtls_x509_crt_init(&_cacert);
124 mbedtls_ssl_init(&_ssl);
125 mbedtls_ssl_config_init(&_ssl_conf);
126 }
127 /**
128 * Initiate the test.
129 *
130 * Starts by clearing test flags, then resolves the address with DNS.
131 *
132 * @param[in] path The path of the file to fetch from the HTTPS server
133 * @return SOCKET_ERROR_NONE on success, or an error code on failure
134 */
135 socket_error_t startTest(const char *path) {
136 /* Initialize the flags */
137 _got200 = false;
138 _gothello = false;
139 _error = false;
140 _disconnected = false;
141 _request_sent = false;
142 /* Fill the request buffer */
143 _bpos = snprintf(_buffer, sizeof(_buffer) - 1, "GET %s HTTP/1.1\nHost: %s\n\n", path, HTTPS_SERVER_NAME);
144
145 /*
146 * Initialize TLS-related stuf.
147 */
148 int ret;
149 if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy,
150 (const unsigned char *) DRBG_PERS,
151 sizeof (DRBG_PERS))) != 0) {
152 print_mbedtls_error("mbedtls_crt_drbg_init", ret);
153 return SOCKET_ERROR_UNKNOWN;
154 }
155
156 if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *) SSL_CA_PEM,
157 sizeof (SSL_CA_PEM))) != 0) {
158 print_mbedtls_error("mbedtls_x509_crt_parse", ret);
159 return SOCKET_ERROR_UNKNOWN;
160 }
161
162 if ((ret = mbedtls_ssl_config_defaults(&_ssl_conf,
163 MBEDTLS_SSL_IS_CLIENT,
164 MBEDTLS_SSL_TRANSPORT_STREAM,
165 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
166 print_mbedtls_error("mbedtls_ssl_config_defaults", ret);
167 return SOCKET_ERROR_UNKNOWN;
168 }
169
170 mbedtls_ssl_conf_ca_chain(&_ssl_conf, &_cacert, NULL);
171 mbedtls_ssl_conf_rng(&_ssl_conf, mbedtls_ctr_drbg_random, &_ctr_drbg);
172
173#if UNSAFE
174 mbedtls_ssl_conf_authmode(&_ssl_conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
175#endif
176
177#if DEBUG_LEVEL > 0
178 mbedtls_ssl_conf_verify(&_ssl_conf, my_verify, NULL);
179 mbedtls_ssl_conf_dbg(&_ssl_conf, my_debug, NULL);
180 mbedtls_debug_set_threshold(DEBUG_LEVEL);
181#endif
182
183 if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) {
184 print_mbedtls_error("mbedtls_ssl_setup", ret);
185 return SOCKET_ERROR_UNKNOWN;
186 }
187
188 mbedtls_ssl_set_hostname(&_ssl, HTTPS_SERVER_NAME);
189
190 mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(&_stream),
191 ssl_send, ssl_recv, NULL );
192
193
194 /* Connect to the server */
195 printf("Connecting to %s:%d\r\n", _domain, _port);
196 /* Resolve the domain name: */
197 socket_error_t err = _stream.resolve(_domain, handler_t(this, &HelloHTTPS::onDNS));
198 return err;
199 }
200 /**
201 * Check if the test has completed.
202 * @return Returns true if done, false otherwise.
203 */
204 bool done() {
205 return _error || (_got200 && _gothello);
206 }
207 /**
208 * Check if there was an error
209 * @return Returns true if there was an error, false otherwise.
210 */
211 bool error() {
212 return _error;
213 }
214 /**
215 * Closes the TCP socket
216 */
217 void close() {
218 _stream.close();
219 while (!_disconnected)
220 __WFI();
221 }
222protected:
223 /**
224 * Helper for pretty-printing mbed TLS error codes
225 */
226 static void print_mbedtls_error(const char *name, int err) {
227 char buf[128];
228 mbedtls_strerror(err, buf, sizeof (buf));
229 printf("%s() failed: -0x%04x (%d): %s\r\n", name, -err, err, buf);
230 }
231
232#if DEBUG_LEVEL > 0
233 /**
234 * Debug callback for mbed TLS
235 * Just prints on the USB serial port
236 */
237 static void my_debug(void *ctx, int level, const char *str)
238 {
239 (void) ctx;
240 (void) level;
241
242 printf("%s", str);
243 }
244
245 /**
246 * Certificate verification callback for mbed TLS
247 * Here we only use it to display information on each cert in the chain
248 */
249 static int my_verify(void *data, mbedtls_x509_crt *crt, int depth, int *flags)
250 {
251 char buf[1024];
252 (void) data;
253
254 printf("\nVerifying certificate at depth %d:\n", depth);
255 mbedtls_x509_crt_info(buf, sizeof (buf) - 1, " ", crt);
256 printf("%s", buf);
257
258 if (*flags == 0)
259 printf("No verification issue for this certificate\n");
260 else
261 {
262 mbedtls_x509_crt_verify_info(buf, sizeof (buf), " ! ", *flags);
263 printf("%s\n", buf);
264 }
265
266 return 0;
267 }
268#endif
269
270 /**
271 * Receive callback for mbed TLS
272 */
273 static int ssl_recv(void *ctx, unsigned char *buf, size_t len) {
274 mbed::TCPStream *stream = static_cast<mbed::TCPStream *>(ctx);
275 socket_error_t err = stream->recv(buf, &len);
276
277 if (err == SOCKET_ERROR_NONE) {
278 return static_cast<int>(len);
279 } else if (err == SOCKET_ERROR_WOULD_BLOCK) {
280 return MBEDTLS_ERR_SSL_WANT_READ;
281 } else {
282 return -1;
283 }
284 }
285
286 /**
287 * Send callback for mbed TLS
288 */
289 static int ssl_send(void *ctx, const unsigned char *buf, size_t len) {
290 mbed::TCPStream *stream = static_cast<mbed::TCPStream *>(ctx);
291
292 socket_error_t err = stream->send(buf, len);
293
294 if (err == SOCKET_ERROR_NONE) {
295 return static_cast<int>(len);
296 } else if (err == SOCKET_ERROR_WOULD_BLOCK) {
297 return MBEDTLS_ERR_SSL_WANT_WRITE;
298 } else {
299 return -1;
300 }
301 }
302
303 /**
304 * On Connect handler
305 * Sends the request which was generated in startTest
306 */
307 void onConnect(socket_error_t err) {
308 (void) err;
309
310 _stream.setOnReadable(handler_t(this, &HelloHTTPS::onReceive));
311 _stream.setOnDisconnect(handler_t(this, &HelloHTTPS::onDisconnect));
312
313 /* Start the handshake, the rest will be done in onReceive() */
314 int ret = mbedtls_ssl_handshake(&_ssl);
315 if (ret < 0) {
316 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
317 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
318 print_mbedtls_error("mbedtls_ssl_handshake", ret);
319 _error = true;
320 }
321 return;
322 }
323 }
324 /**
325 * On Receive handler
326 * Parses the response from the server, to check for the HTTPS 200 status code and the expected response ("Hello World!")
327 */
328 void onReceive(socket_error_t err) {
329 (void) err;
330
331 if (_error)
332 return;
333
334 /* Send request if not done yet */
335 if (!_request_sent) {
336 int ret = mbedtls_ssl_write(&_ssl, (const unsigned char *) _buffer, _bpos);
337 if (ret < 0) {
338 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
339 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
340 print_mbedtls_error("mbedtls_ssl_write", ret);
341 _error = true;
342 }
343 return;
344 }
345
346 /* If we get here, the request was sent */
347 _request_sent = 1;
348
349 /* It also means the handshake is done, time to print info */
350 printf("TLS connection to %s established\r\n", HTTPS_SERVER_NAME);
351 {
352 char buf[1024];
353 mbedtls_x509_crt_info(buf, sizeof(buf), "\r ",
354 mbedtls_ssl_get_peer_cert(&_ssl));
355 printf("Server certificate:\r\n%s\r", buf);
356
357#if defined(UNSAFE)
358 uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl);
359 if( flags != 0 )
360 {
361 mbedtls_x509_crt_verify_info(buf, sizeof (buf), "\r ! ", flags);
362 printf("Certificate verification failed:\r\n%s\r\r\n", buf);
363 }
364 else
365#endif
366 printf("Certificate verification passed\r\n\r\n");
367 }
368 }
369
370 /* Read data out of the socket */
371 int ret = mbedtls_ssl_read(&_ssl, (unsigned char *) _buffer, sizeof(_buffer));
372 if (ret < 0) {
373 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
374 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
375 print_mbedtls_error("mbedtls_ssl_read", ret);
376 _error = true;
377 }
378 return;
379 }
380 _bpos = static_cast<size_t>(ret);
381
382 _buffer[_bpos] = 0;
383
384 /* Check each of the flags */
385 _got200 = _got200 || strstr(_buffer, HTTPS_OK_STR) != NULL;
386 _gothello = _gothello || strstr(_buffer, HTTPS_HELLO_STR) != NULL;
387
388 /* Print status messages */
389 printf("HTTPS: Received %d chars from server\r\n", _bpos);
390 printf("HTTPS: Received 200 OK status ... %s\r\n", _got200 ? "[OK]" : "[FAIL]");
391 printf("HTTPS: Received '%s' status ... %s\r\n", HTTPS_HELLO_STR, _gothello ? "[OK]" : "[FAIL]");
392 printf("HTTPS: Received message:\r\n\r\n");
393 printf("%s", _buffer);
394 _error = !(_got200 && _gothello);
395 }
396 /**
397 * On DNS Handler
398 * Reads the address returned by DNS, then starts the connect process.
399 */
400 void onDNS(socket_error_t err) {
401 socket_event_t *e = _stream.getEvent();
402 /* Check that the result is a valid DNS response */
403 if (socket_addr_is_any(&e->i.d.addr)) {
404 /* Could not find DNS entry */
405 _error = true;
406 printf("Could not find DNS entry for %s", HTTPS_SERVER_NAME);
407 return;
408 } else {
409 /* Start connecting to the remote host */
410 _remoteAddr.setAddr(&e->i.d.addr);
411 err = _stream.connect(&_remoteAddr, _port, handler_t(this, &HelloHTTPS::onConnect));
412
413 if (err != SOCKET_ERROR_NONE) {
414 _error = true;
415 }
416 }
417 }
418 void onDisconnect(socket_error_t err) {
419 (void) err;
420 _disconnected = true;
421 }
422
423protected:
424 mbed::TCPStream _stream; /**< The TCP Socket */
425 const char *_domain; /**< The domain name of the HTTPS server */
426 const uint16_t _port; /**< The HTTPS server port */
427 char _buffer[RECV_BUFFER_SIZE]; /**< The response buffer */
428 size_t _bpos; /**< The current offset in the response buffer */
429 mbed::SocketAddr _remoteAddr; /**< The remote address */
430 volatile bool _got200; /**< Status flag for HTTPS 200 */
431 volatile bool _gothello; /**< Status flag for finding the test string */
432 volatile bool _error; /**< Status flag for an error */
433 volatile bool _disconnected;
434 volatile bool _request_sent;
435
436 mbedtls_entropy_context _entropy;
437 mbedtls_ctr_drbg_context _ctr_drbg;
438 mbedtls_x509_crt _cacert;
439 mbedtls_ssl_context _ssl;
440 mbedtls_ssl_config _ssl_conf;
441};
442
443/**
444 * The main loop of the HTTPS Hello World test
445 */
446int example_client() {
447 EthernetInterface eth;
448 /* Initialise with DHCP, connect, and start up the stack */
449 eth.init();
450 eth.connect();
451 lwipv4_socket_init();
452
453 printf("\r\n\r\n");
454 printf("Client IP Address is %s\r\n", eth.getIPAddress());
455
456 HelloHTTPS hello(HTTPS_SERVER_NAME, HTTPS_SERVER_PORT);
457 socket_error_t rc = hello.startTest(HTTPS_PATH);
458 if (rc != SOCKET_ERROR_NONE) {
459 return 1;
460 }
461 while (!hello.done()) {
462 __WFI();
463 }
464 if (hello.error()) {
465 printf("Failed to fetch %s from %s:%d\r\n", HTTPS_PATH, HTTPS_SERVER_NAME, HTTPS_SERVER_PORT);
466 }
467 /* Shut down the socket before the ethernet interface */
468 hello.close();
469 eth.disconnect();
470 return static_cast<int>(hello.error());
471}
472
473#include "mbed/test_env.h"
474
475int main() {
476 /* The default 9600 bps is too slow to print full TLS debug info and could
477 * cause the other party to time out. Select a higher baud rate for
478 * printf(), regardless of debug level for the sake of uniformity. */
479 Serial pc(USBTX, USBRX);
480 pc.baud(115200);
481
482 MBED_HOSTTEST_TIMEOUT(120);
483 MBED_HOSTTEST_SELECT(default);
484 MBED_HOSTTEST_DESCRIPTION(mbed TLS example HTTPS client);
485 MBED_HOSTTEST_START("MBEDTLS_EX_HTTPS_CLIENT");
486 MBED_HOSTTEST_RESULT(example_client() == 0);
487}
488
489#endif /* TARGET_LIKE_MBED */