ossl-guide-tls-client-block.7ossl 30 KB

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