xref: /freebsd/crypto/openssl/demos/guide/tls-server-block.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1*e7be843bSPierre Pronchery /*
2*e7be843bSPierre Pronchery  *  Copyright 2024 The OpenSSL Project Authors. All Rights Reserved.
3*e7be843bSPierre Pronchery  *
4*e7be843bSPierre Pronchery  *  Licensed under the Apache License 2.0 (the "License").  You may not use
5*e7be843bSPierre Pronchery  *  this file except in compliance with the License.  You can obtain a copy
6*e7be843bSPierre Pronchery  *  in the file LICENSE in the source distribution or at
7*e7be843bSPierre Pronchery  *  https://www.openssl.org/source/license.html
8*e7be843bSPierre Pronchery  */
9*e7be843bSPierre Pronchery 
10*e7be843bSPierre Pronchery /*
11*e7be843bSPierre Pronchery  * NB: Changes to this file should also be reflected in
12*e7be843bSPierre Pronchery  * doc/man7/ossl-guide-tls-server-block.pod
13*e7be843bSPierre Pronchery  */
14*e7be843bSPierre Pronchery 
15*e7be843bSPierre Pronchery #include <string.h>
16*e7be843bSPierre Pronchery 
17*e7be843bSPierre Pronchery /* Include the appropriate header file for SOCK_STREAM */
18*e7be843bSPierre Pronchery #ifdef _WIN32 /* Windows */
19*e7be843bSPierre Pronchery # include <stdarg.h>
20*e7be843bSPierre Pronchery # include <winsock2.h>
21*e7be843bSPierre Pronchery #else /* Linux/Unix */
22*e7be843bSPierre Pronchery # include <err.h>
23*e7be843bSPierre Pronchery # include <sys/socket.h>
24*e7be843bSPierre Pronchery # include <sys/select.h>
25*e7be843bSPierre Pronchery #endif
26*e7be843bSPierre Pronchery 
27*e7be843bSPierre Pronchery #include <openssl/bio.h>
28*e7be843bSPierre Pronchery #include <openssl/ssl.h>
29*e7be843bSPierre Pronchery #include <openssl/err.h>
30*e7be843bSPierre Pronchery 
31*e7be843bSPierre Pronchery static const char cache_id[] = "OpenSSL Demo Server";
32*e7be843bSPierre Pronchery 
33*e7be843bSPierre Pronchery #ifdef _WIN32
34*e7be843bSPierre Pronchery static const char *progname;
35*e7be843bSPierre Pronchery 
vwarnx(const char * fmt,va_list ap)36*e7be843bSPierre Pronchery static void vwarnx(const char *fmt, va_list ap)
37*e7be843bSPierre Pronchery {
38*e7be843bSPierre Pronchery     if (progname != NULL)
39*e7be843bSPierre Pronchery         fprintf(stderr, "%s: ", progname);
40*e7be843bSPierre Pronchery     vfprintf(stderr, fmt, ap);
41*e7be843bSPierre Pronchery     putc('\n', stderr);
42*e7be843bSPierre Pronchery }
43*e7be843bSPierre Pronchery 
errx(int status,const char * fmt,...)44*e7be843bSPierre Pronchery static void errx(int status, const char *fmt, ...)
45*e7be843bSPierre Pronchery {
46*e7be843bSPierre Pronchery     va_list ap;
47*e7be843bSPierre Pronchery     va_start(ap, fmt);
48*e7be843bSPierre Pronchery     vwarnx(fmt, ap);
49*e7be843bSPierre Pronchery     va_end(ap);
50*e7be843bSPierre Pronchery     exit(status);
51*e7be843bSPierre Pronchery }
52*e7be843bSPierre Pronchery 
warnx(const char * fmt,...)53*e7be843bSPierre Pronchery static void warnx(const char *fmt, ...)
54*e7be843bSPierre Pronchery {
55*e7be843bSPierre Pronchery     va_list ap;
56*e7be843bSPierre Pronchery     va_start(ap, fmt);
57*e7be843bSPierre Pronchery     vwarnx(fmt, ap);
58*e7be843bSPierre Pronchery     va_end(ap);
59*e7be843bSPierre Pronchery }
60*e7be843bSPierre Pronchery #endif
61*e7be843bSPierre Pronchery 
62*e7be843bSPierre Pronchery /* Minimal TLS echo server. */
main(int argc,char * argv[])63*e7be843bSPierre Pronchery int main(int argc, char *argv[])
64*e7be843bSPierre Pronchery {
65*e7be843bSPierre Pronchery     int res = EXIT_FAILURE;
66*e7be843bSPierre Pronchery     long opts;
67*e7be843bSPierre Pronchery     const char *hostport;
68*e7be843bSPierre Pronchery     SSL_CTX *ctx = NULL;
69*e7be843bSPierre Pronchery     BIO *acceptor_bio;
70*e7be843bSPierre Pronchery 
71*e7be843bSPierre Pronchery #ifdef _WIN32
72*e7be843bSPierre Pronchery     progname = argv[0];
73*e7be843bSPierre Pronchery #endif
74*e7be843bSPierre Pronchery 
75*e7be843bSPierre Pronchery     if (argc != 2)
76*e7be843bSPierre Pronchery         errx(res, "Usage: %s [host:]port", argv[0]);
77*e7be843bSPierre Pronchery     hostport = argv[1];
78*e7be843bSPierre Pronchery 
79*e7be843bSPierre Pronchery     /*
80*e7be843bSPierre Pronchery      * An SSL_CTX holds shared configuration information for multiple
81*e7be843bSPierre Pronchery      * subsequent per-client SSL connections.
82*e7be843bSPierre Pronchery      */
83*e7be843bSPierre Pronchery     ctx = SSL_CTX_new(TLS_server_method());
84*e7be843bSPierre Pronchery     if (ctx == NULL) {
85*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
86*e7be843bSPierre Pronchery         errx(res, "Failed to create server SSL_CTX");
87*e7be843bSPierre Pronchery     }
88*e7be843bSPierre Pronchery 
89*e7be843bSPierre Pronchery     /*
90*e7be843bSPierre Pronchery      * TLS versions older than TLS 1.2 are deprecated by IETF and SHOULD
91*e7be843bSPierre Pronchery      * be avoided if possible.
92*e7be843bSPierre Pronchery      */
93*e7be843bSPierre Pronchery     if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
94*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
95*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
96*e7be843bSPierre Pronchery         errx(res, "Failed to set the minimum TLS protocol version");
97*e7be843bSPierre Pronchery     }
98*e7be843bSPierre Pronchery 
99*e7be843bSPierre Pronchery #if 0
100*e7be843bSPierre Pronchery     /*
101*e7be843bSPierre Pronchery      * In applications (e.g. SMTP) where most clients are performing
102*e7be843bSPierre Pronchery      * unauthenticated opportunistic TLS it may make sense to set the security
103*e7be843bSPierre Pronchery      * level to 0, allowing weaker encryption parameters, which are still
104*e7be843bSPierre Pronchery      * stronger than a potential cleartext fallback.
105*e7be843bSPierre Pronchery      *
106*e7be843bSPierre Pronchery      * The default security level is 2 (as of OpenSSL 3.2), which is roughly
107*e7be843bSPierre Pronchery      * equivalent to that of 112 bit symmetric keys, or 2048-bit RSA or
108*e7be843bSPierre Pronchery      * finite-field Diffie-Hellman keys.  Notably, non-zero security levels no
109*e7be843bSPierre Pronchery      * longer allow the use of SHA-1 in certificate signatures, key exchange
110*e7be843bSPierre Pronchery      * or in the TLS 1.[01] PRF (so TLS 1.0 and 1.1 require security level 0).
111*e7be843bSPierre Pronchery      */
112*e7be843bSPierre Pronchery     SSL_CTX_set_security_level(ctx, 0);
113*e7be843bSPierre Pronchery #endif
114*e7be843bSPierre Pronchery 
115*e7be843bSPierre Pronchery     /*
116*e7be843bSPierre Pronchery      * Tolerate clients hanging up without a TLS "shutdown".  Appropriate in all
117*e7be843bSPierre Pronchery      * application protocols which perform their own message "framing", and
118*e7be843bSPierre Pronchery      * don't rely on TLS to defend against "truncation" attacks.
119*e7be843bSPierre Pronchery      */
120*e7be843bSPierre Pronchery     opts = SSL_OP_IGNORE_UNEXPECTED_EOF;
121*e7be843bSPierre Pronchery 
122*e7be843bSPierre Pronchery     /*
123*e7be843bSPierre Pronchery      * Block potential CPU-exhaustion attacks by clients that request frequent
124*e7be843bSPierre Pronchery      * renegotiation.  This is of course only effective if there are existing
125*e7be843bSPierre Pronchery      * limits on initial full TLS handshake or connection rates.
126*e7be843bSPierre Pronchery      */
127*e7be843bSPierre Pronchery     opts |= SSL_OP_NO_RENEGOTIATION;
128*e7be843bSPierre Pronchery 
129*e7be843bSPierre Pronchery     /*
130*e7be843bSPierre Pronchery      * Most servers elect to use their own cipher preference rather than that of
131*e7be843bSPierre Pronchery      * the client.
132*e7be843bSPierre Pronchery      */
133*e7be843bSPierre Pronchery     opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
134*e7be843bSPierre Pronchery 
135*e7be843bSPierre Pronchery     /* Apply the selection options */
136*e7be843bSPierre Pronchery     SSL_CTX_set_options(ctx, opts);
137*e7be843bSPierre Pronchery 
138*e7be843bSPierre Pronchery     /*
139*e7be843bSPierre Pronchery      * Load the server's certificate *chain* file (PEM format), which includes
140*e7be843bSPierre Pronchery      * not only the leaf (end-entity) server certificate, but also any
141*e7be843bSPierre Pronchery      * intermediate issuer-CA certificates.  The leaf certificate must be the
142*e7be843bSPierre Pronchery      * first certificate in the file.
143*e7be843bSPierre Pronchery      *
144*e7be843bSPierre Pronchery      * In advanced use-cases this can be called multiple times, once per public
145*e7be843bSPierre Pronchery      * key algorithm for which the server has a corresponding certificate.
146*e7be843bSPierre Pronchery      * However, the corresponding private key (see below) must be loaded first,
147*e7be843bSPierre Pronchery      * *before* moving on to the next chain file.
148*e7be843bSPierre Pronchery      *
149*e7be843bSPierre Pronchery      * The requisite files "chain.pem" and "pkey.pem" can be generated by running
150*e7be843bSPierre Pronchery      * "make chain" in this directory.  If the server will be executed from some
151*e7be843bSPierre Pronchery      * other directory, move or copy the files there.
152*e7be843bSPierre Pronchery      */
153*e7be843bSPierre Pronchery     if (SSL_CTX_use_certificate_chain_file(ctx, "chain.pem") <= 0) {
154*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
155*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
156*e7be843bSPierre Pronchery         errx(res, "Failed to load the server certificate chain file");
157*e7be843bSPierre Pronchery     }
158*e7be843bSPierre Pronchery 
159*e7be843bSPierre Pronchery     /*
160*e7be843bSPierre Pronchery      * Load the corresponding private key, this also checks that the private
161*e7be843bSPierre Pronchery      * key matches the just loaded end-entity certificate.  It does not check
162*e7be843bSPierre Pronchery      * whether the certificate chain is valid, the certificates could be
163*e7be843bSPierre Pronchery      * expired, or may otherwise fail to form a chain that a client can validate.
164*e7be843bSPierre Pronchery      */
165*e7be843bSPierre Pronchery     if (SSL_CTX_use_PrivateKey_file(ctx, "pkey.pem", SSL_FILETYPE_PEM) <= 0) {
166*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
167*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
168*e7be843bSPierre Pronchery         errx(res, "Error loading the server private key file, "
169*e7be843bSPierre Pronchery                   "possible key/cert mismatch???");
170*e7be843bSPierre Pronchery     }
171*e7be843bSPierre Pronchery 
172*e7be843bSPierre Pronchery     /*
173*e7be843bSPierre Pronchery      * Servers that want to enable session resumption must specify a cache id
174*e7be843bSPierre Pronchery      * byte array, that identifies the server application, and reduces the
175*e7be843bSPierre Pronchery      * chance of inappropriate cache sharing.
176*e7be843bSPierre Pronchery      */
177*e7be843bSPierre Pronchery     SSL_CTX_set_session_id_context(ctx, (void *)cache_id, sizeof(cache_id));
178*e7be843bSPierre Pronchery     SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
179*e7be843bSPierre Pronchery 
180*e7be843bSPierre Pronchery     /*
181*e7be843bSPierre Pronchery      * How many client TLS sessions to cache.  The default is
182*e7be843bSPierre Pronchery      * SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (20k in recent OpenSSL versions),
183*e7be843bSPierre Pronchery      * which may be too small or too large.
184*e7be843bSPierre Pronchery      */
185*e7be843bSPierre Pronchery     SSL_CTX_sess_set_cache_size(ctx, 1024);
186*e7be843bSPierre Pronchery 
187*e7be843bSPierre Pronchery     /*
188*e7be843bSPierre Pronchery      * Sessions older than this are considered a cache miss even if still in
189*e7be843bSPierre Pronchery      * the cache.  The default is two hours.  Busy servers whose clients make
190*e7be843bSPierre Pronchery      * many connections in a short burst may want a shorter timeout, on lightly
191*e7be843bSPierre Pronchery      * loaded servers with sporadic connections from any given client, a longer
192*e7be843bSPierre Pronchery      * time may be appropriate.
193*e7be843bSPierre Pronchery      */
194*e7be843bSPierre Pronchery     SSL_CTX_set_timeout(ctx, 3600);
195*e7be843bSPierre Pronchery 
196*e7be843bSPierre Pronchery     /*
197*e7be843bSPierre Pronchery      * Clients rarely employ certificate-based authentication, and so we don't
198*e7be843bSPierre Pronchery      * require "mutual" TLS authentication (indeed there's no way to know
199*e7be843bSPierre Pronchery      * whether or how the client authenticated the server, so the term "mutual"
200*e7be843bSPierre Pronchery      * is potentially misleading).
201*e7be843bSPierre Pronchery      *
202*e7be843bSPierre Pronchery      * Since we're not soliciting or processing client certificates, we don't
203*e7be843bSPierre Pronchery      * need to configure a trusted-certificate store, so no call to
204*e7be843bSPierre Pronchery      * SSL_CTX_set_default_verify_paths() is needed.  The server's own
205*e7be843bSPierre Pronchery      * certificate chain is assumed valid.
206*e7be843bSPierre Pronchery      */
207*e7be843bSPierre Pronchery     SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
208*e7be843bSPierre Pronchery 
209*e7be843bSPierre Pronchery     /*
210*e7be843bSPierre Pronchery      * Create a listener socket wrapped in a BIO.
211*e7be843bSPierre Pronchery      * The first call to BIO_do_accept() initialises the socket
212*e7be843bSPierre Pronchery      */
213*e7be843bSPierre Pronchery     acceptor_bio = BIO_new_accept(hostport);
214*e7be843bSPierre Pronchery     if (acceptor_bio == NULL) {
215*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
216*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
217*e7be843bSPierre Pronchery         errx(res, "Error creating acceptor bio");
218*e7be843bSPierre Pronchery     }
219*e7be843bSPierre Pronchery 
220*e7be843bSPierre Pronchery     BIO_set_bind_mode(acceptor_bio, BIO_BIND_REUSEADDR);
221*e7be843bSPierre Pronchery     if (BIO_do_accept(acceptor_bio) <= 0) {
222*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
223*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
224*e7be843bSPierre Pronchery         errx(res, "Error setting up acceptor socket");
225*e7be843bSPierre Pronchery     }
226*e7be843bSPierre Pronchery 
227*e7be843bSPierre Pronchery     /* Wait for incoming connection */
228*e7be843bSPierre Pronchery     for (;;) {
229*e7be843bSPierre Pronchery         BIO *client_bio;
230*e7be843bSPierre Pronchery         SSL *ssl;
231*e7be843bSPierre Pronchery         unsigned char buf[8192];
232*e7be843bSPierre Pronchery         size_t nread;
233*e7be843bSPierre Pronchery         size_t nwritten;
234*e7be843bSPierre Pronchery         size_t total = 0;
235*e7be843bSPierre Pronchery 
236*e7be843bSPierre Pronchery         /* Pristine error stack for each new connection */
237*e7be843bSPierre Pronchery         ERR_clear_error();
238*e7be843bSPierre Pronchery 
239*e7be843bSPierre Pronchery         /* Wait for the next client to connect */
240*e7be843bSPierre Pronchery         if (BIO_do_accept(acceptor_bio) <= 0) {
241*e7be843bSPierre Pronchery             /* Client went away before we accepted the connection */
242*e7be843bSPierre Pronchery             continue;
243*e7be843bSPierre Pronchery         }
244*e7be843bSPierre Pronchery 
245*e7be843bSPierre Pronchery         /* Pop the client connection from the BIO chain */
246*e7be843bSPierre Pronchery         client_bio = BIO_pop(acceptor_bio);
247*e7be843bSPierre Pronchery         fprintf(stderr, "New client connection accepted\n");
248*e7be843bSPierre Pronchery 
249*e7be843bSPierre Pronchery         /* Associate a new SSL handle with the new connection */
250*e7be843bSPierre Pronchery         if ((ssl = SSL_new(ctx)) == NULL) {
251*e7be843bSPierre Pronchery             ERR_print_errors_fp(stderr);
252*e7be843bSPierre Pronchery             warnx("Error creating SSL handle for new connection");
253*e7be843bSPierre Pronchery             BIO_free(client_bio);
254*e7be843bSPierre Pronchery             continue;
255*e7be843bSPierre Pronchery         }
256*e7be843bSPierre Pronchery         SSL_set_bio(ssl, client_bio, client_bio);
257*e7be843bSPierre Pronchery 
258*e7be843bSPierre Pronchery         /* Attempt an SSL handshake with the client */
259*e7be843bSPierre Pronchery         if (SSL_accept(ssl) <= 0) {
260*e7be843bSPierre Pronchery             ERR_print_errors_fp(stderr);
261*e7be843bSPierre Pronchery             warnx("Error performing SSL handshake with client");
262*e7be843bSPierre Pronchery             SSL_free(ssl);
263*e7be843bSPierre Pronchery             continue;
264*e7be843bSPierre Pronchery         }
265*e7be843bSPierre Pronchery 
266*e7be843bSPierre Pronchery         while (SSL_read_ex(ssl, buf, sizeof(buf), &nread) > 0) {
267*e7be843bSPierre Pronchery             if (SSL_write_ex(ssl, buf, nread, &nwritten) > 0 &&
268*e7be843bSPierre Pronchery                 nwritten == nread) {
269*e7be843bSPierre Pronchery                 total += nwritten;
270*e7be843bSPierre Pronchery                 continue;
271*e7be843bSPierre Pronchery             }
272*e7be843bSPierre Pronchery             warnx("Error echoing client input");
273*e7be843bSPierre Pronchery             break;
274*e7be843bSPierre Pronchery         }
275*e7be843bSPierre Pronchery         fprintf(stderr, "Client connection closed, %zu bytes sent\n", total);
276*e7be843bSPierre Pronchery         SSL_free(ssl);
277*e7be843bSPierre Pronchery     }
278*e7be843bSPierre Pronchery 
279*e7be843bSPierre Pronchery     /*
280*e7be843bSPierre Pronchery      * Unreachable placeholder cleanup code, the above loop runs forever.
281*e7be843bSPierre Pronchery      */
282*e7be843bSPierre Pronchery     SSL_CTX_free(ctx);
283*e7be843bSPierre Pronchery     return EXIT_SUCCESS;
284*e7be843bSPierre Pronchery }
285