Debian Codegraph @

upstream/debian-unstable/man7/ossl-guide-tls-client-block.7ssl

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\" ========================================================================
56 .\"
57 .IX Title "OSSL-GUIDE-TLS-CLIENT-BLOCK 7SSL"
58 .TH OSSL-GUIDE-TLS-CLIENT-BLOCK 7SSL 2026-04-07 3.6.2 OpenSSL
59 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
60 .\" way too many mistakes in technical documents.
61 .if n .ad l
62 .nh
63 .SH NAME
64 ossl\-guide\-tls\-client\-block
65 \&\- OpenSSL Guide: Writing a simple blocking TLS client
66 .SH "SIMPLE BLOCKING TLS CLIENT EXAMPLE"
67 .IX Header "SIMPLE BLOCKING TLS CLIENT EXAMPLE"
68 This page will present various source code samples demonstrating how to write
69 a simple TLS client application which connects to a server, sends an HTTP/1.0
70 request to it, and reads back the response.
71 .PP
72 We use a blocking socket for the purposes of this example. This means that
73 attempting to read data from a socket that has no data available on it to read
74 will block (and the function will not return), until data becomes available.
75 For example, this can happen if we have sent our request, but we are still
76 waiting for the server's response. Similarly any attempts to write to a socket
77 that is not able to write at the moment will block until writing is possible.
78 .PP
79 This blocking behaviour simplifies the implementation of a client because you do
80 not have to worry about what happens if data is not yet available. The
81 application will simply wait until it is available.
82 .PP
83 The complete source code for this example blocking TLS client is available in
84 the \fBdemos/guide\fR directory of the OpenSSL source distribution in the file
85 \&\fBtls\-client\-block.c\fR. It is also available online at
86 <https://github.com/openssl/openssl/blob/master/demos/guide/tls\-client\-block.c>.
87 .PP
88 We assume that you already have OpenSSL installed on your system; that you
89 already have some fundamental understanding of OpenSSL concepts and TLS (see
90 \&\fBossl\-guide\-libraries\-introduction\fR\|(7) and \fBossl\-guide\-tls\-introduction\fR\|(7));
91 and that you know how to write and build C code and link it against the
92 libcrypto and libssl libraries that are provided by OpenSSL. It also assumes
93 that you have a basic understanding of TCP/IP and sockets.
94 .SS "Creating the SSL_CTX and SSL objects"
95 .IX Subsection "Creating the SSL_CTX and SSL objects"
96 The first step is to create an \fBSSL_CTX\fR object for our client. We use the
97 \&\fBSSL_CTX_new\fR\|(3) function for this purpose. We could alternatively use
98 \&\fBSSL_CTX_new_ex\fR\|(3) if we want to associate the \fBSSL_CTX\fR with a particular
99 \&\fBOSSL_LIB_CTX\fR (see \fBossl\-guide\-libraries\-introduction\fR\|(7) to learn about
100 \&\fBOSSL_LIB_CTX\fR). We pass as an argument the return value of the function
101 \&\fBTLS_client_method\fR\|(3). You should use this method whenever you are writing a
102 TLS client. This method will automatically use TLS version negotiation to select
103 the highest version of the protocol that is mutually supported by both the
104 client and the server.
105 .PP
106 .Vb 10
107 \& /*
108 \& * Create an SSL_CTX which we can use to create SSL objects from. We
109 \& * want an SSL_CTX for creating clients so we use TLS_client_method()
110 \& * here.
111 \& */
112 \& ctx = SSL_CTX_new(TLS_client_method());
113 \& if (ctx == NULL) {
114 \& printf("Failed to create the SSL_CTX\en");
115 \& goto end;
116 \& }
117 .Ve
118 .PP
119 Since we are writing a client we must ensure that we verify the server's
120 certificate. We do this by calling the \fBSSL_CTX_set_verify\fR\|(3) function and
121 pass the \fBSSL_VERIFY_PEER\fR value to it. The final argument to this function
122 is a callback that you can optionally supply to override the default handling
123 for certificate verification. Most applications do not need to do this so this
124 can safely be set to NULL to get the default handling.
125 .PP
126 .Vb 6
127 \& /*
128 \& * Configure the client to abort the handshake if certificate
129 \& * verification fails. Virtually all clients should do this unless you
130 \& * really know what you are doing.
131 \& */
132 \& SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
133 .Ve
134 .PP
135 In order for certificate verification to be successful you must have configured
136 where the trusted certificate store to be used is located (see
137 \&\fBossl\-guide\-tls\-introduction\fR\|(7)). In most cases you just want to use the
138 default store so we call \fBSSL_CTX_set_default_verify_paths\fR\|(3).
139 .PP
140 .Vb 5
141 \& /* Use the default trusted certificate store */
142 \& if (!SSL_CTX_set_default_verify_paths(ctx)) {
143 \& printf("Failed to set the default trusted certificate store\en");
144 \& goto end;
145 \& }
146 .Ve
147 .PP
148 We would also like to restrict the TLS versions that we are willing to accept to
149 TLSv1.2 or above. TLS protocol versions earlier than that are generally to be
150 avoided where possible. We can do that using
151 \&\fBSSL_CTX_set_min_proto_version\fR\|(3):
152 .PP
153 .Vb 8
154 \& /*
155 \& * TLSv1.1 or earlier are deprecated by IETF and are generally to be
156 \& * avoided if possible. We require a minimum TLS version of TLSv1.2.
157 \& */
158 \& if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
159 \& printf("Failed to set the minimum TLS protocol version\en");
160 \& goto end;
161 \& }
162 .Ve
163 .PP
164 That is all the setup that we need to do for the \fBSSL_CTX\fR, so next we need to
165 create an \fBSSL\fR object to represent the TLS connection. In a real application
166 we might expect to be creating more than one TLS connection over time. In that
167 case we would expect to reuse the \fBSSL_CTX\fR that we already created each time.
168 There is no need to repeat those steps. In fact it is best not to since certain
169 internal resources are cached in the \fBSSL_CTX\fR. You will get better performance
170 by reusing an existing \fBSSL_CTX\fR instead of creating a new one each time.
171 .PP
172 Creating the \fBSSL\fR object is a simple matter of calling the \fBSSL_new\|(3)\fR
173 function and passing the \fBSSL_CTX\fR we created as an argument.
174 .PP
175 .Vb 6
176 \& /* Create an SSL object to represent the TLS connection */
177 \& ssl = SSL_new(ctx);
178 \& if (ssl == NULL) {
179 \& printf("Failed to create the SSL object\en");
180 \& goto end;
181 \& }
182 .Ve
183 .SS "Creating the socket and BIO"
184 .IX Subsection "Creating the socket and BIO"
185 TLS data is transmitted over an underlying transport layer. Normally a TCP
186 socket. It is the application's responsibility for ensuring that the socket is
187 created and associated with an SSL object (via a BIO).
188 .PP
189 Socket creation for use by a client is typically a 2 step process, i.e.
190 constructing the socket; and connecting the socket.
191 .PP
192 How to construct a socket is platform specific \- but most platforms (including
193 Windows) provide a POSIX compatible interface via the \fIsocket\fR function, e.g.
194 to create an IPv4 TCP socket:
195 .PP
196 .Vb 1
197 \& int sock;
198 \&
199 \& sock = socket(AF_INET, SOCK_STREAM, 0);
200 \& if (sock == \-1)
201 \& return NULL;
202 .Ve
203 .PP
204 Once the socket is constructed it must be connected to the remote server. Again
205 the details are platform specific but most platforms (including Windows)
206 provide the POSIX compatible \fIconnect\fR function. For example:
207 .PP
208 .Vb 2
209 \& struct sockaddr_in serveraddr;
210 \& struct hostent *server;
211 \&
212 \& server = gethostbyname("www.openssl.org");
213 \& if (server == NULL) {
214 \& close(sock);
215 \& return NULL;
216 \& }
217 \&
218 \& memset(&serveraddr, 0, sizeof(serveraddr));
219 \& serveraddr.sin_family = server\->h_addrtype;
220 \& serveraddr.sin_port = htons(443);
221 \& memcpy(&serveraddr.sin_addr.s_addr, server\->h_addr, server\->h_length);
222 \&
223 \& if (connect(sock, (struct sockaddr *)&serveraddr,
224 \& sizeof(serveraddr)) == \-1) {
225 \& close(sock);
226 \& return NULL;
227 \& }
228 .Ve
229 .PP
230 OpenSSL provides portable helper functions to do these tasks which also
231 integrate into the OpenSSL error system to log error data, e.g.
232 .PP
233 .Vb 3
234 \& int sock = \-1;
235 \& BIO_ADDRINFO *res;
236 \& const BIO_ADDRINFO *ai = NULL;
237 \&
238 \& /*
239 \& * Lookup IP address info for the server.
240 \& */
241 \& if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_STREAM, 0,
242 \& &res))
243 \& return NULL;
244 \&
245 \& /*
246 \& * Loop through all the possible addresses for the server and find one
247 \& * we can connect to.
248 \& */
249 \& for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
250 \& /*
251 \& * Create a TCP socket. We could equally use non\-OpenSSL calls such
252 \& * as "socket" here for this and the subsequent connect and close
253 \& * functions. But for portability reasons and also so that we get
254 \& * errors on the OpenSSL stack in the event of a failure we use
255 \& * OpenSSL\*(Aqs versions of these functions.
256 \& */
257 \& sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_STREAM, 0, 0);
258 \& if (sock == \-1)
259 \& continue;
260 \&
261 \& /* Connect the socket to the server\*(Aqs address */
262 \& if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), BIO_SOCK_NODELAY)) {
263 \& BIO_closesocket(sock);
264 \& sock = \-1;
265 \& continue;
266 \& }
267 \&
268 \& /* We have a connected socket so break out of the loop */
269 \& break;
270 \& }
271 \&
272 \& /* Free the address information resources we allocated earlier */
273 \& BIO_ADDRINFO_free(res);
274 .Ve
275 .PP
276 See \fBBIO_lookup_ex\fR\|(3), \fBBIO_socket\fR\|(3), \fBBIO_connect\fR\|(3),
277 \&\fBBIO_closesocket\fR\|(3), \fBBIO_ADDRINFO_next\fR\|(3), \fBBIO_ADDRINFO_address\fR\|(3) and
278 \&\fBBIO_ADDRINFO_free\fR\|(3) for further information on the functions used here. In
279 the above example code the \fBhostname\fR and \fBport\fR variables are strings, e.g.
280 "www.example.com" and "443". Note also the use of the family variable, which
281 can take the values of AF_INET or AF_INET6 based on the command line \-6 option,
282 to allow specific connections to an ipv4 or ipv6 enabled host.
283 .PP
284 Sockets created using the methods described above will automatically be blocking
285 sockets \- which is exactly what we want for this example.
286 .PP
287 Once the socket has been created and connected we need to associate it with a
288 BIO object:
289 .PP
290 .Vb 1
291 \& BIO *bio;
292 \&
293 \& /* Create a BIO to wrap the socket */
294 \& bio = BIO_new(BIO_s_socket());
295 \& if (bio == NULL) {
296 \& BIO_closesocket(sock);
297 \& return NULL;
298 \& }
299 \&
300 \& /*
301 \& * Associate the newly created BIO with the underlying socket. By
302 \& * passing BIO_CLOSE here the socket will be automatically closed when
303 \& * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
304 \& * case you must close the socket explicitly when it is no longer
305 \& * needed.
306 \& */
307 \& BIO_set_fd(bio, sock, BIO_CLOSE);
308 .Ve
309 .PP
310 See \fBBIO_new\fR\|(3), \fBBIO_s_socket\fR\|(3) and \fBBIO_set_fd\fR\|(3) for further
311 information on these functions.
312 .PP
313 Finally we associate the \fBSSL\fR object we created earlier with the \fBBIO\fR using
314 the \fBSSL_set_bio\fR\|(3) function. Note that this passes ownership of the \fBBIO\fR
315 object to the \fBSSL\fR object. Once ownership is passed the SSL object is
316 responsible for its management and will free it automatically when the \fBSSL\fR is
317 freed. So, once \fBSSL_set_bio\fR\|(3) has been been called, you should not call
318 \&\fBBIO_free\fR\|(3) on the \fBBIO\fR.
319 .PP
320 .Vb 1
321 \& SSL_set_bio(ssl, bio, bio);
322 .Ve
323 .SS "Setting the server's hostname"
324 .IX Subsection "Setting the server's hostname"
325 We have already connected our underlying socket to the server, but the client
326 still needs to know the server's hostname. It uses this information for 2 key
327 purposes and we need to set the hostname for each one.
328 .PP
329 Firstly, the server's hostname is included in the initial ClientHello message
330 sent by the client. This is known as the Server Name Indication (SNI). This is
331 important because it is common for multiple hostnames to be fronted by a single
332 server that handles requests for all of them. In other words a single server may
333 have multiple hostnames associated with it and it is important to indicate which
334 one we want to connect to. Without this information we may get a handshake
335 failure, or we may get connected to the "default" server which may not be the
336 one we were expecting.
337 .PP
338 To set the SNI hostname data we call the \fBSSL_set_tlsext_host_name\fR\|(3) function
339 like this:
340 .PP
341 .Vb 8
342 \& /*
343 \& * Tell the server during the handshake which hostname we are attempting
344 \& * to connect to in case the server supports multiple hosts.
345 \& */
346 \& if (!SSL_set_tlsext_host_name(ssl, hostname)) {
347 \& printf("Failed to set the SNI hostname\en");
348 \& goto end;
349 \& }
350 .Ve
351 .PP
352 Here the \f(CW\*(C`hostname\*(C'\fR argument is a string representing the hostname of the
353 server, e.g. "www.example.com".
354 .PP
355 Secondly, we need to tell OpenSSL what hostname we expect to see in the
356 certificate coming back from the server. This is almost always the same one that
357 we asked for in the original request. This is important because, without this,
358 we do not verify that the hostname in the certificate is what we expect it to be
359 and any certificate is acceptable unless your application explicitly checks this
360 itself. We do this via the \fBSSL_set1_host\fR\|(3) function:
361 .PP
362 .Vb 10
363 \& /*
364 \& * Ensure we check during certificate verification that the server has
365 \& * supplied a certificate for the hostname that we were expecting.
366 \& * Virtually all clients should do this unless you really know what you
367 \& * are doing.
368 \& */
369 \& if (!SSL_set1_host(ssl, hostname)) {
370 \& printf("Failed to set the certificate verification hostname");
371 \& goto end;
372 \& }
373 .Ve
374 .PP
375 All of the above steps must happen before we attempt to perform the handshake
376 otherwise they will have no effect.
377 .SS "Performing the handshake"
378 .IX Subsection "Performing the handshake"
379 Before we can start sending or receiving application data over a TLS connection
380 the TLS handshake must be performed. We can do this explicitly via the
381 \&\fBSSL_connect\fR\|(3) function.
382 .PP
383 .Vb 12
384 \& /* Do the handshake with the server */
385 \& if (SSL_connect(ssl) < 1) {
386 \& printf("Failed to connect to the server\en");
387 \& /*
388 \& * If the failure is due to a verification error we can get more
389 \& * information about it from SSL_get_verify_result().
390 \& */
391 \& if (SSL_get_verify_result(ssl) != X509_V_OK)
392 \& printf("Verify error: %s\en",
393 \& X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
394 \& goto end;
395 \& }
396 .Ve
397 .PP
398 The \fBSSL_connect\fR\|(3) function can return 1, 0 or less than 0. Only a return
399 value of 1 is considered a success. For a simple blocking client we only need
400 to concern ourselves with whether the call was successful or not. Anything else
401 indicates that we have failed to connect to the server.
402 .PP
403 A common cause of failures at this stage is due to a problem verifying the
404 server's certificate. For example if the certificate has expired, or it is not
405 signed by a CA in our trusted certificate store. We can use the
406 \&\fBSSL_get_verify_result\fR\|(3) function to find out more information about the
407 verification failure. A return value of \fBX509_V_OK\fR indicates that the
408 verification was successful (so the connection error must be due to some other
409 cause). Otherwise we use the \fBX509_verify_cert_error_string\fR\|(3) function to get
410 a human readable error message.
411 .SS "Sending and receiving data"
412 .IX Subsection "Sending and receiving data"
413 Once the handshake is complete we are able to send and receive application data.
414 Exactly what data is sent and in what order is usually controlled by some
415 application level protocol. In this example we are using HTTP 1.0 which is a
416 very simple request and response protocol. The client sends a request to the
417 server. The server sends the response data and then immediately closes down the
418 connection.
419 .PP
420 To send data to the server we use the \fBSSL_write_ex\fR\|(3) function and to receive
421 data from the server we use the \fBSSL_read_ex\fR\|(3) function. In HTTP 1.0 the
422 client always writes data first. Our HTTP request will include the hostname that
423 we are connecting to. For simplicity, we write the HTTP request in three
424 chunks. First we write the start of the request. Secondly we write the hostname
425 we are sending the request to. Finally we send the end of the request.
426 .PP
427 .Vb 3
428 \& size_t written;
429 \& const char *request_start = "GET / HTTP/1.0\er\enConnection: close\er\enHost: ";
430 \& const char *request_end = "\er\en\er\en";
431 \&
432 \& /* Write an HTTP GET request to the peer */
433 \& if (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
434 \& printf("Failed to write start of HTTP request\en");
435 \& goto end;
436 \& }
437 \& if (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
438 \& printf("Failed to write hostname in HTTP request\en");
439 \& goto end;
440 \& }
441 \& if (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {
442 \& printf("Failed to write end of HTTP request\en");
443 \& goto end;
444 \& }
445 .Ve
446 .PP
447 The \fBSSL_write_ex\fR\|(3) function returns 0 if it fails and 1 if it is successful.
448 If it is successful then we can proceed to waiting for a response from the
449 server.
450 .PP
451 .Vb 2
452 \& size_t readbytes;
453 \& char buf[160];
454 \&
455 \& /*
456 \& * Get up to sizeof(buf) bytes of the response. We keep reading until the
457 \& * server closes the connection.
458 \& */
459 \& while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
460 \& /*
461 \& * OpenSSL does not guarantee that the returned data is a string or
462 \& * that it is NUL terminated so we use fwrite() to write the exact
463 \& * number of bytes that we read. The data could be non\-printable or
464 \& * have NUL characters in the middle of it. For this simple example
465 \& * we\*(Aqre going to print it to stdout anyway.
466 \& */
467 \& fwrite(buf, 1, readbytes, stdout);
468 \& }
469 \& /* In case the response didn\*(Aqt finish with a newline we add one now */
470 \& printf("\en");
471 .Ve
472 .PP
473 We use the \fBSSL_read_ex\fR\|(3) function to read the response. We don't know
474 exactly how much data we are going to receive back so we enter a loop reading
475 blocks of data from the server and printing each block that we receive to the
476 screen. The loop ends as soon as \fBSSL_read_ex\fR\|(3) returns 0 \- meaning that it
477 failed to read any data.
478 .PP
479 A failure to read data could mean that there has been some error, or it could
480 simply mean that server has sent all the data that it wants to send and has
481 indicated that it has finished by sending a "close_notify" alert. This alert is
482 a TLS protocol level message indicating that the endpoint has finished sending
483 all of its data and it will not send any more. Both of these conditions result
484 in a 0 return value from \fBSSL_read_ex\fR\|(3) and we need to use the function
485 \&\fBSSL_get_error\fR\|(3) to determine the cause of the 0 return value.
486 .PP
487 .Vb 10
488 \& /*
489 \& * Check whether we finished the while loop above normally or as the
490 \& * result of an error. The 0 argument to SSL_get_error() is the return
491 \& * code we received from the SSL_read_ex() call. It must be 0 in order
492 \& * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN.
493 \& */
494 \& if (SSL_get_error(ssl, 0) != SSL_ERROR_ZERO_RETURN) {
495 \& /*
496 \& * Some error occurred other than a graceful close down by the
497 \& * peer
498 \& */
499 \& printf ("Failed reading remaining data\en");
500 \& goto end;
501 \& }
502 .Ve
503 .PP
504 If \fBSSL_get_error\fR\|(3) returns \fBSSL_ERROR_ZERO_RETURN\fR then we know that the
505 server has finished sending its data. Otherwise an error has occurred.
506 .SS "Shutting down the connection"
507 .IX Subsection "Shutting down the connection"
508 Once we have finished reading data from the server then we are ready to close
509 the connection down. We do this via the \fBSSL_shutdown\fR\|(3) function which has
510 the effect of sending a TLS protocol level message (a "close_notify" alert) to
511 the server saying that we have finished writing data:
512 .PP
513 .Vb 10
514 \& /*
515 \& * The peer already shutdown gracefully (we know this because of the
516 \& * SSL_ERROR_ZERO_RETURN above). We should do the same back.
517 \& */
518 \& ret = SSL_shutdown(ssl);
519 \& if (ret < 1) {
520 \& /*
521 \& * ret < 0 indicates an error. ret == 0 would be unexpected here
522 \& * because that means "we\*(Aqve sent a close_notify and we\*(Aqre waiting
523 \& * for one back". But we already know we got one from the peer
524 \& * because of the SSL_ERROR_ZERO_RETURN above.
525 \& */
526 \& printf("Error shutting down\en");
527 \& goto end;
528 \& }
529 .Ve
530 .PP
531 The \fBSSL_shutdown\fR\|(3) function will either return 1, 0, or less than 0. A
532 return value of 1 is a success, and a return value less than 0 is an error. More
533 precisely a return value of 1 means that we have sent a "close_notify" alert to
534 the server, and that we have also received one back. A return value of 0 means
535 that we have sent a "close_notify" alert to the server, but we have not yet
536 received one back. Usually in this scenario you would call \fBSSL_shutdown\fR\|(3)
537 again which (with a blocking socket) would block until the "close_notify" is
538 received. However in this case we already know that the server has sent us a
539 "close_notify" because of the SSL_ERROR_ZERO_RETURN that we received from the
540 call to \fBSSL_read_ex\fR\|(3). So this scenario should never happen in practice. We
541 just treat it as an error in this example.
542 .SS "Final clean up"
543 .IX Subsection "Final clean up"
544 Before the application exits we have to clean up some memory that we allocated.
545 If we are exiting due to an error we might also want to display further
546 information about that error if it is available to the user:
547 .PP
548 .Vb 10
549 \& /* Success! */
550 \& res = EXIT_SUCCESS;
551 \& end:
552 \& /*
553 \& * If something bad happened then we will dump the contents of the
554 \& * OpenSSL error stack to stderr. There might be some useful diagnostic
555 \& * information there.
556 \& */
557 \& if (res == EXIT_FAILURE)
558 \& ERR_print_errors_fp(stderr);
559 \&
560 \& /*
561 \& * Free the resources we allocated. We do not free the BIO object here
562 \& * because ownership of it was immediately transferred to the SSL object
563 \& * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
564 \& */
565 \& SSL_free(ssl);
566 \& SSL_CTX_free(ctx);
567 \& return res;
568 .Ve
569 .PP
570 To display errors we make use of the \fBERR_print_errors_fp\fR\|(3) function which
571 simply dumps out the contents of any errors on the OpenSSL error stack to the
572 specified location (in this case \fIstderr\fR).
573 .PP
574 We need to free up the \fBSSL\fR object that we created for the connection via the
575 \&\fBSSL_free\fR\|(3) function. Also, since we are not going to be creating any more
576 TLS connections we must also free up the \fBSSL_CTX\fR via a call to
577 \&\fBSSL_CTX_free\fR\|(3).
578 .SH TROUBLESHOOTING
579 .IX Header "TROUBLESHOOTING"
580 There are a number of things that might go wrong when running the demo
581 application. This section describes some common things you might encounter.
582 .SS "Failure to connect the underlying socket"
583 .IX Subsection "Failure to connect the underlying socket"
584 This could occur for numerous reasons. For example if there is a problem in the
585 network route between the client and the server; or a firewall is blocking the
586 communication; or the server is not in DNS. Check the network configuration.
587 .SS "Verification failure of the server certificate"
588 .IX Subsection "Verification failure of the server certificate"
589 A verification failure of the server certificate would result in a failure when
590 running the \fBSSL_connect\fR\|(3) function. \fBERR_print_errors_fp\fR\|(3) would display
591 an error which would look something like this:
592 .PP
593 .Vb 2
594 \& Verify error: unable to get local issuer certificate
595 \& 40E74AF1F47F0000:error:0A000086:SSL routines:tls_post_process_server_certificate:certificate verify failed:ssl/statem/statem_clnt.c:2069:
596 .Ve
597 .PP
598 A server certificate verification failure could be caused for a number of
599 reasons. For example
600 .IP "Failure to correctly setup the trusted certificate store" 4
601 .IX Item "Failure to correctly setup the trusted certificate store"
602 See the page \fBossl\-guide\-tls\-introduction\fR\|(7) and check that your trusted
603 certificate store is correctly configured
604 .IP "Unrecognised CA" 4
605 .IX Item "Unrecognised CA"
606 If the CA used by the server's certificate is not in the trusted certificate
607 store for the client then this will cause a verification failure during
608 connection. Often this can occur if the server is using a self-signed
609 certificate (i.e. a test certificate that has not been signed by a CA at all).
610 .IP "Missing intermediate CAs" 4
611 .IX Item "Missing intermediate CAs"
612 This is a server misconfiguration where the client has the relevant root CA in
613 its trust store, but the server has not supplied all of the intermediate CA
614 certificates between that root CA and the server's own certificate. Therefore
615 a trust chain cannot be established.
616 .IP "Mismatched hostname" 4
617 .IX Item "Mismatched hostname"
618 If for some reason the hostname of the server that the client is expecting does
619 not match the hostname in the certificate then this will cause verification to
620 fail.
621 .IP "Expired certificate" 4
622 .IX Item "Expired certificate"
623 The date that the server's certificate is valid to has passed.
624 .PP
625 The "unable to get local issuer certificate" we saw in the example above means
626 that we have been unable to find the issuer of the server's certificate (or one
627 of its intermediate CA certificates) in our trusted certificate store (e.g.
628 because the trusted certificate store is misconfigured, or there are missing
629 intermediate CAs, or the issuer is simply unrecognised).
630 .SH "FURTHER READING"
631 .IX Header "FURTHER READING"
632 See \fBossl\-guide\-tls\-client\-non\-block\fR\|(7) to read a tutorial on how to modify
633 the client developed on this page to support a nonblocking socket.
634 .PP
635 See \fBossl\-guide\-tls\-server\-block\fR\|(7) for a tutorial on how to implement a
636 simple TLS server handling one client at a time over a blocking socket.
637 .PP
638 See \fBossl\-guide\-quic\-client\-block\fR\|(7) to read a tutorial on how to modify the
639 client developed on this page to support QUIC instead of TLS.
640 .SH "SEE ALSO"
641 .IX Header "SEE ALSO"
642 \&\fBossl\-guide\-introduction\fR\|(7), \fBossl\-guide\-libraries\-introduction\fR\|(7),
643 \&\fBossl\-guide\-libssl\-introduction\fR\|(7), \fBossl\-guide\-tls\-introduction\fR\|(7),
644 \&\fBossl\-guide\-tls\-client\-non\-block\fR\|(7), \fBossl\-guide\-quic\-client\-block\fR\|(7)
645 .SH COPYRIGHT
646 .IX Header "COPYRIGHT"
647 Copyright 2023\-2024 The OpenSSL Project Authors. All Rights Reserved.
648 .PP
649 Licensed under the Apache License 2.0 (the "License"). You may not use
650 this file except in compliance with the License. You can obtain a copy
651 in the file LICENSE in the source distribution or at
652 <https://www.openssl.org/source/license.html>.