1 /*
2  *  Simple DTLS client demonstration program
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
9 
10 #include "mbedtls/build_info.h"
11 
12 #include "mbedtls/platform.h"
13 
14 #if !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) ||      \
15     !defined(MBEDTLS_NET_C) || !defined(MBEDTLS_SSL_CLI_C) ||           \
16     !defined(MBEDTLS_TIMING_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ||   \
17     !defined(MBEDTLS_PEM_PARSE_C) || !defined(MBEDTLS_X509_CRT_PARSE_C)
main(void)18 int main(void)
19 {
20     mbedtls_printf("MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C and/or "
21                    "MBEDTLS_NET_C and/or MBEDTLS_SSL_CLI_C and/or "
22                    "MBEDTLS_TIMING_C and/or MBEDTLS_SSL_PROTO_DTLS and/or "
23                    "MBEDTLS_PEM_PARSE_C and/or MBEDTLS_X509_CRT_PARSE_C "
24                    "not defined.\n");
25     mbedtls_exit(0);
26 }
27 #else
28 
29 #include <string.h>
30 
31 #include "mbedtls/net_sockets.h"
32 #include "mbedtls/debug.h"
33 #include "mbedtls/ssl.h"
34 #include "mbedtls/entropy.h"
35 #include "mbedtls/ctr_drbg.h"
36 #include "mbedtls/error.h"
37 #include "mbedtls/timing.h"
38 #include "test/certs.h"
39 
40 /* Uncomment out the following line to default to IPv4 and disable IPv6 */
41 //#define FORCE_IPV4
42 
43 #define SERVER_PORT "4433"
44 #define SERVER_NAME "localhost"
45 
46 #ifdef FORCE_IPV4
47 #define SERVER_ADDR "127.0.0.1"     /* Forces IPv4 */
48 #else
49 #define SERVER_ADDR SERVER_NAME
50 #endif
51 
52 #define MESSAGE     "Echo this"
53 
54 #define READ_TIMEOUT_MS 1000
55 #define MAX_RETRY       5
56 
57 #define DEBUG_LEVEL 0
58 
59 
my_debug(void * ctx,int level,const char * file,int line,const char * str)60 static void my_debug(void *ctx, int level,
61                      const char *file, int line,
62                      const char *str)
63 {
64     ((void) level);
65 
66     mbedtls_fprintf((FILE *) ctx, "%s:%04d: %s", file, line, str);
67     fflush((FILE *) ctx);
68 }
69 
main(int argc,char * argv[])70 int main(int argc, char *argv[])
71 {
72     int ret, len;
73     mbedtls_net_context server_fd;
74     uint32_t flags;
75     unsigned char buf[1024];
76     const char *pers = "dtls_client";
77     int retry_left = MAX_RETRY;
78 
79     mbedtls_entropy_context entropy;
80     mbedtls_ctr_drbg_context ctr_drbg;
81     mbedtls_ssl_context ssl;
82     mbedtls_ssl_config conf;
83     mbedtls_x509_crt cacert;
84     mbedtls_timing_delay_context timer;
85 
86     ((void) argc);
87     ((void) argv);
88 
89 #if defined(MBEDTLS_DEBUG_C)
90     mbedtls_debug_set_threshold(DEBUG_LEVEL);
91 #endif
92 
93     /*
94      * 0. Initialize the RNG and the session data
95      */
96     mbedtls_net_init(&server_fd);
97     mbedtls_ssl_init(&ssl);
98     mbedtls_ssl_config_init(&conf);
99     mbedtls_x509_crt_init(&cacert);
100     mbedtls_ctr_drbg_init(&ctr_drbg);
101     mbedtls_entropy_init(&entropy);
102 
103     psa_status_t status = psa_crypto_init();
104     if (status != PSA_SUCCESS) {
105         mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
106                         (int) status);
107         ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
108         goto exit;
109     }
110 
111     mbedtls_printf("\n  . Seeding the random number generator...");
112     fflush(stdout);
113 
114     if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
115                                      (const unsigned char *) pers,
116                                      strlen(pers))) != 0) {
117         mbedtls_printf(" failed\n  ! mbedtls_ctr_drbg_seed returned %d\n", ret);
118         goto exit;
119     }
120 
121     mbedtls_printf(" ok\n");
122 
123     /*
124      * 0. Load certificates
125      */
126     mbedtls_printf("  . Loading the CA root certificate ...");
127     fflush(stdout);
128 
129     ret = mbedtls_x509_crt_parse(&cacert, (const unsigned char *) mbedtls_test_cas_pem,
130                                  mbedtls_test_cas_pem_len);
131     if (ret < 0) {
132         mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse returned -0x%x\n\n",
133                        (unsigned int) -ret);
134         goto exit;
135     }
136 
137     mbedtls_printf(" ok (%d skipped)\n", ret);
138 
139     /*
140      * 1. Start the connection
141      */
142     mbedtls_printf("  . Connecting to udp/%s/%s...", SERVER_NAME, SERVER_PORT);
143     fflush(stdout);
144 
145     if ((ret = mbedtls_net_connect(&server_fd, SERVER_ADDR,
146                                    SERVER_PORT, MBEDTLS_NET_PROTO_UDP)) != 0) {
147         mbedtls_printf(" failed\n  ! mbedtls_net_connect returned %d\n\n", ret);
148         goto exit;
149     }
150 
151     mbedtls_printf(" ok\n");
152 
153     /*
154      * 2. Setup stuff
155      */
156     mbedtls_printf("  . Setting up the DTLS structure...");
157     fflush(stdout);
158 
159     if ((ret = mbedtls_ssl_config_defaults(&conf,
160                                            MBEDTLS_SSL_IS_CLIENT,
161                                            MBEDTLS_SSL_TRANSPORT_DATAGRAM,
162                                            MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
163         mbedtls_printf(" failed\n  ! mbedtls_ssl_config_defaults returned %d\n\n", ret);
164         goto exit;
165     }
166 
167     /* OPTIONAL is usually a bad choice for security, but makes interop easier
168      * in this simplified example, in which the ca chain is hardcoded.
169      * Production code should set a proper ca chain and use REQUIRED. */
170     mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
171     mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
172     mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
173     mbedtls_ssl_conf_read_timeout(&conf, READ_TIMEOUT_MS);
174 
175     if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
176         mbedtls_printf(" failed\n  ! mbedtls_ssl_setup returned %d\n\n", ret);
177         goto exit;
178     }
179 
180     if ((ret = mbedtls_ssl_set_hostname(&ssl, SERVER_NAME)) != 0) {
181         mbedtls_printf(" failed\n  ! mbedtls_ssl_set_hostname returned %d\n\n", ret);
182         goto exit;
183     }
184 
185     mbedtls_ssl_set_bio(&ssl, &server_fd,
186                         mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout);
187 
188     mbedtls_ssl_set_timer_cb(&ssl, &timer, mbedtls_timing_set_delay,
189                              mbedtls_timing_get_delay);
190 
191     mbedtls_printf(" ok\n");
192 
193     /*
194      * 4. Handshake
195      */
196     mbedtls_printf("  . Performing the DTLS handshake...");
197     fflush(stdout);
198 
199     do {
200         ret = mbedtls_ssl_handshake(&ssl);
201     } while (ret == MBEDTLS_ERR_SSL_WANT_READ ||
202              ret == MBEDTLS_ERR_SSL_WANT_WRITE);
203 
204     if (ret != 0) {
205         mbedtls_printf(" failed\n  ! mbedtls_ssl_handshake returned -0x%x\n\n",
206                        (unsigned int) -ret);
207         goto exit;
208     }
209 
210     mbedtls_printf(" ok\n");
211 
212     /*
213      * 5. Verify the server certificate
214      */
215     mbedtls_printf("  . Verifying peer X.509 certificate...");
216 
217     /* In real life, we would have used MBEDTLS_SSL_VERIFY_REQUIRED so that the
218      * handshake would not succeed if the peer's cert is bad.  Even if we used
219      * MBEDTLS_SSL_VERIFY_OPTIONAL, we would bail out here if ret != 0 */
220     if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0) {
221 #if !defined(MBEDTLS_X509_REMOVE_INFO)
222         char vrfy_buf[512];
223 #endif
224 
225         mbedtls_printf(" failed\n");
226 
227 #if !defined(MBEDTLS_X509_REMOVE_INFO)
228         mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), "  ! ", flags);
229 
230         mbedtls_printf("%s\n", vrfy_buf);
231 #endif
232     } else {
233         mbedtls_printf(" ok\n");
234     }
235 
236     /*
237      * 6. Write the echo request
238      */
239 send_request:
240     mbedtls_printf("  > Write to server:");
241     fflush(stdout);
242 
243     len = sizeof(MESSAGE) - 1;
244 
245     do {
246         ret = mbedtls_ssl_write(&ssl, (unsigned char *) MESSAGE, len);
247     } while (ret == MBEDTLS_ERR_SSL_WANT_READ ||
248              ret == MBEDTLS_ERR_SSL_WANT_WRITE);
249 
250     if (ret < 0) {
251         mbedtls_printf(" failed\n  ! mbedtls_ssl_write returned %d\n\n", ret);
252         goto exit;
253     }
254 
255     len = ret;
256     mbedtls_printf(" %d bytes written\n\n%s\n\n", len, MESSAGE);
257 
258     /*
259      * 7. Read the echo response
260      */
261     mbedtls_printf("  < Read from server:");
262     fflush(stdout);
263 
264     len = sizeof(buf) - 1;
265     memset(buf, 0, sizeof(buf));
266 
267     do {
268         ret = mbedtls_ssl_read(&ssl, buf, len);
269     } while (ret == MBEDTLS_ERR_SSL_WANT_READ ||
270              ret == MBEDTLS_ERR_SSL_WANT_WRITE);
271 
272     if (ret <= 0) {
273         switch (ret) {
274             case MBEDTLS_ERR_SSL_TIMEOUT:
275                 mbedtls_printf(" timeout\n\n");
276                 if (retry_left-- > 0) {
277                     goto send_request;
278                 }
279                 goto exit;
280 
281             case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
282                 mbedtls_printf(" connection was closed gracefully\n");
283                 goto close_notify;
284 
285             default:
286                 mbedtls_printf(" mbedtls_ssl_read returned -0x%x\n\n", (unsigned int) -ret);
287                 goto exit;
288         }
289     }
290 
291     len = ret;
292     mbedtls_printf(" %d bytes read\n\n%s\n\n", len, buf);
293 
294     /*
295      * 8. Done, cleanly close the connection
296      */
297 close_notify:
298     mbedtls_printf("  . Closing the connection...");
299 
300     /* No error checking, the connection might be closed already */
301     do {
302         ret = mbedtls_ssl_close_notify(&ssl);
303     } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
304     ret = 0;
305 
306     mbedtls_printf(" done\n");
307 
308     /*
309      * 9. Final clean-ups and exit
310      */
311 exit:
312 
313 #ifdef MBEDTLS_ERROR_C
314     if (ret != 0) {
315         char error_buf[100];
316         mbedtls_strerror(ret, error_buf, 100);
317         mbedtls_printf("Last error was: %d - %s\n\n", ret, error_buf);
318     }
319 #endif
320 
321     mbedtls_net_free(&server_fd);
322     mbedtls_x509_crt_free(&cacert);
323     mbedtls_ssl_free(&ssl);
324     mbedtls_ssl_config_free(&conf);
325     mbedtls_ctr_drbg_free(&ctr_drbg);
326     mbedtls_entropy_free(&entropy);
327     mbedtls_psa_crypto_free();
328 
329     /* Shell can not handle large exit numbers -> 1 for errors */
330     if (ret < 0) {
331         ret = 1;
332     }
333 
334     mbedtls_exit(ret);
335 }
336 
337 #endif /* configuration allows running this program */
338