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