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, '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 */ 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. */ 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. */ 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 goto err; 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 goto err; 176 } 177 178 return fd; 179 180 err: 181 BIO_closesocket(fd); 182 return -1; 183 } 184 185 /* 186 * Main loop for server to accept QUIC connections. 187 * Echo every request back to the client. 188 */ 189 static int run_quic_server(SSL_CTX *ctx, int fd) 190 { 191 int ok = 0; 192 SSL *listener, *conn; 193 unsigned char buf[8192]; 194 size_t nread; 195 size_t nwritten; 196 197 /* 198 * Create a new QUIC listener. Listeners, and other QUIC objects, default 199 * to operating in blocking mode. The configured behaviour is inherited by 200 * child objects. 201 */ 202 if ((listener = SSL_new_listener(ctx, 0)) == NULL) 203 goto err; 204 205 /* Provide the listener with our UDP socket. */ 206 if (!SSL_set_fd(listener, fd)) 207 goto err; 208 209 /* Begin listening. */ 210 if (!SSL_listen(listener)) 211 goto err; 212 213 /* 214 * Begin an infinite loop of listening for connections. We will only 215 * exit this loop if we encounter an error. 216 */ 217 for (;;) { 218 /* Pristine error stack for each new connection */ 219 ERR_clear_error(); 220 221 /* Block while waiting for a client connection */ 222 printf("Waiting for connection\n"); 223 conn = SSL_accept_connection(listener, 0); 224 if (conn == NULL) { 225 fprintf(stderr, "error while accepting connection\n"); 226 goto err; 227 } 228 printf("Accepted new connection\n"); 229 230 /* Echo client input */ 231 while (SSL_read_ex(conn, buf, sizeof(buf), &nread) > 0) { 232 if (SSL_write_ex(conn, buf, nread, &nwritten) > 0 233 && nwritten == nread) 234 continue; 235 fprintf(stderr, "Error echoing client input"); 236 break; 237 } 238 239 /* Signal the end of the stream. */ 240 if (SSL_stream_conclude(conn, 0) != 1) { 241 fprintf(stderr, "Unable to conclude stream\n"); 242 SSL_free(conn); 243 goto err; 244 } 245 246 /* 247 * Shut down the connection. We may need to call this multiple times 248 * to ensure the connection is shutdown completely. 249 */ 250 while (SSL_shutdown(conn) != 1) 251 continue; 252 253 SSL_free(conn); 254 } 255 256 err: 257 SSL_free(listener); 258 return ok; 259 } 260 261 /* Minimal QUIC HTTP/1.0 server. */ 262 int main(int argc, char *argv[]) 263 { 264 int res = EXIT_FAILURE; 265 SSL_CTX *ctx = NULL; 266 int fd; 267 unsigned long port; 268 #ifdef _WIN32 269 static const char *progname; 270 271 progname = argv[0]; 272 #endif 273 274 if (argc != 4) 275 errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]); 276 277 /* Create SSL_CTX that supports QUIC. */ 278 if ((ctx = create_ctx(argv[2], argv[3])) == NULL) { 279 ERR_print_errors_fp(stderr); 280 errx(res, "Failed to create context"); 281 } 282 283 /* Parse port number from command line arguments. */ 284 port = strtoul(argv[1], NULL, 0); 285 if (port == 0 || port > UINT16_MAX) { 286 SSL_CTX_free(ctx); 287 errx(res, "Failed to parse port number"); 288 } 289 290 /* Create and bind a UDP socket. */ 291 if ((fd = create_socket((uint16_t)port)) < 0) { 292 SSL_CTX_free(ctx); 293 ERR_print_errors_fp(stderr); 294 errx(res, "Failed to create socket"); 295 } 296 297 /* QUIC server connection acceptance loop. */ 298 if (!run_quic_server(ctx, fd)) { 299 SSL_CTX_free(ctx); 300 BIO_closesocket(fd); 301 ERR_print_errors_fp(stderr); 302 errx(res, "Error in QUIC server loop"); 303 } 304 305 /* Free resources. */ 306 SSL_CTX_free(ctx); 307 BIO_closesocket(fd); 308 res = EXIT_SUCCESS; 309 return res; 310 } 311