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