Add `gnutls/dtls.h' to the distribution.
[gnutls.git] / doc / cha-gtls-app.texi
blob3f907e205c028347c466d6d34b1037363bcb0e85
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 * Compatibility with the OpenSSL library::
13 * Keying Material Exporters::
14 * Channel Bindings::
15 @end menu
17 @node Preparation
18 @section Preparation
20 To use @acronym{GnuTLS}, you have to perform some changes to your
21 sources and your build system. The necessary changes are explained in
22 the following subsections.
24 @menu
25 * Headers::
26 * Initialization::
27 * Version check::
28 * Debugging::
29 * Building the source::
30 @end menu
32 @node Headers
33 @subsection Headers
35 All the data types and functions of the @acronym{GnuTLS} library are
36 defined in the header file @file{gnutls/gnutls.h}.  This must be
37 included in all programs that make use of the @acronym{GnuTLS}
38 library.
40 The extra functionality of the @acronym{GnuTLS-extra} library is
41 available by including the header file @file{gnutls/extra.h} in your
42 programs.
44 @node Initialization
45 @subsection Initialization
47 GnuTLS must be initialized before it can be used.  The library is
48 initialized by calling @ref{gnutls_global_init}.  The resources
49 allocated by the initialization process can be released if the
50 application no longer has a need to call GnuTLS functions, this is
51 done by calling @ref{gnutls_global_deinit}.
53 The extra functionality of the @acronym{GnuTLS-extra} library is
54 available after calling @ref{gnutls_global_init_extra}.
56 In order to take advantage of the internationalisation features in
57 GnuTLS, such as translated error messages, the application must set
58 the current locale using @code{setlocale} before initializing GnuTLS.
60 @node Version check
61 @subsection Version Check
63 It is often desirable to check that the version of `gnutls' used is
64 indeed one which fits all requirements.  Even with binary
65 compatibility new features may have been introduced but due to problem
66 with the dynamic linker an old version is actually used.  So you may
67 want to check that the version is okay right after program startup.
68 See the function @ref{gnutls_check_version}.
70 @node Debugging
71 @subsection Debugging
73 In many cases things may not go as expected and further information,
74 to assist debugging, from @acronym{GnuTLS} is desired. Those are the
75 case where the @ref{gnutls_global_set_log_level} and
76 @ref{gnutls_global_set_log_function} are to be used. Those will print
77 verbose information on the @acronym{GnuTLS} functions internal flow.
79 @node Building the source
80 @subsection Building the Source
82 If you want to compile a source file including the
83 @file{gnutls/gnutls.h} header file, you must make sure that the
84 compiler can find it in the directory hierarchy.  This is accomplished
85 by adding the path to the directory in which the header file is
86 located to the compilers include file search path (via the @option{-I}
87 option).
89 However, the path to the include file is determined at the time the
90 source is configured.  To solve this problem, the library uses the
91 external package @command{pkg-config} that knows the path to the
92 include file and other configuration options.  The options that need
93 to be added to the compiler invocation at compile time are output by
94 the @option{--cflags} option to @command{pkg-config gnutls}.  The
95 following example shows how it can be used at the command line:
97 @example
98 gcc -c foo.c `pkg-config gnutls --cflags`
99 @end example
101 Adding the output of @samp{pkg-config gnutls --cflags} to the
102 compilers command line will ensure that the compiler can find the
103 @file{gnutls/gnutls.h} header file.
105 A similar problem occurs when linking the program with the library.
106 Again, the compiler has to find the library files.  For this to work,
107 the path to the library files has to be added to the library search
108 path (via the @option{-L} option).  For this, the option
109 @option{--libs} to @command{pkg-config gnutls} can be used.  For
110 convenience, this option also outputs all other options that are
111 required to link the program with the libarary (for instance, the
112 @samp{-ltasn1} option).  The example shows how to link @file{foo.o}
113 with the library to a program @command{foo}.
115 @example
116 gcc -o foo foo.o `pkg-config gnutls --libs`
117 @end example
119 Of course you can also combine both examples to a single command by
120 specifying both options to @command{pkg-config}:
122 @example
123 gcc -o foo foo.c `pkg-config gnutls --cflags --libs`
124 @end example
126 @node Multi-threaded applications
127 @section Multi-Threaded Applications
129 Although the @acronym{GnuTLS} library is thread safe by design, some
130 parts of the cryptographic backend, such as the random generator, are not.
131 Applications can either call @ref{gnutls_global_init} and use the default 
132 operating system provided locks (i.e. @code{pthreads} on GNU/Linux), or
133 specify manualy the locking system using the function @ref{gnutls_global_set_mutex}
134 before calling @ref{gnutls_global_init}. Setting manually mutexes is recommended
135 only to applications that have full control of the underlying libraries. If this
136 is not the case, the use of the operating system defaults is recommended.
139 There are helper macros to help you properly initialize the libraries.
140 Examples are shown below.
142 @itemize
144 @item POSIX threads in GNU/Linux
145 @example
146 #include <gnutls.h>
147 #include <errno.h>
148 #include <pthread.h>
150 int main()
152    gnutls_global_init();
154 @end example
156 @item Other thread packages
157 @example
159 int main()
161    gnutls_global_mutex_set (mutex_init, mutex_deinit, mutex_lock, mutex_unlock);
162    gnutls_global_init();
164 @end example
165 @end itemize
167 @node Client examples
168 @section Client Examples
170 This section contains examples of @acronym{TLS} and @acronym{SSL}
171 clients, using @acronym{GnuTLS}.  Note that these examples contain
172 little or no error checking.  Some of the examples require functions
173 implemented by another example.
175 @menu
176 * Simple client example with anonymous authentication::
177 * Simple client example with X.509 certificate support::
178 * Obtaining session information::
179 * Verifying peer's certificate::
180 * Using a callback to select the certificate to use::
181 * Verifying a certificate::
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 @node Using a callback to select the certificate to use
238 @subsection Using a Callback to Select the Certificate to Use
240 There are cases where a client holds several certificate and key
241 pairs, and may not want to load all of them in the credentials
242 structure.  The following example demonstrates the use of the
243 certificate selection callback.
245 @verbatiminclude examples/ex-cert-select.c
247 @node Verifying a certificate
248 @subsection Verifying a Certificate
249 @anchor{ex:verify2}
251 An example is listed below which uses the high level verification
252 functions to verify a given certificate list.
254 @verbatiminclude examples/ex-verify.c
256 @node Client using a PKCS #11 token with TLS
257 @subsection Using a @acronym{PKCS #11} token with TLS
258 @anchor{ex:pkcs11-client}
260 This example will demonstrate how to load keys and certificates
261 from a @acronym{PKCS} #11 token, and use it with a TLS connection.
263 @verbatiminclude examples/ex-cert-select-pkcs11.c
266 @node Client with Resume capability example
267 @subsection Client with Resume Capability Example
268 @anchor{ex:resume-client}
270 This is a modification of the simple client example. Here we
271 demonstrate the use of session resumption. The client tries to connect
272 once using @acronym{TLS}, close the connection and then try to
273 establish a new connection using the previously negotiated data.
275 @verbatiminclude examples/ex-client-resume.c
278 @node Simple client example with SRP authentication
279 @subsection Simple Client Example with @acronym{SRP} Authentication
281 The following client is a very simple @acronym{SRP} @acronym{TLS}
282 client which connects to a server and authenticates using a
283 @emph{username} and a @emph{password}. The server may authenticate
284 itself using a certificate, and in that case it has to be verified.
286 @verbatiminclude examples/ex-client-srp.c
288 @node Simple client example in C++
289 @subsection Simple Client Example using the C++ API
291 The following client is a simple example of a client client utilizing
292 the GnuTLS C++ API.
294 @verbatiminclude examples/ex-cxx.cpp
296 @node Helper function for TCP connections
297 @subsection Helper Function for TCP Connections
299 This helper function abstracts away TCP connection handling from the
300 other examples.  It is required to build some examples.
302 @verbatiminclude examples/tcp.c
304 @node Server examples
305 @section Server Examples
307 This section contains examples of @acronym{TLS} and @acronym{SSL}
308 servers, using @acronym{GnuTLS}.
310 @menu
311 * Echo Server with X.509 authentication::
312 * Echo Server with OpenPGP authentication::
313 * Echo Server with SRP authentication::
314 * Echo Server with anonymous authentication::
315 @end menu
317 @node Echo Server with X.509 authentication
318 @subsection Echo Server with @acronym{X.509} Authentication
320 This example is a very simple echo server which supports
321 @acronym{X.509} authentication, using the RSA ciphersuites.
323 @verbatiminclude examples/ex-serv1.c
325 @node Echo Server with OpenPGP authentication
326 @subsection Echo Server with @acronym{OpenPGP} Authentication
327 @cindex @acronym{OpenPGP} Server
329 The following example is an echo server which supports
330 @acronym{@acronym{OpenPGP}} key authentication. You can easily combine
331 this functionality ---that is have a server that supports both
332 @acronym{X.509} and @acronym{OpenPGP} certificates--- but we separated
333 them to keep these examples as simple as possible.
335 @verbatiminclude examples/ex-serv-pgp.c
337 @node Echo Server with SRP authentication
338 @subsection Echo Server with @acronym{SRP} Authentication
340 This is a server which supports @acronym{SRP} authentication. It is
341 also possible to combine this functionality with a certificate
342 server. Here it is separate for simplicity.
344 @verbatiminclude examples/ex-serv-srp.c
346 @node Echo Server with anonymous authentication
347 @subsection Echo Server with Anonymous Authentication
349 This example server support anonymous authentication, and could be
350 used to serve the example client for anonymous authentication.
352 @verbatiminclude examples/ex-serv-anon.c
354 @node Miscellaneous examples
355 @section Miscellaneous Examples
357 @menu
358 * Checking for an alert::
359 * X.509 certificate parsing example::
360 * Certificate request generation::
361 * PKCS #12 structure generation::
362 @end menu
364 @node Checking for an alert
365 @subsection Checking for an Alert
367 This is a function that checks if an alert has been received in the
368 current session.
370 @verbatiminclude examples/ex-alert.c
372 @node X.509 certificate parsing example
373 @subsection @acronym{X.509} Certificate Parsing Example
374 @anchor{ex:x509-info}
376 To demonstrate the @acronym{X.509} parsing capabilities an example program is
377 listed below.  That program reads the peer's certificate, and prints
378 information about it.
380 @verbatiminclude examples/ex-x509-info.c
382 @node Certificate request generation
383 @subsection Certificate Request Generation
384 @anchor{ex:crq}
386 The following example is about generating a certificate request, and a
387 private key. A certificate request can be later be processed by a CA,
388 which should return a signed certificate.
390 @verbatiminclude examples/ex-crq.c
392 @node PKCS #12 structure generation
393 @subsection @acronym{PKCS} #12 Structure Generation
394 @anchor{ex:pkcs12}
396 The following example is about generating a @acronym{PKCS} #12
397 structure.
399 @verbatiminclude examples/ex-pkcs12.c
401 @node Compatibility with the OpenSSL library
402 @section Compatibility with the OpenSSL Library
403 @cindex OpenSSL
405 To ease @acronym{GnuTLS}' integration with existing applications, a
406 compatibility layer with the widely used OpenSSL library is included
407 in the @code{gnutls-openssl} library. This compatibility layer is not
408 complete and it is not intended to completely reimplement the OpenSSL
409 API with @acronym{GnuTLS}.  It only provides source-level
410 compatibility. There is currently no attempt to make it
411 binary-compatible with OpenSSL.
413 The prototypes for the compatibility functions are in the
414 @file{gnutls/openssl.h} header file.
416 Current limitations imposed by the compatibility layer include:
418 @itemize
420 @item Error handling is not thread safe.
422 @end itemize
424 @node Keying Material Exporters
425 @section Keying Material Exporters
426 @cindex Keying Material Exporters
427 @cindex Exporting Keying Material
429 The TLS PRF can be used by other protocols to derive data.  The API to
430 use is @ref{gnutls_prf}.  The function needs to be provided with the
431 label in the parameter @code{label}, and the extra data to mix in the
432 @code{extra} parameter.  Depending on whether you want to mix in the
433 client or server random data first, you can set the
434 @code{server_random_first} parameter.
436 For example, after establishing a TLS session using
437 @ref{gnutls_handshake}, you can invoke the TLS PRF with this call:
439 @smallexample
440 #define MYLABEL "EXPORTER-FOO"
441 #define MYCONTEXT "some context data"
442 char out[32];
443 rc = gnutls_prf (session, strlen (MYLABEL), MYLABEL, 0,
444                  strlen (MYCONTEXT), MYCONTEXT, 32, out);
445 @end smallexample
447 If you don't want to mix in the client/server random, there is a more
448 low-level TLS PRF interface called @ref{gnutls_prf_raw}.
450 @node Channel Bindings
451 @section Channel Bindings
452 @cindex Channel Bindings
454 In user authentication protocols (e.g., EAP or SASL mechanisms) it is
455 useful to have a unique string that identifies the secure channel that
456 is used, to bind together the user authentication with the secure
457 channel.  This can protect against man-in-the-middle attacks in some
458 situations.  The unique strings is a ``channel bindings''.  For
459 background and more discussion see @xcite{RFC5056}.
461 You can extract a channel bindings using the
462 @ref{gnutls_session_channel_binding} function.  Currently only the
463 @code{GNUTLS_CB_TLS_UNIQUE} type is supported, which corresponds to
464 the @code{tls-unique} channel bindings for TLS defined in
465 @xcite{RFC5929}.
467 The following example describes how to print the channel binding data.
468 Note that it must be run after a successful TLS handshake.
470 @smallexample
472   gnutls_datum cb;
473   int rc;
475   rc = gnutls_session_channel_binding (session,
476                                        GNUTLS_CB_TLS_UNIQUE,
477                                        &cb);
478   if (rc)
479     fprintf (stderr, "Channel binding error: %s\n",
480              gnutls_strerror (rc));
481   else
482     @{
483       size_t i;
484       printf ("- Channel binding 'tls-unique': ");
485       for (i = 0; i < cb.size; i++)
486         printf ("%02x", cb.data[i]);
487       printf ("\n");
488     @}
490 @end smallexample