1 /*
2 * Copyright 2024-2025 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 /*
11 * NB: Changes to this file should also be reflected in
12 * doc/man7/ossl-guide-quic-server-non-block.pod
13 */
14
15 #include <string.h>
16
17 /* Include the appropriate header file for SOCK_STREAM */
18 #ifdef _WIN32 /* Windows */
19 # include <stdarg.h>
20 # include <winsock2.h>
21 #else /* Linux/Unix */
22 # include <err.h>
23 # include <sys/socket.h>
24 # include <sys/select.h>
25 # include <netinet/in.h>
26 # include <unistd.h>
27 #endif
28
29 #include <openssl/bio.h>
30 #include <openssl/ssl.h>
31 #include <openssl/err.h>
32 #include <openssl/quic.h>
33
34 #ifdef _WIN32
35 static const char *progname;
36
vwarnx(const char * fmt,va_list ap)37 static void vwarnx(const char *fmt, va_list ap)
38 {
39 if (progname != NULL)
40 fprintf(stderr, "%s: ", progname);
41 vfprintf(stderr, fmt, ap);
42 putc('\n', stderr);
43 }
44
errx(int status,const char * fmt,...)45 static void errx(int status, const char *fmt, ...)
46 {
47 va_list ap;
48
49 va_start(ap, fmt);
50 vwarnx(fmt, ap);
51 va_end(ap);
52 exit(status);
53 }
54
warnx(const char * fmt,...)55 static void warnx(const char *fmt, ...)
56 {
57 va_list ap;
58
59 va_start(ap, fmt);
60 vwarnx(fmt, ap);
61 va_end(ap);
62 }
63 #endif
64
65 /*
66 * ALPN strings for TLS handshake. Only 'http/1.0' and 'hq-interop'
67 * are accepted.
68 */
69 static const unsigned char alpn_ossltest[] = {
70 8, 'h', 't', 't', 'p', '/', '1', '.', '0',
71 10, 'h', 'q', '-', 'i', 'n', 't', 'e', 'r', 'o', 'p',
72 };
73
74 /*
75 * This callback validates and negotiates the desired ALPN on the server side.
76 */
select_alpn(SSL * ssl,const unsigned char ** out,unsigned char * out_len,const unsigned char * in,unsigned int in_len,void * arg)77 static int select_alpn(SSL *ssl, const unsigned char **out,
78 unsigned char *out_len, const unsigned char *in,
79 unsigned int in_len, void *arg)
80 {
81 if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest,
82 sizeof(alpn_ossltest), in,
83 in_len) == OPENSSL_NPN_NEGOTIATED)
84 return SSL_TLSEXT_ERR_OK;
85 return SSL_TLSEXT_ERR_ALERT_FATAL;
86 }
87
88 /* Create SSL_CTX. */
create_ctx(const char * cert_path,const char * key_path)89 static SSL_CTX *create_ctx(const char *cert_path, const char *key_path)
90 {
91 SSL_CTX *ctx;
92
93 /*
94 * An SSL_CTX holds shared configuration information for multiple
95 * subsequent per-client connections. We specifically load a QUIC
96 * server method here.
97 */
98 ctx = SSL_CTX_new(OSSL_QUIC_server_method());
99 if (ctx == NULL)
100 goto err;
101
102 /*
103 * Load the server's certificate *chain* file (PEM format), which includes
104 * not only the leaf (end-entity) server certificate, but also any
105 * intermediate issuer-CA certificates. The leaf certificate must be the
106 * first certificate in the file.
107 *
108 * In advanced use-cases this can be called multiple times, once per public
109 * key algorithm for which the server has a corresponding certificate.
110 * However, the corresponding private key (see below) must be loaded first,
111 * *before* moving on to the next chain file.
112 *
113 * The requisite files "chain.pem" and "pkey.pem" can be generated by running
114 * "make chain" in this directory. If the server will be executed from some
115 * other directory, move or copy the files there.
116 */
117 if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) {
118 fprintf(stderr, "couldn't load certificate file: %s\n", cert_path);
119 goto err;
120 }
121
122 /*
123 * Load the corresponding private key, this also checks that the private
124 * key matches the just loaded end-entity certificate. It does not check
125 * whether the certificate chain is valid, the certificates could be
126 * expired, or may otherwise fail to form a chain that a client can validate.
127 */
128 if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) {
129 fprintf(stderr, "couldn't load key file: %s\n", key_path);
130 goto err;
131 }
132
133 /*
134 * Clients rarely employ certificate-based authentication, and so we don't
135 * require "mutual" TLS authentication (indeed there's no way to know
136 * whether or how the client authenticated the server, so the term "mutual"
137 * is potentially misleading).
138 *
139 * Since we're not soliciting or processing client certificates, we don't
140 * need to configure a trusted-certificate store, so no call to
141 * SSL_CTX_set_default_verify_paths() is needed. The server's own
142 * certificate chain is assumed valid.
143 */
144 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
145
146 /* Setup ALPN negotiation callback to decide which ALPN is accepted. */
147 SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL);
148
149 return ctx;
150
151 err:
152 SSL_CTX_free(ctx);
153 return NULL;
154 }
155
156 /* Create UDP socket on the given port. */
create_socket(uint16_t port)157 static int create_socket(uint16_t port)
158 {
159 int fd;
160 struct sockaddr_in sa = {0};
161
162 /* Retrieve the file descriptor for a new UDP socket */
163 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
164 fprintf(stderr, "cannot create socket");
165 return -1;
166 }
167
168 sa.sin_family = AF_INET;
169 sa.sin_port = htons(port);
170
171 /* Bind to the new UDP socket on localhost */
172 if (bind(fd, (const struct sockaddr *)&sa, sizeof(sa)) < 0) {
173 fprintf(stderr, "cannot bind to %u\n", port);
174 BIO_closesocket(fd);
175 return -1;
176 }
177
178 /* Set port to nonblocking mode */
179 if (BIO_socket_nbio(fd, 1) <= 0) {
180 fprintf(stderr, "Unable to set port to nonblocking mode");
181 BIO_closesocket(fd);
182 return -1;
183 }
184
185 return fd;
186 }
187
188 /**
189 * @brief Waits for activity on the SSL socket, either for reading or writing.
190 *
191 * This function monitors the underlying file descriptor of the given SSL
192 * connection to determine when it is ready for reading or writing, or both.
193 * It uses the select function to wait until the socket is either readable
194 * or writable, depending on what the SSL connection requires.
195 *
196 * @param ssl A pointer to the SSL object representing the connection.
197 *
198 * @note This function blocks until there is activity on the socket. In a real
199 * application, you might want to perform other tasks while waiting, such as
200 * updating a GUI or handling other connections.
201 *
202 * @note This function uses select for simplicity and portability. Depending
203 * on your application's requirements, you might consider using other
204 * mechanisms like poll or epoll for handling multiple file descriptors.
205 */
wait_for_activity(SSL * ssl)206 static void wait_for_activity(SSL *ssl)
207 {
208 int sock, isinfinite;
209 fd_set read_fd, write_fd;
210 struct timeval tv;
211 struct timeval *tvp = NULL;
212
213 /* Get hold of the underlying file descriptor for the socket */
214 if ((sock = SSL_get_fd(ssl)) == -1) {
215 fprintf(stderr, "Unable to get file descriptor");
216 return;
217 }
218
219 /* Initialize the fd_set structure */
220 FD_ZERO(&read_fd);
221 FD_ZERO(&write_fd);
222
223 /*
224 * Determine if we would like to write to the socket, read from it, or both.
225 */
226 if (SSL_net_write_desired(ssl))
227 FD_SET(sock, &write_fd);
228 if (SSL_net_read_desired(ssl))
229 FD_SET(sock, &read_fd);
230
231 /*
232 * Find out when OpenSSL would next like to be called, regardless of
233 * whether the state of the underlying socket has changed or not.
234 */
235 if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)
236 tvp = &tv;
237
238 /*
239 * Wait until the socket is writeable or readable. We use select here
240 * for the sake of simplicity and portability, but you could equally use
241 * poll/epoll or similar functions
242 *
243 * NOTE: For the purposes of this demonstration code this effectively
244 * makes this demo block until it has something more useful to do. In a
245 * real application you probably want to go and do other work here (e.g.
246 * update a GUI, or service other connections).
247 *
248 * Let's say for example that you want to update the progress counter on
249 * a GUI every 100ms. One way to do that would be to use the timeout in
250 * the last parameter to "select" below. If the tvp value is greater
251 * than 100ms then use 100ms instead. Then, when select returns, you
252 * check if it did so because of activity on the file descriptors or
253 * because of the timeout. If the 100ms GUI timeout has expired but the
254 * tvp timeout has not then go and update the GUI and then restart the
255 * "select" (with updated timeouts).
256 */
257
258 select(sock + 1, &read_fd, &write_fd, NULL, tvp);
259 }
260
261 /**
262 * @brief Handles I/O failures on an SSL connection based on the result code.
263 *
264 * This function processes the result of an SSL I/O operation and handles
265 * different types of errors that may occur during the operation. It takes
266 * appropriate actions such as retrying the operation, reporting errors, or
267 * returning specific status codes based on the error type.
268 *
269 * @param ssl A pointer to the SSL object representing the connection.
270 * @param res The result code from the SSL I/O operation.
271 * @return An integer indicating the outcome:
272 * - 1: Temporary failure, the operation should be retried.
273 * - 0: EOF, indicating the connection has been closed.
274 * - -1: A fatal error occurred or the connection has been reset.
275 *
276 * @note This function may block if a temporary failure occurs and
277 * wait_for_activity() is called.
278 *
279 * @note If the failure is due to an SSL verification error, additional
280 * information will be logged to stderr.
281 */
handle_io_failure(SSL * ssl,int res)282 static int handle_io_failure(SSL *ssl, int res)
283 {
284 switch (SSL_get_error(ssl, res)) {
285 case SSL_ERROR_WANT_READ:
286 case SSL_ERROR_WANT_WRITE:
287 /* Temporary failure. Wait until we can read/write and try again */
288 wait_for_activity(ssl);
289 return 1;
290
291 case SSL_ERROR_ZERO_RETURN:
292 case SSL_ERROR_NONE:
293 /* EOF */
294 return 0;
295
296 case SSL_ERROR_SYSCALL:
297 return -1;
298
299 case SSL_ERROR_SSL:
300 /*
301 * Some stream fatal error occurred. This could be because of a
302 * stream reset - or some failure occurred on the underlying
303 * connection.
304 */
305 switch (SSL_get_stream_read_state(ssl)) {
306 case SSL_STREAM_STATE_RESET_REMOTE:
307 printf("Stream reset occurred\n");
308 /*
309 * The stream has been reset but the connection is still
310 * healthy.
311 */
312 break;
313
314 case SSL_STREAM_STATE_CONN_CLOSED:
315 printf("Connection closed\n");
316 /* Connection is already closed. */
317 break;
318
319 default:
320 printf("Unknown stream failure\n");
321 break;
322 }
323 /*
324 * If the failure is due to a verification error we can get more
325 * information about it from SSL_get_verify_result().
326 */
327 if (SSL_get_verify_result(ssl) != X509_V_OK)
328 printf("Verify error: %s\n",
329 X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
330 return -1;
331
332 default:
333 return -1;
334 }
335 }
336
337 /*
338 * Main loop for server to accept QUIC connections.
339 * Echo every request back to the client.
340 */
run_quic_server(SSL_CTX * ctx,int fd)341 static int run_quic_server(SSL_CTX *ctx, int fd)
342 {
343 int ok = -1;
344 int ret, eof;
345 SSL *listener, *conn = NULL;
346 unsigned char buf[8192];
347 size_t nread, total_read, total_written;
348
349 /* Create a new QUIC listener */
350 if ((listener = SSL_new_listener(ctx, 0)) == NULL)
351 goto err;
352
353 /* Provide the listener with our UDP socket. */
354 if (!SSL_set_fd(listener, fd))
355 goto err;
356
357 /*
358 * Set the listener mode to non-blocking, which is inherited by
359 * child objects.
360 */
361 if (!SSL_set_blocking_mode(listener, 0))
362 goto err;
363
364 /*
365 * Begin listening. Note that is not usually needed as SSL_accept_connection
366 * will implicitly start listening. It is only needed if a server wishes to
367 * ensure it has started to accept incoming connections but does not wish to
368 * actually call SSL_accept_connection yet.
369 */
370 if (!SSL_listen(listener))
371 goto err;
372
373 /*
374 * Begin an infinite loop of listening for connections. We will only
375 * exit this loop if we encounter an error.
376 */
377 for (;;) {
378 eof = 0;
379 total_read = 0;
380 total_written = 0;
381
382 /* Pristine error stack for each new connection */
383 ERR_clear_error();
384
385 /* Block while waiting for a client connection */
386 printf("Waiting for connection\n");
387 while ((conn = SSL_accept_connection(listener, 0)) == NULL)
388 wait_for_activity(listener);
389 printf("Accepted new connection\n");
390
391 /* Read from client until the client sends a end of stream packet */
392 while (!eof) {
393 ret = SSL_read_ex(conn, buf + total_read, sizeof(buf) - total_read,
394 &nread);
395 total_read += nread;
396 if (total_read >= 8192) {
397 fprintf(stderr, "Could not fit all data into buffer\n");
398 goto err;
399 }
400
401 switch (handle_io_failure(conn, ret)) {
402 case 1:
403 continue; /* Retry */
404 case 0:
405 /* Reached end of stream */
406 if (!SSL_has_pending(conn))
407 eof = 1;
408 break;
409 default:
410 fprintf(stderr, "Failed reading remaining data\n");
411 goto err;
412 }
413 }
414
415 /* Echo client input */
416 while (!SSL_write_ex2(conn, buf,
417 total_read,
418 SSL_WRITE_FLAG_CONCLUDE, &total_written)) {
419 if (handle_io_failure(conn, 0) == 1)
420 continue;
421 fprintf(stderr, "Failed to write data\n");
422 goto err;
423 }
424
425 if (total_read != total_written)
426 fprintf(stderr, "Failed to echo data [read: %lu, written: %lu]\n",
427 total_read, total_written);
428
429 /*
430 * Shut down the connection. We may need to call this multiple times
431 * to ensure the connection is shutdown completely.
432 */
433 while ((ret = SSL_shutdown(conn)) != 1) {
434 if (ret < 0 && handle_io_failure(conn, ret) == 1)
435 continue; /* Retry */
436 }
437
438 SSL_free(conn);
439 }
440
441 ok = EXIT_SUCCESS;
442 err:
443 SSL_free(listener);
444 return ok;
445 }
446
447 /* Minimal QUIC HTTP/1.0 server. */
main(int argc,char * argv[])448 int main(int argc, char *argv[])
449 {
450 int res = EXIT_FAILURE;
451 SSL_CTX *ctx = NULL;
452 int fd;
453 unsigned long port;
454
455 #ifdef _WIN32
456 progname = argv[0];
457 #endif
458
459 if (argc != 4)
460 errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]);
461
462 /* Create SSL_CTX that supports QUIC. */
463 if ((ctx = create_ctx(argv[2], argv[3])) == NULL) {
464 ERR_print_errors_fp(stderr);
465 errx(res, "Failed to create context");
466 }
467
468 /* Parse port number from command line arguments. */
469 port = strtoul(argv[1], NULL, 0);
470 if (port == 0 || port > UINT16_MAX) {
471 SSL_CTX_free(ctx);
472 errx(res, "Failed to parse port number");
473 }
474
475 /* Create and bind a UDP socket. */
476 if ((fd = create_socket((uint16_t)port)) < 0) {
477 SSL_CTX_free(ctx);
478 ERR_print_errors_fp(stderr);
479 errx(res, "Failed to create socket");
480 }
481
482 /* QUIC server connection acceptance loop. */
483 if (run_quic_server(ctx, fd) < 0) {
484 SSL_CTX_free(ctx);
485 BIO_closesocket(fd);
486 ERR_print_errors_fp(stderr);
487 errx(res, "Error in QUIC server loop");
488 }
489
490 /* Free resources. */
491 SSL_CTX_free(ctx);
492 BIO_closesocket(fd);
493 res = EXIT_SUCCESS;
494 return res;
495 }
496