1 /*
2  *  Simple DTLS server program that does the same thing as echo-server but
3  *  over encrypted UDP link.
4  *
5  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
6  *  Copyright (C) 2017 Intel Corporation
7  *  SPDX-License-Identifier: Apache-2.0
8  *
9  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
10  *  not use this file except in compliance with the License.
11  *  You may obtain a copy of the License at
12  *
13  *  http://www.apache.org/licenses/LICENSE-2.0
14  *
15  *  Unless required by applicable law or agreed to in writing, software
16  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  *  See the License for the specific language governing permissions and
19  *  limitations under the License.
20  *
21  */
22 
23 #include <stdbool.h>
24 #include <unistd.h>
25 #include <errno.h>
26 
27 #if !defined(MBEDTLS_CONFIG_FILE)
28 #include "mbedtls/config.h"
29 #else
30 #include MBEDTLS_CONFIG_FILE
31 #endif
32 
33 #if defined(MBEDTLS_PLATFORM_C)
34 #include "mbedtls/platform.h"
35 #else
36 #include <stdio.h>
37 #define mbedtls_printf     printf
38 #define mbedtls_fprintf    fprintf
39 #define mbedtls_time_t     time_t
40 #endif
41 
42 #if !defined(MBEDTLS_SSL_SRV_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ||	\
43 	!defined(MBEDTLS_SSL_COOKIE_C) || !defined(MBEDTLS_NET_C) ||	\
44 	!defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) ||	\
45 	!defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_RSA_C) || \
46 	!defined(MBEDTLS_CERTS_C) || !defined(MBEDTLS_PEM_PARSE_C) ||	\
47 	!defined(MBEDTLS_TIMING_C)
48 
main(void)49 int main(void)
50 {
51 	printf("MBEDTLS_SSL_SRV_C and/or MBEDTLS_SSL_PROTO_DTLS and/or "
52 	       "MBEDTLS_SSL_COOKIE_C and/or MBEDTLS_NET_C and/or "
53 	       "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C and/or "
54 	       "MBEDTLS_X509_CRT_PARSE_C and/or MBEDTLS_RSA_C and/or "
55 	       "MBEDTLS_CERTS_C and/or MBEDTLS_PEM_PARSE_C and/or "
56 	       "MBEDTLS_TIMING_C not defined.\n");
57 	return(0);
58 }
59 #else
60 
61 #if defined(_WIN32)
62 #include <windows.h>
63 #endif
64 
65 #include <string.h>
66 #include <stdlib.h>
67 #include <stdio.h>
68 
69 #include "mbedtls/entropy.h"
70 #include "mbedtls/ctr_drbg.h"
71 #include "mbedtls/certs.h"
72 #include "mbedtls/x509.h"
73 #include "mbedtls/ssl.h"
74 #include "mbedtls/ssl_cookie.h"
75 #include "mbedtls/net_sockets.h"
76 #include "mbedtls/error.h"
77 #include "mbedtls/debug.h"
78 #include "mbedtls/timing.h"
79 
80 #if defined(MBEDTLS_SSL_CACHE_C)
81 #include "mbedtls/ssl_cache.h"
82 #endif
83 
84 #define READ_TIMEOUT_MS 10000   /* 5 seconds */
85 #define DEBUG_LEVEL 0
86 
87 extern int optind, opterr, optopt;
88 extern char *optarg;
89 
90 static bool debug;
91 static bool help;
92 
my_debug(void * ctx,int level,const char * file,int line,const char * str)93 static void my_debug(void *ctx, int level,
94 		     const char *file, int line,
95 		     const char *str)
96 {
97 	((void) level);
98 
99 	mbedtls_fprintf((FILE *) ctx, "%s:%04d: %s", file, line, str);
100 	fflush( (FILE *) ctx );
101 }
102 
main(int argc,char * argv[])103 int main(int argc, char *argv[])
104 {
105 	int ret, len, c;
106 	mbedtls_net_context listen_fd, client_fd;
107 	unsigned char buf[1024];
108 	const char *pers = "dtls_server";
109 	unsigned char client_ip[16] = { 0 };
110 	size_t cliip_len;
111 	mbedtls_ssl_cookie_ctx cookie_ctx;
112 
113 	mbedtls_entropy_context entropy;
114 	mbedtls_ctr_drbg_context ctr_drbg;
115 	mbedtls_ssl_context ssl;
116 	mbedtls_ssl_config conf;
117 	mbedtls_x509_crt srvcert;
118 	mbedtls_pk_context pkey;
119 	mbedtls_timing_delay_context timer;
120 #if defined(MBEDTLS_SSL_CACHE_C)
121 	mbedtls_ssl_cache_context cache;
122 #endif
123 
124 #define LISTEN_PORT "4242"
125 	const char *listen_port = LISTEN_PORT;
126 
127 #define SRV_CERT_FILE "echo-apps-cert.pem"
128 	const char *srv_cert_file = SRV_CERT_FILE;
129 
130 #define SRV_KEY_FILE "echo-apps-key.pem"
131 	const char *srv_key_file = SRV_KEY_FILE;
132 
133 	opterr = 0;
134 
135 	while ((c = getopt(argc, argv, "c:k:p:Dh")) != -1) {
136 		switch (c) {
137 		case 'c':
138 			srv_cert_file = optarg;
139 			break;
140 		case 'k':
141 			srv_key_file = optarg;
142 			break;
143 		case 'p':
144 			listen_port = optarg;
145 			break;
146 		case 'D':
147 			debug = true;
148 			break;
149 		case 'h':
150 			help = true;
151 			break;
152 		}
153 	}
154 
155 	if (help) {
156 		printf("usage: %s [-c <server cert file>] [-k <cert key file>] "
157 		       "[-p <port>] [-D]\n", argv[0]);
158 		printf("-c Server cert file (default is %s)\n", SRV_CERT_FILE);
159 		printf("-k Server key file (default is %s)\n", SRV_KEY_FILE);
160 		printf("-p Port number to use (default is %s)\n", LISTEN_PORT);
161 		printf("-D Activate debugging.\n");
162 		exit(-EINVAL);
163 	}
164 
165 	mbedtls_net_init(&listen_fd);
166 	mbedtls_net_init(&client_fd);
167 	mbedtls_ssl_init(&ssl);
168 	mbedtls_ssl_config_init(&conf);
169 	mbedtls_ssl_cookie_init(&cookie_ctx);
170 #if defined(MBEDTLS_SSL_CACHE_C)
171 	mbedtls_ssl_cache_init(&cache);
172 #endif
173 	mbedtls_x509_crt_init(&srvcert);
174 	mbedtls_pk_init(&pkey);
175 	mbedtls_entropy_init(&entropy);
176 	mbedtls_ctr_drbg_init(&ctr_drbg);
177 
178 #if defined(MBEDTLS_DEBUG_C)
179 	mbedtls_debug_set_threshold(DEBUG_LEVEL);
180 #endif
181 
182 	/*
183 	 * 1. Load the certificates and private RSA key
184 	 */
185 	printf("\n  . Loading the server cert. and key...");
186 	fflush(stdout);
187 
188 	ret = mbedtls_x509_crt_parse_file(&srvcert, srv_cert_file);
189 	if (ret != 0) {
190 		printf(" failed\n  !  mbedtls_x509_crt_parse returned %d\n\n",
191 		       ret);
192 		goto exit;
193 	}
194 
195 	ret =  mbedtls_pk_parse_keyfile(&pkey, srv_key_file, NULL);
196 	if (ret != 0) {
197 		printf(" failed\n  !  mbedtls_pk_parse_keyfile returned %d\n\n",
198 		       ret);
199 		goto exit;
200 	}
201 
202 	printf(" ok\n");
203 
204 	/*
205 	 * 2. Setup the "listening" UDP socket
206 	 */
207 	printf("  . Bind on udp/*/%s ...", listen_port);
208 	fflush(stdout);
209 
210 	if ((ret = mbedtls_net_bind(&listen_fd, NULL, listen_port,
211 				    MBEDTLS_NET_PROTO_UDP)) != 0) {
212 		printf(" failed\n  ! mbedtls_net_bind returned %d\n\n", ret);
213 		goto exit;
214 	}
215 
216 	printf(" ok\n");
217 
218 	/*
219 	 * 3. Seed the RNG
220 	 */
221 	printf("  . Seeding the random number generator...");
222 	fflush(stdout);
223 
224 	if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
225 					 &entropy,
226 					 (const unsigned char *) pers,
227 					 strlen(pers))) != 0) {
228 		printf(" failed\n  ! mbedtls_ctr_drbg_seed returned %d\n", ret);
229 		goto exit;
230 	}
231 
232 	printf(" ok\n");
233 
234 	/*
235 	 * 4. Setup stuff
236 	 */
237 	printf("  . Setting up the DTLS data...");
238 	fflush(stdout);
239 
240 	if ((ret = mbedtls_ssl_config_defaults(&conf,
241 					       MBEDTLS_SSL_IS_SERVER,
242 					       MBEDTLS_SSL_TRANSPORT_DATAGRAM,
243 					       MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
244 		mbedtls_printf(" failed\n  ! mbedtls_ssl_config_defaults "
245 			       "returned %d\n\n", ret);
246 		goto exit;
247 	}
248 
249 	mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
250 	mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
251 
252 #if defined(MBEDTLS_SSL_CACHE_C)
253 	mbedtls_ssl_conf_session_cache(&conf, &cache,
254 				       mbedtls_ssl_cache_get,
255 				       mbedtls_ssl_cache_set);
256 #endif
257 
258 	mbedtls_ssl_conf_ca_chain(&conf, srvcert.next, NULL);
259 	if ((ret = mbedtls_ssl_conf_own_cert(&conf, &srvcert, &pkey)) != 0) {
260 		printf(" failed\n  ! mbedtls_ssl_conf_own_cert "
261 		       "returned %d\n\n", ret);
262 		goto exit;
263 	}
264 
265 	if ((ret = mbedtls_ssl_cookie_setup(&cookie_ctx,
266 					    mbedtls_ctr_drbg_random,
267 					    &ctr_drbg)) != 0) {
268 		printf(" failed\n  ! mbedtls_ssl_cookie_setup returned %d\n\n",
269 		       ret);
270 		goto exit;
271 	}
272 
273 	mbedtls_ssl_conf_dtls_cookies(&conf, mbedtls_ssl_cookie_write,
274 				      mbedtls_ssl_cookie_check, &cookie_ctx);
275 
276 	if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
277 		printf(" failed\n  ! mbedtls_ssl_setup returned %d\n\n", ret);
278 		goto exit;
279 	}
280 
281 	mbedtls_ssl_set_timer_cb(&ssl, &timer, mbedtls_timing_set_delay,
282 				 mbedtls_timing_get_delay);
283 
284 	printf(" ok\n");
285 
286 reset:
287 #ifdef MBEDTLS_ERROR_C
288 	if (ret != 0) {
289 		char error_buf[100];
290 		mbedtls_strerror(ret, error_buf, 100);
291 		printf("Last error was: %d - %s\n\n", ret, error_buf);
292 	}
293 #endif
294 
295 	mbedtls_net_free(&client_fd);
296 
297 	mbedtls_ssl_session_reset(&ssl);
298 
299 	/*
300 	 * 3. Wait until a client connects
301 	 */
302 	printf("  . Waiting for a remote connection ...");
303 	fflush(stdout);
304 
305 	if ((ret = mbedtls_net_accept(&listen_fd, &client_fd,
306 				      client_ip, sizeof(client_ip),
307 				      &cliip_len)) != 0) {
308 		printf(" failed\n  ! mbedtls_net_accept returned %d\n\n", ret);
309 		goto exit;
310 	}
311 
312 	/* For HelloVerifyRequest cookies */
313 	if ((ret = mbedtls_ssl_set_client_transport_id(&ssl,
314 						       client_ip,
315 						       cliip_len)) != 0) {
316 		printf(" failed\n  ! "
317 		       "mbedtls_ssl_set_client_transport_id() "
318 		       "returned -0x%x\n\n", -ret);
319 		goto exit;
320 	}
321 
322 	mbedtls_ssl_set_bio(&ssl, &client_fd,
323 			    mbedtls_net_send, mbedtls_net_recv,
324 			    mbedtls_net_recv_timeout);
325 
326 	printf(" ok\n");
327 
328 	/*
329 	 * 5. Handshake
330 	 */
331 	printf("  . Performing the DTLS handshake...");
332 	fflush(stdout);
333 
334 	do ret = mbedtls_ssl_handshake(&ssl);
335 	while(ret == MBEDTLS_ERR_SSL_WANT_READ ||
336 	      ret == MBEDTLS_ERR_SSL_WANT_WRITE);
337 
338 	if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) {
339 		printf(" hello verification requested\n");
340 		ret = 0;
341 		goto reset;
342 	}
343 	else if (ret != 0)
344 	{
345 		printf(" failed\n  ! mbedtls_ssl_handshake returned -0x%x\n\n",
346 		       -ret);
347 		goto reset;
348 	}
349 
350 	printf(" ok\n");
351 
352 again:
353 	/*
354 	 * 6. Read the echo Request
355 	 */
356 	printf("  < Read from client:");
357 	fflush(stdout);
358 
359 	len = sizeof(buf) - 1;
360 	memset(buf, 0, sizeof(buf));
361 
362 	do ret = mbedtls_ssl_read(&ssl, buf, len);
363 	while(ret == MBEDTLS_ERR_SSL_WANT_READ ||
364 	      ret == MBEDTLS_ERR_SSL_WANT_WRITE);
365 
366 	if (ret <= 0) {
367 		switch(ret) {
368 		case MBEDTLS_ERR_SSL_TIMEOUT:
369 			printf(" timeout\n\n");
370 			goto reset;
371 
372 		case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
373 			printf(" connection was closed gracefully\n");
374 			ret = 0;
375 			goto close_notify;
376 
377 		default:
378 			printf(" mbedtls_ssl_read returned -0x%x\n\n", -ret);
379 			goto reset;
380 		}
381 	}
382 
383 	len = ret;
384 	printf(" %d bytes read\n\n%s\n\n", len, buf);
385 
386 	/*
387 	 * 7. Write the 200 Response
388 	 */
389 	printf("  > Write to client:");
390 	fflush(stdout);
391 
392 	do ret = mbedtls_ssl_write(&ssl, buf, len);
393 	while(ret == MBEDTLS_ERR_SSL_WANT_READ ||
394 	      ret == MBEDTLS_ERR_SSL_WANT_WRITE);
395 
396 	if (ret < 0) {
397 		printf(" failed\n  ! mbedtls_ssl_write returned %d\n\n", ret);
398 		goto exit;
399 	}
400 
401 	len = ret;
402 	printf(" %d bytes written\n\n%s\n\n", len, buf);
403 
404 	goto again;
405 
406 	/*
407 	 * 8. Done, cleanly close the connection
408 	 */
409 close_notify:
410 	printf("  . Closing the connection...");
411 
412 	/* No error checking, the connection might be closed already */
413 	do ret = mbedtls_ssl_close_notify(&ssl);
414 	while(ret == MBEDTLS_ERR_SSL_WANT_WRITE);
415 	ret = 0;
416 
417 	printf(" done\n");
418 
419 	goto reset;
420 
421 	/*
422 	 * Final clean-ups and exit
423 	 */
424 exit:
425 
426 #ifdef MBEDTLS_ERROR_C
427 	if (ret != 0) {
428 		char error_buf[100];
429 		mbedtls_strerror(ret, error_buf, 100);
430 		printf("Last error was: %d - %s\n\n", ret, error_buf);
431 	}
432 #endif
433 
434 	mbedtls_net_free(&client_fd);
435 	mbedtls_net_free(&listen_fd);
436 
437 	mbedtls_x509_crt_free(&srvcert);
438 	mbedtls_pk_free(&pkey);
439 	mbedtls_ssl_free(&ssl);
440 	mbedtls_ssl_config_free(&conf);
441 	mbedtls_ssl_cookie_free(&cookie_ctx);
442 #if defined(MBEDTLS_SSL_CACHE_C)
443 	mbedtls_ssl_cache_free(&cache);
444 #endif
445 	mbedtls_ctr_drbg_free(&ctr_drbg);
446 	mbedtls_entropy_free(&entropy);
447 
448 #if defined(_WIN32)
449 	printf("  Press Enter to exit this program.\n");
450 	fflush(stdout); getchar();
451 #endif
452 
453 	/* Shell can not handle large exit numbers -> 1 for errors */
454 	if (ret < 0)
455 		ret = 1;
456 
457 	return(ret);
458 }
459 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_PROTO_DTLS &&
460           MBEDTLS_SSL_COOKIE_C && MBEDTLS_NET_C && MBEDTLS_ENTROPY_C &&
461           MBEDTLS_CTR_DRBG_C && MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_RSA_C
462           && MBEDTLS_CERTS_C && MBEDTLS_PEM_PARSE_C && MBEDTLS_TIMING_C */
463