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-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 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 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 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, 71 'h', 72 't', 73 't', 74 'p', 75 '/', 76 '1', 77 '.', 78 '0', 79 10, 80 'h', 81 'q', 82 '-', 83 'i', 84 'n', 85 't', 86 'e', 87 'r', 88 'o', 89 'p', 90 }; 91 92 /* 93 * This callback validates and negotiates the desired ALPN on the server side. 94 */ 95 static int select_alpn(SSL *ssl, const unsigned char **out, 96 unsigned char *out_len, const unsigned char *in, 97 unsigned int in_len, void *arg) 98 { 99 if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest, 100 sizeof(alpn_ossltest), in, 101 in_len) 102 == OPENSSL_NPN_NEGOTIATED) 103 return SSL_TLSEXT_ERR_OK; 104 return SSL_TLSEXT_ERR_ALERT_FATAL; 105 } 106 107 /* Create SSL_CTX. */ 108 static SSL_CTX *create_ctx(const char *cert_path, const char *key_path) 109 { 110 SSL_CTX *ctx; 111 112 /* 113 * An SSL_CTX holds shared configuration information for multiple 114 * subsequent per-client connections. We specifically load a QUIC 115 * server method here. 116 */ 117 ctx = SSL_CTX_new(OSSL_QUIC_server_method()); 118 if (ctx == NULL) 119 goto err; 120 121 /* 122 * Load the server's certificate *chain* file (PEM format), which includes 123 * not only the leaf (end-entity) server certificate, but also any 124 * intermediate issuer-CA certificates. The leaf certificate must be the 125 * first certificate in the file. 126 * 127 * In advanced use-cases this can be called multiple times, once per public 128 * key algorithm for which the server has a corresponding certificate. 129 * However, the corresponding private key (see below) must be loaded first, 130 * *before* moving on to the next chain file. 131 * 132 * The requisite files "chain.pem" and "pkey.pem" can be generated by running 133 * "make chain" in this directory. If the server will be executed from some 134 * other directory, move or copy the files there. 135 */ 136 if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) { 137 fprintf(stderr, "couldn't load certificate file: %s\n", cert_path); 138 goto err; 139 } 140 141 /* 142 * Load the corresponding private key, this also checks that the private 143 * key matches the just loaded end-entity certificate. It does not check 144 * whether the certificate chain is valid, the certificates could be 145 * expired, or may otherwise fail to form a chain that a client can validate. 146 */ 147 if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) { 148 fprintf(stderr, "couldn't load key file: %s\n", key_path); 149 goto err; 150 } 151 152 /* 153 * Clients rarely employ certificate-based authentication, and so we don't 154 * require "mutual" TLS authentication (indeed there's no way to know 155 * whether or how the client authenticated the server, so the term "mutual" 156 * is potentially misleading). 157 * 158 * Since we're not soliciting or processing client certificates, we don't 159 * need to configure a trusted-certificate store, so no call to 160 * SSL_CTX_set_default_verify_paths() is needed. The server's own 161 * certificate chain is assumed valid. 162 */ 163 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); 164 165 /* Setup ALPN negotiation callback to decide which ALPN is accepted. */ 166 SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL); 167 168 return ctx; 169 170 err: 171 SSL_CTX_free(ctx); 172 return NULL; 173 } 174 175 /* Create UDP socket on the given port. */ 176 static int create_socket(uint16_t port) 177 { 178 int fd; 179 struct sockaddr_in sa = { 0 }; 180 181 /* Retrieve the file descriptor for a new UDP socket */ 182 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { 183 fprintf(stderr, "cannot create socket"); 184 goto err; 185 } 186 187 sa.sin_family = AF_INET; 188 sa.sin_port = htons(port); 189 190 /* Bind to the new UDP socket on localhost */ 191 if (bind(fd, (const struct sockaddr *)&sa, sizeof(sa)) < 0) { 192 fprintf(stderr, "cannot bind to %u\n", port); 193 BIO_closesocket(fd); 194 goto err; 195 } 196 197 return fd; 198 199 err: 200 BIO_closesocket(fd); 201 return -1; 202 } 203 204 /* 205 * Main loop for server to accept QUIC connections. 206 * Echo every request back to the client. 207 */ 208 static int run_quic_server(SSL_CTX *ctx, int fd) 209 { 210 int ok = 0; 211 SSL *listener, *conn; 212 unsigned char buf[8192]; 213 size_t nread; 214 size_t nwritten; 215 216 /* 217 * Create a new QUIC listener. Listeners, and other QUIC objects, default 218 * to operating in blocking mode. The configured behaviour is inherited by 219 * child objects. 220 */ 221 if ((listener = SSL_new_listener(ctx, 0)) == NULL) 222 goto err; 223 224 /* Provide the listener with our UDP socket. */ 225 if (!SSL_set_fd(listener, fd)) 226 goto err; 227 228 /* Begin listening. */ 229 if (!SSL_listen(listener)) 230 goto err; 231 232 /* 233 * Begin an infinite loop of listening for connections. We will only 234 * exit this loop if we encounter an error. 235 */ 236 for (;;) { 237 /* Pristine error stack for each new connection */ 238 ERR_clear_error(); 239 240 /* Block while waiting for a client connection */ 241 printf("Waiting for connection\n"); 242 conn = SSL_accept_connection(listener, 0); 243 if (conn == NULL) { 244 fprintf(stderr, "error while accepting connection\n"); 245 goto err; 246 } 247 printf("Accepted new connection\n"); 248 249 /* Echo client input */ 250 while (SSL_read_ex(conn, buf, sizeof(buf), &nread) > 0) { 251 if (SSL_write_ex(conn, buf, nread, &nwritten) > 0 252 && nwritten == nread) 253 continue; 254 fprintf(stderr, "Error echoing client input"); 255 break; 256 } 257 258 /* Signal the end of the stream. */ 259 if (SSL_stream_conclude(conn, 0) != 1) { 260 fprintf(stderr, "Unable to conclude stream\n"); 261 SSL_free(conn); 262 goto err; 263 } 264 265 /* 266 * Shut down the connection. We may need to call this multiple times 267 * to ensure the connection is shutdown completely. 268 */ 269 while (SSL_shutdown(conn) != 1) 270 continue; 271 272 SSL_free(conn); 273 } 274 275 err: 276 SSL_free(listener); 277 return ok; 278 } 279 280 /* Minimal QUIC HTTP/1.0 server. */ 281 int main(int argc, char *argv[]) 282 { 283 int res = EXIT_FAILURE; 284 SSL_CTX *ctx = NULL; 285 int fd; 286 unsigned long port; 287 #ifdef _WIN32 288 static const char *progname; 289 290 progname = argv[0]; 291 #endif 292 293 if (argc != 4) 294 errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]); 295 296 /* Create SSL_CTX that supports QUIC. */ 297 if ((ctx = create_ctx(argv[2], argv[3])) == NULL) { 298 ERR_print_errors_fp(stderr); 299 errx(res, "Failed to create context"); 300 } 301 302 /* Parse port number from command line arguments. */ 303 port = strtoul(argv[1], NULL, 0); 304 if (port == 0 || port > UINT16_MAX) { 305 SSL_CTX_free(ctx); 306 errx(res, "Failed to parse port number"); 307 } 308 309 /* Create and bind a UDP socket. */ 310 if ((fd = create_socket((uint16_t)port)) < 0) { 311 SSL_CTX_free(ctx); 312 ERR_print_errors_fp(stderr); 313 errx(res, "Failed to create socket"); 314 } 315 316 /* QUIC server connection acceptance loop. */ 317 if (!run_quic_server(ctx, fd)) { 318 SSL_CTX_free(ctx); 319 BIO_closesocket(fd); 320 ERR_print_errors_fp(stderr); 321 errx(res, "Error in QUIC server loop"); 322 } 323 324 /* Free resources. */ 325 SSL_CTX_free(ctx); 326 BIO_closesocket(fd); 327 res = EXIT_SUCCESS; 328 return res; 329 } 330