1 /*
2  *  SSL server demonstration program using fork() for handling multiple clients
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_SRV_C) ||           \
16     !defined(MBEDTLS_PEM_PARSE_C) || !defined(MBEDTLS_X509_CRT_PARSE_C)
main(void)17 int main(void)
18 {
19     mbedtls_printf("MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C and/or "
20                    "MBEDTLS_NET_C and/or MBEDTLS_SSL_SRV_C and/or "
21                    "MBEDTLS_PEM_PARSE_C and/or MBEDTLS_X509_CRT_PARSE_C "
22                    "not defined.\n");
23     mbedtls_exit(0);
24 }
25 #elif defined(_WIN32)
main(void)26 int main(void)
27 {
28     mbedtls_printf("_WIN32 defined. This application requires fork() and signals "
29                    "to work correctly.\n");
30     mbedtls_exit(0);
31 }
32 #else
33 
34 #include "mbedtls/entropy.h"
35 #include "mbedtls/ctr_drbg.h"
36 #include "test/certs.h"
37 #include "mbedtls/x509.h"
38 #include "mbedtls/ssl.h"
39 #include "mbedtls/net_sockets.h"
40 #include "mbedtls/timing.h"
41 
42 #include <string.h>
43 #include <signal.h>
44 
45 #if !defined(_MSC_VER) || defined(EFIX64) || defined(EFI32)
46 #include <unistd.h>
47 #endif
48 
49 #define HTTP_RESPONSE \
50     "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
51     "<h2>Mbed TLS Test Server</h2>\r\n" \
52     "<p>Successful connection using: %s</p>\r\n"
53 
54 #define DEBUG_LEVEL 0
55 
56 
my_debug(void * ctx,int level,const char * file,int line,const char * str)57 static void my_debug(void *ctx, int level,
58                      const char *file, int line,
59                      const char *str)
60 {
61     ((void) level);
62 
63     mbedtls_fprintf((FILE *) ctx, "%s:%04d: %s", file, line, str);
64     fflush((FILE *) ctx);
65 }
66 
main(void)67 int main(void)
68 {
69     int ret = 1, len, cnt = 0, pid;
70     int exit_code = MBEDTLS_EXIT_FAILURE;
71     mbedtls_net_context listen_fd, client_fd;
72     unsigned char buf[1024];
73     const char *pers = "ssl_fork_server";
74 
75     mbedtls_entropy_context entropy;
76     mbedtls_ctr_drbg_context ctr_drbg;
77     mbedtls_ssl_context ssl;
78     mbedtls_ssl_config conf;
79     mbedtls_x509_crt srvcert;
80     mbedtls_pk_context pkey;
81 
82     mbedtls_net_init(&listen_fd);
83     mbedtls_net_init(&client_fd);
84     mbedtls_ssl_init(&ssl);
85     mbedtls_ssl_config_init(&conf);
86     mbedtls_entropy_init(&entropy);
87     mbedtls_pk_init(&pkey);
88     mbedtls_x509_crt_init(&srvcert);
89     mbedtls_ctr_drbg_init(&ctr_drbg);
90 
91     psa_status_t status = psa_crypto_init();
92     if (status != PSA_SUCCESS) {
93         mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
94                         (int) status);
95         goto exit;
96     }
97 
98     signal(SIGCHLD, SIG_IGN);
99 
100     /*
101      * 0. Initial seeding of the RNG
102      */
103     mbedtls_printf("\n  . Initial seeding of the random generator...");
104     fflush(stdout);
105 
106     if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
107                                      (const unsigned char *) pers,
108                                      strlen(pers))) != 0) {
109         mbedtls_printf(" failed!  mbedtls_ctr_drbg_seed returned %d\n\n", ret);
110         goto exit;
111     }
112 
113     mbedtls_printf(" ok\n");
114 
115     /*
116      * 1. Load the certificates and private RSA key
117      */
118     mbedtls_printf("  . Loading the server cert. and key...");
119     fflush(stdout);
120 
121     /*
122      * This demonstration program uses embedded test certificates.
123      * Instead, you may want to use mbedtls_x509_crt_parse_file() to read the
124      * server and CA certificates, as well as mbedtls_pk_parse_keyfile().
125      */
126     ret = mbedtls_x509_crt_parse(&srvcert, (const unsigned char *) mbedtls_test_srv_crt,
127                                  mbedtls_test_srv_crt_len);
128     if (ret != 0) {
129         mbedtls_printf(" failed!  mbedtls_x509_crt_parse returned %d\n\n", ret);
130         goto exit;
131     }
132 
133     ret = mbedtls_x509_crt_parse(&srvcert, (const unsigned char *) mbedtls_test_cas_pem,
134                                  mbedtls_test_cas_pem_len);
135     if (ret != 0) {
136         mbedtls_printf(" failed!  mbedtls_x509_crt_parse returned %d\n\n", ret);
137         goto exit;
138     }
139 
140     ret =  mbedtls_pk_parse_key(&pkey, (const unsigned char *) mbedtls_test_srv_key,
141                                 mbedtls_test_srv_key_len, NULL, 0);
142     if (ret != 0) {
143         mbedtls_printf(" failed!  mbedtls_pk_parse_key returned %d\n\n", ret);
144         goto exit;
145     }
146 
147     mbedtls_printf(" ok\n");
148 
149     /*
150      * 1b. Prepare SSL configuration
151      */
152     mbedtls_printf("  . Configuring SSL...");
153     fflush(stdout);
154 
155     if ((ret = mbedtls_ssl_config_defaults(&conf,
156                                            MBEDTLS_SSL_IS_SERVER,
157                                            MBEDTLS_SSL_TRANSPORT_STREAM,
158                                            MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
159         mbedtls_printf(" failed!  mbedtls_ssl_config_defaults returned %d\n\n", ret);
160         goto exit;
161     }
162 
163     mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
164 
165     mbedtls_ssl_conf_ca_chain(&conf, srvcert.next, NULL);
166     if ((ret = mbedtls_ssl_conf_own_cert(&conf, &srvcert, &pkey)) != 0) {
167         mbedtls_printf(" failed!  mbedtls_ssl_conf_own_cert returned %d\n\n", ret);
168         goto exit;
169     }
170 
171     mbedtls_printf(" ok\n");
172 
173     /*
174      * 2. Setup the listening TCP socket
175      */
176     mbedtls_printf("  . Bind on https://localhost:4433/ ...");
177     fflush(stdout);
178 
179     if ((ret = mbedtls_net_bind(&listen_fd, NULL, "4433", MBEDTLS_NET_PROTO_TCP)) != 0) {
180         mbedtls_printf(" failed!  mbedtls_net_bind returned %d\n\n", ret);
181         goto exit;
182     }
183 
184     mbedtls_printf(" ok\n");
185 
186     while (1) {
187         /*
188          * 3. Wait until a client connects
189          */
190         mbedtls_net_init(&client_fd);
191         mbedtls_ssl_init(&ssl);
192 
193         mbedtls_printf("  . Waiting for a remote connection ...\n");
194         fflush(stdout);
195 
196         if ((ret = mbedtls_net_accept(&listen_fd, &client_fd,
197                                       NULL, 0, NULL)) != 0) {
198             mbedtls_printf(" failed!  mbedtls_net_accept returned %d\n\n", ret);
199             goto exit;
200         }
201 
202         /*
203          * 3.5. Forking server thread
204          */
205 
206         mbedtls_printf("  . Forking to handle connection ...");
207         fflush(stdout);
208 
209         pid = fork();
210 
211         if (pid < 0) {
212             mbedtls_printf(" failed!  fork returned %d\n\n", pid);
213             goto exit;
214         }
215 
216         if (pid != 0) {
217             mbedtls_printf(" ok\n");
218             mbedtls_net_close(&client_fd);
219             fflush(stdout);
220 
221             if ((ret = mbedtls_ctr_drbg_reseed(&ctr_drbg,
222                                                (const unsigned char *) "parent",
223                                                6)) != 0) {
224                 mbedtls_printf(" failed!  mbedtls_ctr_drbg_reseed returned %d\n\n", ret);
225                 goto exit;
226             }
227 
228             continue;
229         }
230 
231         mbedtls_net_close(&listen_fd);
232 
233         pid = getpid();
234 
235         /*
236          * 4. Setup stuff
237          */
238         mbedtls_printf("pid %d: Setting up the SSL data.\n", pid);
239         fflush(stdout);
240 
241         if ((ret = mbedtls_ctr_drbg_reseed(&ctr_drbg,
242                                            (const unsigned char *) "child",
243                                            5)) != 0) {
244             mbedtls_printf(
245                 "pid %d: SSL setup failed!  mbedtls_ctr_drbg_reseed returned %d\n\n",
246                 pid, ret);
247             goto exit;
248         }
249 
250         if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
251             mbedtls_printf(
252                 "pid %d: SSL setup failed!  mbedtls_ssl_setup returned %d\n\n",
253                 pid, ret);
254             goto exit;
255         }
256 
257         mbedtls_ssl_set_bio(&ssl, &client_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
258 
259         mbedtls_printf("pid %d: SSL setup ok\n", pid);
260 
261         /*
262          * 5. Handshake
263          */
264         mbedtls_printf("pid %d: Performing the SSL/TLS handshake.\n", pid);
265         fflush(stdout);
266 
267         while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
268             if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
269                 mbedtls_printf(
270                     "pid %d: SSL handshake failed!  mbedtls_ssl_handshake returned %d\n\n",
271                     pid, ret);
272                 goto exit;
273             }
274         }
275 
276         mbedtls_printf("pid %d: SSL handshake ok\n", pid);
277         fflush(stdout);
278 
279         /*
280          * 6. Read the HTTP Request
281          */
282         mbedtls_printf("pid %d: Start reading from client.\n", pid);
283         fflush(stdout);
284 
285         do {
286             len = sizeof(buf) - 1;
287             memset(buf, 0, sizeof(buf));
288             ret = mbedtls_ssl_read(&ssl, buf, len);
289 
290             if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
291                 continue;
292             }
293 
294             if (ret <= 0) {
295                 switch (ret) {
296                     case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
297                         mbedtls_printf("pid %d: connection was closed gracefully\n", pid);
298                         break;
299 
300                     case MBEDTLS_ERR_NET_CONN_RESET:
301                         mbedtls_printf("pid %d: connection was reset by peer\n", pid);
302                         break;
303 
304                     default:
305                         mbedtls_printf("pid %d: mbedtls_ssl_read returned %d\n", pid, ret);
306                         break;
307                 }
308                 fflush(stdout);
309 
310                 break;
311             }
312 
313             len = ret;
314             mbedtls_printf("pid %d: %d bytes read\n\n%s", pid, len, (char *) buf);
315             fflush(stdout);
316 
317             if (ret > 0) {
318                 break;
319             }
320         } while (1);
321 
322         /*
323          * 7. Write the 200 Response
324          */
325         mbedtls_printf("pid %d: Start writing to client.\n", pid);
326         fflush(stdout);
327 
328         len = sprintf((char *) buf, HTTP_RESPONSE,
329                       mbedtls_ssl_get_ciphersuite(&ssl));
330 
331         while (cnt++ < 10) {
332             while ((ret = mbedtls_ssl_write(&ssl, buf, len)) <= 0) {
333                 if (ret == MBEDTLS_ERR_NET_CONN_RESET) {
334                     mbedtls_printf(
335                         "pid %d: Write failed!  peer closed the connection\n\n", pid);
336                     goto exit;
337                 }
338 
339                 if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
340                     mbedtls_printf(
341                         "pid %d: Write failed!  mbedtls_ssl_write returned %d\n\n",
342                         pid, ret);
343                     goto exit;
344                 }
345             }
346             len = ret;
347             mbedtls_printf("pid %d: %d bytes written (cnt=%d)\n\n%s\n",
348                            pid, len, cnt, (char *) buf);
349             fflush(stdout);
350 
351             mbedtls_net_usleep(1000000);
352         }
353 
354         mbedtls_ssl_close_notify(&ssl);
355         mbedtls_printf("pid %d: shutting down\n", pid);
356         fflush(stdout);
357         goto exit;
358     }
359 
360 exit:
361     mbedtls_net_free(&client_fd);
362     mbedtls_net_free(&listen_fd);
363     mbedtls_x509_crt_free(&srvcert);
364     mbedtls_pk_free(&pkey);
365     mbedtls_ssl_free(&ssl);
366     mbedtls_ssl_config_free(&conf);
367     mbedtls_ctr_drbg_free(&ctr_drbg);
368     mbedtls_entropy_free(&entropy);
369     mbedtls_psa_crypto_free();
370 
371     mbedtls_exit(exit_code);
372 }
373 #endif /* MBEDTLS_BIGNUM_C && MBEDTLS_ENTROPY_C &&
374           MBEDTLS_SSL_TLS_C && MBEDTLS_SSL_SRV_C && MBEDTLS_NET_C &&
375           MBEDTLS_RSA_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_PEM_PARSE_C &&
376           ! _WIN32 */
377