documented fix
[gnutls.git] / doc / cha-gtls-app.texi
blob27a4ff73ad09b1b803994a4802e1920d6cbc1b2f
1 @node How to use GnuTLS in applications
2 @chapter How To Use @acronym{GnuTLS} in Applications
3 @anchor{examples}
4 @cindex Example programs
6 @menu
7 * Preparation::
8 * Multi-threaded applications::
9 * Client examples::
10 * Server examples::
11 * Miscellaneous examples::
12 * Parameter generation::
13 * Keying Material Exporters::
14 * Channel Bindings::
15 * Compatibility with the OpenSSL library::
16 @end menu
18 @node Preparation
19 @section Preparation
21 To use @acronym{GnuTLS}, you have to perform some changes to your
22 sources and your build system. The necessary changes are explained in
23 the following subsections.
25 @menu
26 * Headers::
27 * Initialization::
28 * Version check::
29 * Debugging::
30 * Building the source::
31 @end menu
33 @node Headers
34 @subsection Headers
36 All the data types and functions of the @acronym{GnuTLS} library are
37 defined in the header file @file{gnutls/gnutls.h}.  This must be
38 included in all programs that make use of the @acronym{GnuTLS}
39 library.
41 The extra functionality of the @acronym{GnuTLS-extra} library is
42 available by including the header file @file{gnutls/extra.h} in your
43 programs.
45 @node Initialization
46 @subsection Initialization
48 GnuTLS must be initialized before it can be used.  The library is
49 initialized by calling @ref{gnutls_global_init}.  The resources
50 allocated by the initialization process can be released if the
51 application no longer has a need to call GnuTLS functions, this is
52 done by calling @ref{gnutls_global_deinit}.
54 The extra functionality of the @acronym{GnuTLS-extra} library is
55 available after calling @ref{gnutls_global_init_extra}.
57 In order to take advantage of the internationalisation features in
58 GnuTLS, such as translated error messages, the application must set
59 the current locale using @code{setlocale} before initializing GnuTLS.
61 @node Version check
62 @subsection Version Check
64 It is often desirable to check that the version of `gnutls' used is
65 indeed one which fits all requirements.  Even with binary
66 compatibility new features may have been introduced but due to problem
67 with the dynamic linker an old version is actually used.  So you may
68 want to check that the version is okay right after program startup.
69 See the function @ref{gnutls_check_version}.
71 @node Debugging
72 @subsection Debugging
74 In many cases things may not go as expected and further information,
75 to assist debugging, from @acronym{GnuTLS} is desired. Those are the
76 case where the @ref{gnutls_global_set_log_level} and
77 @ref{gnutls_global_set_log_function} are to be used. Those will print
78 verbose information on the @acronym{GnuTLS} functions internal flow.
80 @node Building the source
81 @subsection Building the Source
83 If you want to compile a source file including the
84 @file{gnutls/gnutls.h} header file, you must make sure that the
85 compiler can find it in the directory hierarchy.  This is accomplished
86 by adding the path to the directory in which the header file is
87 located to the compilers include file search path (via the @option{-I}
88 option).
90 However, the path to the include file is determined at the time the
91 source is configured.  To solve this problem, the library uses the
92 external package @command{pkg-config} that knows the path to the
93 include file and other configuration options.  The options that need
94 to be added to the compiler invocation at compile time are output by
95 the @option{--cflags} option to @command{pkg-config gnutls}.  The
96 following example shows how it can be used at the command line:
98 @example
99 gcc -c foo.c `pkg-config gnutls --cflags`
100 @end example
102 Adding the output of @samp{pkg-config gnutls --cflags} to the
103 compilers command line will ensure that the compiler can find the
104 @file{gnutls/gnutls.h} header file.
106 A similar problem occurs when linking the program with the library.
107 Again, the compiler has to find the library files.  For this to work,
108 the path to the library files has to be added to the library search
109 path (via the @option{-L} option).  For this, the option
110 @option{--libs} to @command{pkg-config gnutls} can be used.  For
111 convenience, this option also outputs all other options that are
112 required to link the program with the libarary (for instance, the
113 @samp{-ltasn1} option).  The example shows how to link @file{foo.o}
114 with the library to a program @command{foo}.
116 @example
117 gcc -o foo foo.o `pkg-config gnutls --libs`
118 @end example
120 Of course you can also combine both examples to a single command by
121 specifying both options to @command{pkg-config}:
123 @example
124 gcc -o foo foo.c `pkg-config gnutls --cflags --libs`
125 @end example
127 @node Multi-threaded applications
128 @section Multi-Threaded Applications
130 Although the @acronym{GnuTLS} library is thread safe by design, some
131 parts of the cryptographic backend, such as the random generator, are not.
132 Applications can either call @ref{gnutls_global_init} and use the default 
133 operating system provided locks (i.e. @code{pthreads} on GNU/Linux), or
134 specify manualy the locking system using the function @ref{gnutls_global_set_mutex}
135 before calling @ref{gnutls_global_init}. Setting manually mutexes is recommended
136 only to applications that have full control of the underlying libraries. If this
137 is not the case, the use of the operating system defaults is recommended.
140 There are helper macros to help you properly initialize the libraries.
141 Examples are shown below.
143 @itemize
145 @item POSIX threads in GNU/Linux
146 @example
147 #include <gnutls.h>
148 #include <errno.h>
149 #include <pthread.h>
151 int main()
153    gnutls_global_init();
155 @end example
157 @item Other thread packages
158 @example
160 int main()
162    gnutls_global_mutex_set (mutex_init, mutex_deinit, mutex_lock, mutex_unlock);
163    gnutls_global_init();
165 @end example
166 @end itemize
168 @node Client examples
169 @section Client Examples
171 This section contains examples of @acronym{TLS} and @acronym{SSL}
172 clients, using @acronym{GnuTLS}.  Note that these examples contain
173 little or no error checking.  Some of the examples require functions
174 implemented by another example.
176 @menu
177 * Simple client example with anonymous authentication::
178 * Simple client example with X.509 certificate support::
179 * Obtaining session information::
180 * Verifying peer's certificate::
181 * Using a callback to select the certificate to use::
182 * Client using a PKCS #11 token with TLS::
183 * Client with Resume capability example::
184 * Simple client example with SRP authentication::
185 * Simple client example in C++::
186 * Helper function for TCP connections::
187 @end menu
189 @node Simple client example with anonymous authentication
190 @subsection Simple Client Example with Anonymous Authentication
192 The simplest client using TLS is the one that doesn't do any
193 authentication.  This means no external certificates or passwords are
194 needed to set up the connection.  As could be expected, the connection
195 is vulnerable to man-in-the-middle (active or redirection) attacks.
196 However, the data is integrity and privacy protected.
198 @verbatiminclude examples/ex-client1.c
200 @node Simple client example with X.509 certificate support
201 @subsection Simple Client Example with @acronym{X.509} Certificate Support
203 Let's assume now that we want to create a TCP client which
204 communicates with servers that use @acronym{X.509} or
205 @acronym{OpenPGP} certificate authentication. The following client is
206 a very simple @acronym{TLS} client, it does not support session
207 resuming, not even certificate verification. The TCP functions defined
208 in this example are used in most of the other examples below, without
209 redefining them.
211 @verbatiminclude examples/ex-client2.c
213 @node Obtaining session information
214 @subsection Obtaining Session Information
216 Most of the times it is desirable to know the security properties of
217 the current established session.  This includes the underlying ciphers
218 and the protocols involved.  That is the purpose of the following
219 function.  Note that this function will print meaningful values only
220 if called after a successful @ref{gnutls_handshake}.
222 @verbatiminclude examples/ex-session-info.c
224 @node Verifying peer's certificate
225 @subsection Verifying Peer's Certificate
226 @anchor{ex:verify}
228 A @acronym{TLS} session is not secure just after the handshake
229 procedure has finished.  It must be considered secure, only after the
230 peer's certificate and identity have been verified. That is, you have
231 to verify the signature in peer's certificate, the hostname in the
232 certificate, and expiration dates.  Just after this step you should
233 treat the connection as being a secure one.
235 @verbatiminclude examples/ex-rfc2818.c
237 Another example is listed below which provides more detailed
238 verification output, for applications that need it.
240 @verbatiminclude examples/ex-verify.c
242 @node Using a callback to select the certificate to use
243 @subsection Using a Callback to Select the Certificate to Use
245 There are cases where a client holds several certificate and key
246 pairs, and may not want to load all of them in the credentials
247 structure.  The following example demonstrates the use of the
248 certificate selection callback.
250 @verbatiminclude examples/ex-cert-select.c
253 @node Client using a PKCS #11 token with TLS
254 @subsection Using a @acronym{PKCS #11} token with TLS
255 @anchor{ex:pkcs11-client}
257 This example will demonstrate how to load keys and certificates
258 from a @acronym{PKCS} #11 token, and use it with a TLS connection.
260 @verbatiminclude examples/ex-cert-select-pkcs11.c
263 @node Client with Resume capability example
264 @subsection Client with Resume Capability Example
265 @anchor{ex:resume-client}
267 This is a modification of the simple client example. Here we
268 demonstrate the use of session resumption. The client tries to connect
269 once using @acronym{TLS}, close the connection and then try to
270 establish a new connection using the previously negotiated data.
272 @verbatiminclude examples/ex-client-resume.c
275 @node Simple client example with SRP authentication
276 @subsection Simple Client Example with @acronym{SRP} Authentication
278 The following client is a very simple @acronym{SRP} @acronym{TLS}
279 client which connects to a server and authenticates using a
280 @emph{username} and a @emph{password}. The server may authenticate
281 itself using a certificate, and in that case it has to be verified.
283 @verbatiminclude examples/ex-client-srp.c
285 @node Simple client example in C++
286 @subsection Simple Client Example using the C++ API
288 The following client is a simple example of a client client utilizing
289 the GnuTLS C++ API.
291 @verbatiminclude examples/ex-cxx.cpp
293 @node Helper function for TCP connections
294 @subsection Helper Function for TCP Connections
296 This helper function abstracts away TCP connection handling from the
297 other examples.  It is required to build some examples.
299 @verbatiminclude examples/tcp.c
301 @node Server examples
302 @section Server Examples
304 This section contains examples of @acronym{TLS} and @acronym{SSL}
305 servers, using @acronym{GnuTLS}.
307 @menu
308 * Echo Server with X.509 authentication::
309 * Echo Server with OpenPGP authentication::
310 * Echo Server with SRP authentication::
311 * Echo Server with anonymous authentication::
312 @end menu
314 @node Echo Server with X.509 authentication
315 @subsection Echo Server with @acronym{X.509} Authentication
317 This example is a very simple echo server which supports
318 @acronym{X.509} authentication, using the RSA ciphersuites.
320 @verbatiminclude examples/ex-serv1.c
322 @node Echo Server with OpenPGP authentication
323 @subsection Echo Server with @acronym{OpenPGP} Authentication
324 @cindex @acronym{OpenPGP} Server
326 The following example is an echo server which supports
327 @acronym{@acronym{OpenPGP}} key authentication. You can easily combine
328 this functionality ---that is have a server that supports both
329 @acronym{X.509} and @acronym{OpenPGP} certificates--- but we separated
330 them to keep these examples as simple as possible.
332 @verbatiminclude examples/ex-serv-pgp.c
334 @node Echo Server with SRP authentication
335 @subsection Echo Server with @acronym{SRP} Authentication
337 This is a server which supports @acronym{SRP} authentication. It is
338 also possible to combine this functionality with a certificate
339 server. Here it is separate for simplicity.
341 @verbatiminclude examples/ex-serv-srp.c
343 @node Echo Server with anonymous authentication
344 @subsection Echo Server with Anonymous Authentication
346 This example server support anonymous authentication, and could be
347 used to serve the example client for anonymous authentication.
349 @verbatiminclude examples/ex-serv-anon.c
351 @node Miscellaneous examples
352 @section Miscellaneous Examples
354 @menu
355 * Checking for an alert::
356 * X.509 certificate parsing example::
357 * Certificate request generation::
358 * PKCS #12 structure generation::
359 @end menu
361 @node Checking for an alert
362 @subsection Checking for an Alert
364 This is a function that checks if an alert has been received in the
365 current session.
367 @verbatiminclude examples/ex-alert.c
369 @node X.509 certificate parsing example
370 @subsection @acronym{X.509} Certificate Parsing Example
371 @anchor{ex:x509-info}
373 To demonstrate the @acronym{X.509} parsing capabilities an example program is
374 listed below.  That program reads the peer's certificate, and prints
375 information about it.
377 @verbatiminclude examples/ex-x509-info.c
379 @node Certificate request generation
380 @subsection Certificate Request Generation
381 @anchor{ex:crq}
383 The following example is about generating a certificate request, and a
384 private key. A certificate request can be later be processed by a CA,
385 which should return a signed certificate.
387 @verbatiminclude examples/ex-crq.c
389 @node PKCS #12 structure generation
390 @subsection @acronym{PKCS} #12 Structure Generation
391 @anchor{ex:pkcs12}
393 The following example is about generating a @acronym{PKCS} #12
394 structure.
396 @verbatiminclude examples/ex-pkcs12.c
398 @node Parameter generation
399 @section Parameter generation
400 @cindex parameter generation
401 @cindex generating parameters
403 Several TLS ciphersuites require additional parameters that
404 need to be generated or provided by the application. The
405 Diffie-Hellman based ciphersuites (ANON-DH or DHE), require
406 the group information to be provided. This information can be either
407 be generated on the fly using @ref{gnutls_dh_params_generate2}
408 or imported from some pregenerated value using @ref{gnutls_dh_params_import_pkcs3}.
409 The parameters can be used in a session by calling
410 @ref{gnutls_certificate_set_dh_params} or
411 @ref{gnutls_anon_set_server_dh_params} for anonymous sessions.
413 Due to the time-consuming calculations required for the generation
414 of Diffie-Hellman parameters we suggest against performing generation
415 of them within an application. The @code{certtool} tool can be used to 
416 generate or export known safe values that can be stored in code
417 or in a configuration file to provide the ability to replace. We also
418 recommend the usage of @ref{gnutls_sec_param_to_pk_bits} to determine
419 the bit size of the parameters to be generated.
421 The ciphersuites that involve the RSA-EXPORT key exchange require
422 additional parameters. Those ciphersuites are rarely used today
423 because they are by design insecure, thus if you have no requirement
424 for them, this section should be skipped. The RSA-EXPORT key exchange
425 requires 512-bit RSA keys to be generated. It is recommended those
426 parameters to be refreshed (regenerated) in short intervals. The
427 following functions can be used for these parameters.
429 @itemize
431 @item @ref{gnutls_rsa_params_generate2}
433 @item @ref{gnutls_certificate_set_rsa_export_params}
435 @item @ref{gnutls_rsa_params_import_pkcs1}
437 @item @ref{gnutls_rsa_params_export_pkcs1}
439 @end itemize
442 @node Keying Material Exporters
443 @section Keying Material Exporters
444 @cindex Keying Material Exporters
445 @cindex Exporting Keying Material
447 The TLS PRF can be used by other protocols to derive data.  The API to
448 use is @ref{gnutls_prf}.  The function needs to be provided with the
449 label in the parameter @code{label}, and the extra data to mix in the
450 @code{extra} parameter.  Depending on whether you want to mix in the
451 client or server random data first, you can set the
452 @code{server_random_first} parameter.
454 For example, after establishing a TLS session using
455 @ref{gnutls_handshake}, you can invoke the TLS PRF with this call:
457 @smallexample
458 #define MYLABEL "EXPORTER-FOO"
459 #define MYCONTEXT "some context data"
460 char out[32];
461 rc = gnutls_prf (session, strlen (MYLABEL), MYLABEL, 0,
462                  strlen (MYCONTEXT), MYCONTEXT, 32, out);
463 @end smallexample
465 If you don't want to mix in the client/server random, there is a more
466 low-level TLS PRF interface called @ref{gnutls_prf_raw}.
468 @node Channel Bindings
469 @section Channel Bindings
470 @cindex Channel Bindings
472 In user authentication protocols (e.g., EAP or SASL mechanisms) it is
473 useful to have a unique string that identifies the secure channel that
474 is used, to bind together the user authentication with the secure
475 channel.  This can protect against man-in-the-middle attacks in some
476 situations.  The unique strings is a ``channel bindings''.  For
477 background and more discussion see @xcite{RFC5056}.
479 You can extract a channel bindings using the
480 @ref{gnutls_session_channel_binding} function.  Currently only the
481 @code{GNUTLS_CB_TLS_UNIQUE} type is supported, which corresponds to
482 the @code{tls-unique} channel bindings for TLS defined in
483 @xcite{RFC5929}.
485 The following example describes how to print the channel binding data.
486 Note that it must be run after a successful TLS handshake.
488 @smallexample
490   gnutls_datum cb;
491   int rc;
493   rc = gnutls_session_channel_binding (session,
494                                        GNUTLS_CB_TLS_UNIQUE,
495                                        &cb);
496   if (rc)
497     fprintf (stderr, "Channel binding error: %s\n",
498              gnutls_strerror (rc));
499   else
500     @{
501       size_t i;
502       printf ("- Channel binding 'tls-unique': ");
503       for (i = 0; i < cb.size; i++)
504         printf ("%02x", cb.data[i]);
505       printf ("\n");
506     @}
508 @end smallexample
510 @node Compatibility with the OpenSSL library
511 @section Compatibility with the OpenSSL Library
512 @cindex OpenSSL
514 To ease @acronym{GnuTLS}' integration with existing applications, a
515 compatibility layer with the widely used OpenSSL library is included
516 in the @code{gnutls-openssl} library. This compatibility layer is not
517 complete and it is not intended to completely reimplement the OpenSSL
518 API with @acronym{GnuTLS}.  It only provides source-level
519 compatibility. There is currently no attempt to make it
520 binary-compatible with OpenSSL.
522 The prototypes for the compatibility functions are in the
523 @file{gnutls/openssl.h} header file.
525 Current limitations imposed by the compatibility layer include:
527 @itemize
529 @item Error handling is not thread safe.
531 @end itemize