mention retrieve_function2
[gnutls.git] / doc / cha-gtls-app.texi
blob2f73f5cb5e51006d0f8118cc0a039b2c2d081f35
1 @node How to use GnuTLS in applications
2 @chapter How to use @acronym{GnuTLS} in applications
4 @menu
5 * Introduction to the library::
6 * Preparation::
7 * Session initialization::
8 * Associating the credentials::
9 * Setting up the transport layer::
10 * TLS handshake::
11 * Data transfer and termination::
12 * Handling alerts::
13 * Priority Strings::
14 * Advanced and other topics::
15 * Using the cryptographic library::
16 * Selecting cryptographic key sizes::
17 @end menu
19 @node Introduction to the library
20 @section Introduction
22 @menu
23 * General idea::
24 * Error handling::
25 * Common types::
26 * Debugging and auditing::
27 * Thread safety::
28 * Callback functions::
29 @end menu
31 @node General idea
32 @subsection General idea
34 A brief description of how @acronym{GnuTLS} works internally is shown
35 at @ref{fig:gnutls-design}. This section may become more clear after
36 having read the rest of this section.
37 As shown in the figure, there is a read-only global state that is
38 initialized once by the global initialization function.  This global
39 structure, among others, contains the memory allocation functions
40 used, and structures needed for the @acronym{ASN.1} parser.  This
41 structure is never modified by any @acronym{GnuTLS} function, except
42 for the deinitialization function which frees all allocated memory
43 and is called after the program has permanently
44 finished using @acronym{GnuTLS}.
46 @float Figure,fig:gnutls-design
47 @image{gnutls-internals,12cm}
48 @caption{High level design of GnuTLS.}
49 @end float
51 The credentials structures are used by the authentication methods, such
52 as certificate authentication. They store certificates, privates keys,
53 and other information that is needed to prove the identity to the peer,
54 and/or verify the indentity of the peer. The information stored in
55 the credentials structures is initialized once and then can be 
56 shared by many @acronym{TLS} sessions.
58 A @acronym{GnuTLS} session contains all the required information
59 to handle one secure connection. The session communicates with the
60 peers using the provided functions of the transport layer.
61 Every session has a unique session ID shared with the peer.
63 Since TLS sessions can be resumed, servers need a
64 database back-end to hold the session's parameters.  Every
65 @acronym{GnuTLS} session after a successful handshake calls the
66 appropriate back-end function (see @ref{resume})
67 to store the newly negotiated session. The session
68 database is examined by the server just after having received the
69 client hello@footnote{The first message in a @acronym{TLS} handshake},
70 and if the session ID sent by the client, matches a stored session,
71 the stored session will be retrieved, and the new session will be a
72 resumed one, and will share the same session ID with the previous one.
74 @node Error handling
75 @subsection Error handling
77 In @acronym{GnuTLS} most functions return an integer type as a result.
78 In almost all cases a zero or a positive number means success, and a
79 negative number indicates failure, or a situation that some action has
80 to be taken. Thus negative error codes may be fatal or not.
82 Fatal errors terminate the connection immediately and further sends
83 and receives will be disallowed.  Such an example is
84 @code{GNUTLS_@-E_@-DECRYPTION_@-FAILED}. Non-fatal errors may warn about
85 something, i.e., a warning alert was received, or indicate the some
86 action has to be taken. This is the case with the error code
87 @code{GNUTLS_@-E_@-REHANDSHAKE} returned by @funcref{gnutls_record_recv}.
88 This error code indicates that the server requests a re-handshake. The
89 client may ignore this request, or may reply with an alert.  You can
90 test if an error code is a fatal one by using the
91 @funcref{gnutls_error_is_fatal}.
92 All errors can be converted to a descriptive string using @funcref{gnutls_strerror}.
94 If any non fatal errors, that require an action, are to be returned by
95 a function, these error codes will be documented in the function's
96 reference. For example the error codes @code{GNUTLS_@-E_@-WARNING_@-ALERT_@-RECEIVED} and @code{GNUTLS_@-E_@-FATAL_@-ALERT_@-RECEIVED}
97 that may returned when receiving data, should be handled by notifying the
98 user of the alert (as explained in @ref{Handling alerts}).
99 See @ref{Error codes}, for a description of the available error codes.
101 @node Common types
102 @subsection Common types
104 Several functions in @acronym{GnuTLS} use @code{gnutls_datum_t} which is
105 convenient way to combine a pointer to data and data's size. Its definition is
106 shown below.
107 @verbatim
108   typedef struct
109   {
110     unsigned char *data;
111     unsigned int size;
112   } gnutls_datum_t;
113 @end verbatim
115 Other functions that require data for scattered read use a structure similar
116 to @code{struct iovec} typically used by @funcintref{readv}. It is shown
117 below.
118 @verbatim
119   typedef struct
120   {
121     void *iov_base;             /* Starting address */
122     size_t iov_len;             /* Number of bytes to transfer */
123   } giovec_t;
124 @end verbatim
127 @node Debugging and auditing
128 @subsection Debugging and auditing
130 In many cases things may not go as expected and further information,
131 to assist debugging, from @acronym{GnuTLS} is desired. 
132 Those are the cases where the @funcref{gnutls_global_set_log_level} and
133 @funcref{gnutls_global_set_log_function} are to be used. Those will print
134 verbose information on the @acronym{GnuTLS} functions internal flow.
136 @showfuncB{gnutls_global_set_log_level,gnutls_global_set_log_function}
138 When debugging is not required, important issues, such as detected
139 attacks on the protocol still need to be logged. This is provided
140 by the logging function set by
141 @funcref{gnutls_global_set_audit_log_function}. The provided function
142 will receive an message and the corresponding
143 TLS session. The session information might be used to derive IP addresses
144 or other information about the peer involved.
146 @showfuncdesc{gnutls_global_set_audit_log_function}
148 @node Thread safety
149 @subsection Thread safety
150 @cindex thread safety
152 The @acronym{GnuTLS} library is thread safe by design, meaning that
153 objects of the library such as TLS sessions, can be safely divided across
154 threads as long as a single thread accesses a single object. This is
155 sufficient to support a server which handles several sessions per thread.
156 If, however, an object needs to be shared across threads then access must be 
157 protected with a mutex. Read-only access to objects, for example the
158 credentials holding structures, is also thread-safe. 
160 The random generator of the cryptographic back-end, is not thread safe and requires
161 mutex locks which are setup by @acronym{GnuTLS}.
162 Applications can either call @funcref{gnutls_global_init} which will initialize the default
163 operating system provided locks (i.e. @code{pthreads} on GNU/Linux and
164 @code{CriticalSection} on Windows), or manually specify the locking system using
165 the function @funcref{gnutls_global_set_mutex} before calling @funcref{gnutls_global_init}. 
166 Setting mutexes manually is recommended
167 only for applications that have full control of the underlying libraries. If this
168 is not the case, the use of the operating system defaults is recommended. An example of 
169 non-native thread usage is shown below.
171 @example
172 #include <gnutls/gnutls.h>
174 int main()
176    /* When the system mutexes are not to be used 
177     * gnutls_global_set_mutex() must be called explicitly
178     */
179    gnutls_global_set_mutex (mutex_init, mutex_deinit, 
180                             mutex_lock, mutex_unlock);
181    gnutls_global_init();
183 @end example
185 @showfuncdesc{gnutls_global_set_mutex}
187 @node Callback functions
188 @subsection Callback functions
189 @cindex callback functions
191 There are several cases where @acronym{GnuTLS} may need out of
192 band input from your program. This is now implemented using some
193 callback functions, which your program is expected to register.
195 An example of this type of functions are the push and pull callbacks
196 which are used to specify the functions that will retrieve and send
197 data to the transport layer.
199 @showfuncB{gnutls_transport_set_push_function,gnutls_transport_set_pull_function}
201 Other callback functions may require more complicated input and data
202 to be allocated. Such an example is 
203 @funcref{gnutls_srp_set_server_credentials_function}.
204 All callbacks should allocate and free memory using 
205 @funcintref{gnutls_malloc} and @funcintref{gnutls_free}.
208 @node Preparation
209 @section Preparation
211 To use @acronym{GnuTLS}, you have to perform some changes to your
212 sources and your build system. The necessary changes are explained in
213 the following subsections.
215 @menu
216 * Headers::
217 * Initialization::
218 * Version check::
219 * Building the source::
220 @end menu
222 @node Headers
223 @subsection Headers
225 All the data types and functions of the @acronym{GnuTLS} library are
226 defined in the header file @file{gnutls/gnutls.h}.  This must be
227 included in all programs that make use of the @acronym{GnuTLS}
228 library.
230 @node Initialization
231 @subsection Initialization
233 GnuTLS must be initialized before it can be used.  The library is
234 initialized by calling @funcref{gnutls_global_init}.  The resources
235 allocated by the initialization process can be released if the
236 application no longer has a need to call GnuTLS functions, this is
237 done by calling @funcref{gnutls_global_deinit}.
239 In order to take advantage of the internationalization features in
240 GnuTLS, such as translated error messages, the application must set
241 the current locale using @code{setlocale} before initializing GnuTLS.
243 @node Version check
244 @subsection Version check
246 It is often desirable to check that the version of `gnutls' used is
247 indeed one which fits all requirements.  Even with binary
248 compatibility new features may have been introduced but due to problem
249 with the dynamic linker an old version is actually used.  So you may
250 want to check that the version is okay right after program start-up.
251 See the function @funcref{gnutls_check_version}.
253 @node Building the source
254 @subsection Building the source
256 If you want to compile a source file including the
257 @file{gnutls/gnutls.h} header file, you must make sure that the
258 compiler can find it in the directory hierarchy.  This is accomplished
259 by adding the path to the directory in which the header file is
260 located to the compilers include file search path (via the @option{-I}
261 option).
263 However, the path to the include file is determined at the time the
264 source is configured.  To solve this problem, the library uses the
265 external package @command{pkg-config} that knows the path to the
266 include file and other configuration options.  The options that need
267 to be added to the compiler invocation at compile time are output by
268 the @option{--cflags} option to @command{pkg-config gnutls}.  The
269 following example shows how it can be used at the command line:
271 @example
272 gcc -c foo.c `pkg-config gnutls --cflags`
273 @end example
275 Adding the output of @samp{pkg-config gnutls --cflags} to the
276 compilers command line will ensure that the compiler can find the
277 @file{gnutls/gnutls.h} header file.
279 A similar problem occurs when linking the program with the library.
280 Again, the compiler has to find the library files.  For this to work,
281 the path to the library files has to be added to the library search
282 path (via the @option{-L} option).  For this, the option
283 @option{--libs} to @command{pkg-config gnutls} can be used.  For
284 convenience, this option also outputs all other options that are
285 required to link the program with the library (for instance, the
286 @samp{-ltasn1} option).  The example shows how to link @file{foo.o}
287 with the library to a program @command{foo}.
289 @example
290 gcc -o foo foo.o `pkg-config gnutls --libs`
291 @end example
293 Of course you can also combine both examples to a single command by
294 specifying both options to @command{pkg-config}:
296 @example
297 gcc -o foo foo.c `pkg-config gnutls --cflags --libs`
298 @end example
300 When a program uses the GNU autoconf system, then the following
301 line or similar can be used to detect the presence of GnuTLS.
303 @example
304 PKG_CHECK_MODULES([LIBGNUTLS], [gnutls >= 3.0.0])
306 AC_SUBST([LIBGNUTLS_CFLAGS])
307 AC_SUBST([LIBGNUTLS_LIBS])
308 @end example
310 @node Session initialization
311 @section Session initialization
313 In the previous sections we have discussed the global initialization
314 required for GnuTLS as well as the initialization required for each
315 authentication method's credentials (see @ref{Authentication}).
316 In this section we elaborate on the TLS or DTLS session initiation.
317 Each session is initialized using @funcref{gnutls_init} which among
318 others is used to specify the type of the connection (server or client), 
319 and the underlying protocol type, i.e., datagram (UDP) or reliable (TCP).
321 @showfuncdesc{gnutls_init}
323 After the session initialization details on the allowed ciphersuites
324 and protocol versions should be set using the priority functions
325 such as @funcref{gnutls_priority_set_direct}. We elaborate on them
326 in @ref{Priority Strings}.
327 The credentials used for the key exchange method, such as certificates 
328 or usernames and passwords should also be associated with the session
329 current session using @funcref{gnutls_credentials_set}. 
331 @showfuncdesc{gnutls_credentials_set}
333 @node Associating the credentials
334 @section Associating the credentials
336 @menu
337 * Certificate credentials::
338 * SRP credentials::
339 * PSK credentials::
340 * Anonymous credentials::
341 @end menu
343 Each authentication method is associated with a key exchange method, and a credentials type. 
344 The contents of the credentials is method-dependent, e.g. certificates
345 for certificate authentication and should be initialized and associated
346 with a session (see @funcref{gnutls_credentials_set}).  A mapping of the key exchange methods
347 with the credential types is shown in @ref{tab:key-exchange-cred}.
349 @float Table,tab:key-exchange-cred
350 @multitable @columnfractions .25 .25 .2 .2
352 @headitem Authentication method @tab Key exchange @tab Client credentials @tab Server credentials
354 @item Certificate
355 @tab @code{KX_RSA},
356 @code{KX_DHE_RSA},
357 @code{KX_DHE_DSS},
358 @code{KX_ECDHE_RSA},
359 @code{KX_ECDHE_ECDSA},
360 @code{KX_RSA_EXPORT}
361 @tab @code{CRD_CERTIFICATE}
362 @tab @code{CRD_CERTIFICATE}
364 @item Password and certificate
365 @tab @code{KX_SRP_RSA}, @code{KX_SRP_DSS}
366 @tab @code{CRD_SRP}
367 @tab @code{CRD_CERTIFICATE}, @code{CRD_SRP}
369 @item Password
370 @tab @code{KX_SRP}
371 @tab @code{CRD_SRP}
372 @tab @code{CRD_SRP}
374 @item Anonymous
375 @tab @code{KX_ANON_DH},
376 @code{KX_ANON_ECDH}
377 @tab @code{CRD_ANON}
378 @tab @code{CRD_ANON}
380 @item Pre-shared key
381 @tab @code{KX_PSK},
382 @code{KX_DHE_PSK}, @code{KX_ECDHE_PSK}
383 @tab @code{CRD_PSK}
384 @tab @code{CRD_PSK}
386 @end multitable
387 @caption{Key exchange algorithms and the corresponding credential types.}
388 @end float
390 @node Certificate credentials
391 @subsection Certificates
392 @subsubheading Server certificate authentication
394 When using certificates the server is required to have at least one
395 certificate and private key pair. Clients may not hold such
396 a pair, but a server could require it. In this section we discuss
397 general issues applying to both client and server certificates. The next
398 section will elaborate on issues arising from client authentication only.
400 @showfuncB{gnutls_certificate_allocate_credentials,gnutls_certificate_free_credentials}
402 After the credentials structures are initialized, the certificate 
403 and key pair must be loaded. This occurs before any @acronym{TLS} 
404 session is initialized, and the same structures are reused for multiple sessions.
405 Depending on the certificate type different loading functions
406 are available, as shown below.
407 For @acronym{X.509} certificates, the functions will
408 accept and use a certificate chain that leads to a trusted
409 authority. The certificate chain must be ordered in such way that every
410 certificate certifies the one before it. The trusted authority's
411 certificate need not to be included since the peer should possess it
412 already.
414 @showfuncC{gnutls_certificate_set_x509_key_mem,gnutls_certificate_set_x509_key,gnutls_certificate_set_x509_key_file}
416 @showfuncD{gnutls_certificate_set_openpgp_key_mem,gnutls_certificate_set_openpgp_key,gnutls_certificate_set_openpgp_key_file,gnutls_certificate_set_key}
418 If multiple certificates are used with the functions above each
419 client's request will be served with the certificate that matches the
420 requested name (see @ref{Server name indication}).
422 As an alternative to loading from files or buffers, a callback may be used for the 
423 server or the client to specify the certificate and the key at the handshake time.
424 In that case a certificate should be selected according the peer's signature
425 algorithm preferences. To get those preferences use
426 @funcref{gnutls_sign_algorithm_get_requested}. Both functions are shown below.
428 @showfuncC{gnutls_certificate_set_retrieve_function,gnutls_certificate_retrieve_function2,gnutls_sign_algorithm_get_requested}
430 The functions above do not handle the requested server name automatically.
431 A server would need to check the name requested by the client
432 using @funcref{gnutls_server_name_get}, and serve the appropriate
433 certificate.
435 In a handshake, the negotiated cipher suite depends on the
436 certificate's parameters, so some key exchange methods might not be
437 available with all certificates. @acronym{GnuTLS} will disable
438 ciphersuites that are not compatible with the key, or the enabled
439 authentication methods.  For example keys marked as sign-only, will
440 not be able to access the plain RSA ciphersuites, that require
441 decryption. It is not recommended to use RSA keys for both
442 signing and encryption. If possible use a different key for the
443 @code{DHE-RSA} which uses signing and @code{RSA} that requires decryption.
444 All the key exchange methods shown in @ref{tab:key-exchange} are
445 available in certificate authentication.
448 @subsubheading Client certificate authentication
450 If a certificate is to be requested from the client during the handshake, the server
451 will send a certificate request message. This behavior is controlled @funcref{gnutls_certificate_server_set_request}.
452 The request contains a list of the acceptable by the server certificate signers. This list
453 is constructed using the trusted certificate authorities of the server.
454 In cases where the server supports a large number of certificate authorities
455 it makes sense not to advertise all of the names to save bandwidth. That can
456 be controlled using the function @funcref{gnutls_certificate_send_x509_rdn_sequence}. 
457 This however will have the side-effect of not restricting the client to certificates
458 signed by server's acceptable signers.
460 @showfuncdesc{gnutls_certificate_server_set_request}
462 @showfuncdesc{gnutls_certificate_send_x509_rdn_sequence}
465 @subsubheading Client or server certificate verification
467 Certificate verification is possible by loading the trusted
468 authorities into the credentials structure by using
469 the following functions, applicable to X.509 and OpenPGP certificates.
471 @showfuncB{gnutls_certificate_set_x509_trust_file,gnutls_certificate_set_openpgp_keyring_file}
473 The peer's certificate is not automatically verified and one 
474 should call @funcref{gnutls_certificate_verify_peers2}
475 after a successful handshake to verify the certificate's signature.
476 Alternative the verification can occur during the handshake
477 by using @funcref{gnutls_certificate_set_verify_function}.
479 In order to report a detailed verification output, an alternative
480 way has to be used. For that, one should call @funcref{gnutls_certificate_get_peers} 
481 to obtain the raw certificate of the peer and verify it using the
482 functions discussed in @ref{X.509 certificates}.
484 @showfuncdesc{gnutls_certificate_verify_peers2}
486 @showfuncdesc{gnutls_certificate_set_verify_function}
490 @node SRP credentials
491 @subsection SRP
493 The initialization functions in SRP credentials differ between
494 client and server.
495 Clients supporting @acronym{SRP} should set the username and password
496 prior to connection, to the credentials structure.
497 Alternatively @funcref{gnutls_srp_set_client_credentials_function}
498 may be used instead, to specify a callback function that should return the
499 SRP username and password.
500 The callback is called once during the @acronym{TLS} handshake.
502 @showfuncE{gnutls_srp_allocate_server_credentials,gnutls_srp_allocate_client_credentials,gnutls_srp_free_server_credentials,gnutls_srp_free_client_credentials,gnutls_srp_set_client_credentials}
504 @showfuncdesc{gnutls_srp_set_client_credentials_function}
506 In server side the default behavior of @acronym{GnuTLS} is to read
507 the usernames and @acronym{SRP} verifiers from password files. These
508 password file format is compatible the with the @emph{Stanford srp libraries}
509 format.  If a different password file format is to be used, then 
510 @funcref{gnutls_srp_set_server_credentials_function} should be called,
511 to set an appropriate callback. 
513 @showfuncdesc{gnutls_srp_set_server_credentials_file}
515 @showfuncdesc{gnutls_srp_set_server_credentials_function}
518 @node PSK credentials
519 @subsection PSK
520 The initialization functions in PSK credentials differ between
521 client and server.
523 @showfuncD{gnutls_psk_allocate_server_credentials,gnutls_psk_allocate_client_credentials,gnutls_psk_free_server_credentials,gnutls_psk_free_client_credentials}
525 Clients supporting @acronym{PSK} should supply the username and key
526 before a TLS session is established.  Alternatively 
527 @funcref{gnutls_psk_set_client_credentials_function} can be used to
528 specify a callback function. This has the
529 advantage that the callback will be called only if @acronym{PSK} has
530 been negotiated.
532 @showfuncA{gnutls_psk_set_client_credentials}
534 @showfuncdesc{gnutls_psk_set_client_credentials_function}
536 In server side the default behavior of @acronym{GnuTLS} is to read
537 the usernames and @acronym{PSK} keys from a password file. The
538 password file should contain usernames and keys in hexadecimal
539 format. The name of the password file can be stored to the credentials
540 structure by calling @funcref{gnutls_psk_set_server_credentials_file}.  If
541 a different password file format is to be used, then
542 a callback should be set instead by @funcref{gnutls_psk_set_server_credentials_function}.
544 The server can help the client chose a suitable username and password,
545 by sending a hint. Note that there is no common profile for the PSK hint and applications
546 are discouraged to use it.
547 A server, may specify the hint by calling
548 @funcref{gnutls_psk_set_server_credentials_hint}.  The client can retrieve
549 the hint, for example in the callback function, using
550 @funcref{gnutls_psk_client_get_hint}.
552 @showfuncdesc{gnutls_psk_set_server_credentials_file}
554 @showfuncC{gnutls_psk_set_server_credentials_function,gnutls_psk_set_server_credentials_hint,gnutls_psk_client_get_hint}
556 @node Anonymous credentials
557 @subsection Anonymous
558 The key exchange methods for anonymous authentication
559 might require Diffie-Hellman parameters to be generated by the server and
560 associated with an anonymous credentials structure. Check
561 @ref{Parameter generation} for more information.
562 The initialization functions for the credentials are shown below.
564 @showfuncD{gnutls_anon_allocate_server_credentials,gnutls_anon_allocate_client_credentials,gnutls_anon_free_server_credentials,gnutls_anon_free_client_credentials}
568 @node Setting up the transport layer
569 @section Setting up the transport layer
571 The next step is to setup the underlying transport layer details. The
572 Berkeley sockets are implicitly used by GnuTLS, thus a
573 call to @funcref{gnutls_transport_set_ptr2} would be sufficient to
574 specify the socket descriptor.
576 @showfuncdesc{gnutls_transport_set_ptr2}
578 @showfuncA{gnutls_transport_set_ptr}
580 If however another transport layer than TCP is selected, then
581 the following functions have to be specified.
583 @showfuncdesc{gnutls_transport_set_push_function}
584 @showfuncdesc{gnutls_transport_set_vec_push_function}
585 @showfuncdesc{gnutls_transport_set_pull_function}
587 The functions above accept a callback function which
588 should return the number of bytes written, or -1 on
589 error and should set @code{errno} appropriately.
590 In some environments, setting @code{errno} is unreliable. For example
591 Windows have several errno variables in different CRTs, or in other
592 systems it may be a non thread-local variable.  If this is a concern to
593 you, call @funcref{gnutls_transport_set_errno} with the intended errno
594 value instead of setting @code{errno} directly.
596 @showfuncdesc{gnutls_transport_set_errno}
598 @acronym{GnuTLS} currently only interprets the EINTR and EAGAIN errno
599 values and returns the corresponding @acronym{GnuTLS} error codes:
600 @itemize
601 @item @code{GNUTLS_E_INTERRUPTED} 
602 @item @code{GNUTLS_E_AGAIN}
603 @end itemize
604 The EINTR and EAGAIN values are returned by interrupted system calls, 
605 or when non blocking IO is used.  All @acronym{GnuTLS} functions can be 
606 resumed (called again), if any of the above error codes is returned.  
608 In the case of DTLS it is also desirable to override the generic 
609 transport functions with functions that emulate the operation
610 of @code{recvfrom} and @code{sendto}. In addition
611 @acronym{DTLS} requires timers during the receive of a handshake
612 message, set using the @funcref{gnutls_transport_set_pull_timeout_function} 
613 function. To check the retransmission timers the function
614 @funcref{gnutls_dtls_get_timeout} is provided, which returns the time
615 remaining until the next retransmission, or better the time until 
616 @funcref{gnutls_handshake} should be called again.
618 @showfuncdesc{gnutls_transport_set_pull_timeout_function}
619 @showfuncdesc{gnutls_dtls_get_timeout}
621 @menu
622 * Asynchronous operation::
623 * DTLS sessions::
624 @end menu
626 @node Asynchronous operation
627 @subsection Asynchronous operation
628 @acronym{GnuTLS} can be used with asynchronous socket or event-driven programming.
629 The approach is similar to using Berkeley sockets under such an environment.
630 The blocking, due to network interaction, calls such as
631 @funcref{gnutls_handshake}, @funcref{gnutls_record_recv},
632 can be set to non-blocking by setting the underlying sockets to non-blocking.
633 If other push and pull functions are setup, then they should behave the same
634 way as @funcintref{recv} and @funcintref{send} when used in a non-blocking
635 way, i.e., set errno to @code{EAGAIN}. Since, during a TLS protocol session 
636 @acronym{GnuTLS} does not block except for network interaction, the non blocking
637 @code{EAGAIN} errno will be propagated and @acronym{GnuTLS} functions 
638 will return the @code{GNUTLS_E_AGAIN} error code. Such calls can be resumed the 
639 same way as a system call would. 
640 The only exception is @funcref{gnutls_record_send},
641 which if interrupted subsequent calls need not to include the data to be
642 sent (can be called with NULL argument).
644 The @funcintref{select} system call can also be used in combination with the
645 @acronym{GnuTLS} functions. @funcintref{select} allows monitoring of sockets
646 and notifies on them being ready for reading or writing data. Note however
647 that this system call cannot notify on data present in @acronym{GnuTLS}
648 read buffers, it is only applicable to the kernel sockets API. Thus if
649 you are using it for reading from a @acronym{GnuTLS} session, make sure
650 that any cached data are read completely. That can be achieved by checking there 
651 are no data waiting to be read (using @funcref{gnutls_record_check_pending}), 
652 either before the @funcintref{select} system call, or after a call to
653 @funcref{gnutls_record_recv}. @acronym{GnuTLS} does not keep a write buffer,
654 thus when writing no additional actions are required.
656 Although in the TLS protocol implementation each call to receive or send
657 function implies to restoring the same function that was interrupted, in
658 the DTLS protocol this requirement isn't true.
659 There are cases where a retransmission is required, which are indicated by
660 a received message and thus @funcref{gnutls_record_get_direction} must be called 
661 to decide which operation to restore, i.e., send or receive.
662 @showfuncdesc{gnutls_record_get_direction}
664 Moreover, to prevent blocking from DTLS' retransmission timers to block a
665 handshake, the @funcref{gnutls_init} function should be called with the
666 @code{GNUTLS_NONBLOCK} flag set (see @ref{Session initialization}).
669 @node DTLS sessions
670 @subsection DTLS sessions
672 Because datagram TLS can operate over connections where the peer
673 of a server cannot be reliably verified, functionality is available to prevent
674 denial of service attacks. @acronym{GnuTLS} requires a server
675 to generate a secret key that is used to sign a cookie@footnote{A key of 128 bits or 16 bytes should be sufficient for this purpose.}. 
676 That cookie is sent to the client using @funcref{gnutls_dtls_cookie_send}, and 
677 the client must reply using the correct cookie. The server side
678 should verify the initial message sent by client using @funcref{gnutls_dtls_cookie_verify}.
679 If successful the session should be initialized and associated with
680 the cookie using @funcref{gnutls_dtls_prestate_set}, before proceeding to
681 the handshake.
683 @showfuncD{gnutls_key_generate,gnutls_dtls_cookie_send,gnutls_dtls_cookie_verify,gnutls_dtls_prestate_set}
685 Note that the above apply to server side only and they are not mandatory to be
686 used. Not using them, however, allows denial of service attacks.
687 The client side cookie handling is part of @funcref{gnutls_handshake}. 
689 Datagrams are typically restricted by a maximum transfer unit (MTU). For that
690 both client and server side should set the correct maximum transfer unit for
691 the layer underneath @acronym{GnuTLS}. This will allow proper fragmentation
692 of DTLS messages and prevent messages from being silently discarded by the
693 transport layer. The ``correct'' maximum transfer unit can be obtained through
694 a path MTU discovery mechanism @xcite{RFC4821}.
696 @showfuncC{gnutls_dtls_set_mtu,gnutls_dtls_get_mtu,gnutls_dtls_get_data_mtu}
699 @node TLS handshake
700 @section TLS handshake
701 Once a session has been initialized and a network
702 connection has been set up, TLS and DTLS protocols
703 perform a handshake. The handshake is the actual key
704 exchange.
706 @showfuncdesc{gnutls_handshake}
708 The handshake process doesn't ensure the verification
709 of the peer's identity. When certificates are in use,
710 this can be done, either after the handshake is complete, or during 
711 the handshake if @funcref{gnutls_certificate_set_verify_function}
712 has been used. In both cases the @funcref{gnutls_certificate_verify_peers2} function can be
713 used to verify the peer's certificate (see @ref{Certificate authentication}
714 for more information).
716 @showfuncA{gnutls_certificate_verify_peers2}
718 @node Data transfer and termination
719 @section Data transfer and termination
720 Once the handshake is complete and peer's identity
721 has been verified data can be exchanged. The available
722 functions resemble the POSIX @code{recv} and @code{send}
723 functions. It is suggested to use @funcref{gnutls_error_is_fatal}
724 to check whether the error codes returned by these functions are
725 fatal for the protocol or can be ignored.
727 @showfuncdesc{gnutls_record_send}
729 @showfuncdesc{gnutls_record_recv}
731 @showfuncdesc{gnutls_error_is_fatal}
733 Although, in the TLS protocol the receive function can be called
734 at any time, when DTLS is used the GnuTLS receive functions must be
735 called once a message is available for reading, even if no data are
736 expected. This is because in DTLS various (internal) actions
737 may be required due to retransmission timers. Moreover,
738 an extended receive function is shown below, which allows the extraction
739 of the message's sequence number. Due to the unreliable nature of the
740 protocol, this field allows distinguishing out-of-order messages.
742 @showfuncdesc{gnutls_record_recv_seq}
744 The @funcref{gnutls_record_check_pending} helper function is available to 
745 allow checking whether data are available to be read in a @acronym{GnuTLS} session 
746 buffers. Note that this function complements but does not replace @funcintref{select},
747 i.e., @funcref{gnutls_record_check_pending} reports no data to be read, @funcintref{select}
748 should be called to check for data in the network buffers.
750 @showfuncdesc{gnutls_record_check_pending}
751 @showfuncA{gnutls_record_get_direction}
753 Once a TLS or DTLS session is no longer needed, it is
754 recommended to use @funcref{gnutls_bye} to terminate the
755 session. That way the peer is notified securely about the
756 intention of termination, which allows distinguishing it
757 from a malicious connection termination.
758 A session can be deinitialized with the @funcref{gnutls_deinit} function.
760 @showfuncdesc{gnutls_bye}
761 @showfuncdesc{gnutls_deinit}
763 @node Handling alerts
764 @section Handling alerts
765 During a TLS connection alert messages may be exchanged by the
766 two peers. Those messages may be fatal, meaning the connection
767 must be terminated afterwards, or warning when something needs
768 to be reported to the peer, but without interrupting the session.
769 The error codes @code{GNUTLS_E_@-WARNING_@-ALERT_@-RECEIVED}
770 or @code{GNUTLS_E_@-FATAL_@-ALERT_@-RECEIVED} signal those alerts
771 when received, and may be returned by all GnuTLS functions that receive 
772 data from the peer, being @funcref{gnutls_handshake} and @funcref{gnutls_record_recv}.
774 If those error codes are received the alert and its level should be logged
775 or reported to the peer using the functions below.
777 @showfuncdesc{gnutls_alert_get}
778 @showfuncdesc{gnutls_alert_get_name}
780 The peer may also be warned or notified of a fatal issue
781 by using one of the functions below. All the available alerts
782 are listed in @ref{The Alert Protocol}.
784 @showfuncdesc{gnutls_alert_send}
785 @showfuncdesc{gnutls_error_to_alert}
788 @node Priority Strings
789 @section Priority strings
790 @cindex Priority strings
792 In order to specify cipher suite preferences on a TLS session
793 there are priority functions that accept a string
794 specifying the enabled for the handshake algorithms.
795 That string may contain a single initial keyword such as
796 in @ref{tab:prio-keywords} and may be followed by
797 additional algorithm or special keywords.
799 @showfuncB{gnutls_priority_set_direct,gnutls_priority_set}
801 @float Table,tab:prio-keywords
802 @multitable @columnfractions .20 .70
803 @headitem Keyword @tab Description
804 @item PERFORMANCE @tab
805 All the known to be secure ciphersuites are enabled,
806 limited to 128 bit ciphers and sorted by terms of speed
807 performance. The message authenticity security level is of 64 bits or more.
809 @item NORMAL @tab
810 Means all the known to be secure ciphersuites. The ciphers are sorted by security
811 margin, although the 256-bit ciphers are included as a fallback only.
812 The message authenticity security level is of 64 bits or more.
814 @item SECURE128 @tab
815 Means all known to be secure ciphersuites that offer a 
816 security level 128-bit or more and a message authenticity
817 security level of 80 bits or more.
819 @item SECURE192 @tab
820 Means all the known to be secure ciphersuites that offer a 
821 security level 192-bit or more and a message authenticity
822 security level of 128 bits or more.
824 @item SECURE256 @tab
825 Currently alias for SECURE192.
827 @item SUITEB128 @tab
828 Means all the NSA Suite B cryptography (RFC5430) ciphersuites
829 with an 128 bit security level.
831 @item SUITEB192 @tab
832 Means all the NSA Suite B cryptography (RFC5430) ciphersuites
833 with an 192 bit security level.
835 @item EXPORT @tab
836 Means all ciphersuites are enabled, including the
837 low-security 40 bit ciphers.
839 @item NONE @tab
840 Means nothing is enabled.  This disables even protocols and
841 compression methods. It should be followed by the
842 algorithms to be enabled.
844 @end multitable
845 @caption{Supported initial keywords.}
846 @end float
848 Unless the initial keyword is "NONE" the defaults (in preference
849 order) are for TLS protocols TLS 1.2, TLS1.1, TLS1.0, SSL3.0; for
850 compression NULL; for certificate types X.509.
851 In key exchange algorithms when in NORMAL or SECURE levels the
852 perfect forward secrecy algorithms take precedence of the other
853 protocols.  In all cases all the supported key exchange algorithms
854 are enabled@footnote{Except for the RSA-EXPORT which is only enabled in
855 EXPORT level.}.
857 Note that the SECURE levels distinguish between overall security level and
858 message authenticity security level. That is because the message
859 authenticity security level requires the adversary to break
860 the algorithms at real-time during the protocol run, whilst 
861 the overall security level refers to off-line adversaries 
862 (e.g. adversaries breaking the ciphertext years after it was captured).
864 The NONE keyword, if used, must followed by keywords specifying 
865 the algorithms and protocols to be enabled. The other initial keywords may be 
866 followed by such keywords.
867 The order with which every algorithm or protocol
868 is specified is significant. Algorithms specified before others
869 will take precedence. The supported algorithms and protocols
870 are shown in @ref{tab:prio-algorithms}. 
871 To avoid collisions in order to specify a compression algorithm in
872 the priority string you have to prefix it with "COMP-", protocol versions
873 with "VERS-", signature algorithms with "SIGN-" and certificate types with "CTYPE-". 
874 All other algorithms don't need a prefix. Each specified keyword can
875 be prefixed with any of the following characters.
877 @table @asis
878 @item '!' or '-' 
879 appended with an algorithm will remove this algorithm.
880 @item "+" 
881 appended with an algorithm will add this algorithm.
882 @end table
884 @float Table,tab:prio-algorithms
885 @multitable @columnfractions .20 .70
886 @headitem Type @tab Keywords
887 @item Ciphers @tab
888 AES-128-CBC, AES-256-CBC, AES-128-GCM, CAMELLIA-128-CBC,
889 CAMELLIA-256-CBC, ARCFOUR-128, 3DES-CBC ARCFOUR-40. Catch all
890 name is CIPHER-ALL which will add all the algorithms from NORMAL
891 priority.
893 @item Key exchange @tab
894 RSA, DHE-RSA, DHE-DSS, SRP, SRP-RSA, SRP-DSS,
895 PSK, DHE-PSK, ECDHE-RSA, ANON-ECDH, ANON-DH, RSA-EXPORT. The
896 Catch all name is KX-ALL which will add all the algorithms from NORMAL
897 priority.
899 @item MAC @tab
900 MD5, SHA1, SHA256, AEAD (used with
901 GCM ciphers only). All algorithms from NORMAL priority can be accessed with MAC-ALL.
903 @item Compression algorithms @tab
904 COMP-NULL, COMP-DEFLATE. Catch all is COMP-ALL.
906 @item TLS versions @tab
907 VERS-SSL3.0, VERS-TLS1.0, VERS-TLS1.1,
908 VERS-TLS1.2, VERS-DTLS1.0. Catch all is VERS-TLS-ALL.
910 @item Signature algorithms @tab
911 SIGN-RSA-SHA1, SIGN-RSA-SHA224, 
912 SIGN-RSA-SHA256, SIGN-RSA-SHA384, SIGN-RSA-SHA512, SIGN-DSA-SHA1, 
913 SIGN-DSA-SHA224, SIGN-DSA-SHA256, SIGN-RSA-MD5. Catch all
914 is SIGN-ALL. This is only valid for TLS 1.2 and later.
916 @item Elliptic curves @tab
917 CURVE-SECP192R1, CURVE-SECP224R1, CURVE-SECP256R1, CURVE-SECP384R1, CURVE-SECP521R1. Catch all is CURVE-ALL.
919 @end multitable
920 @caption{The supported algorithm keywords in priority strings.}
921 @end float
923 Note that the DHE key exchange methods are generally
924 slower@footnote{It depends on the group used.  Primes with
925 lesser bits are always faster, but also easier to break.  See @ref{Selecting cryptographic key sizes}
926 for the acceptable security levels.} than their elliptic curves counterpart
927 (ECDHE). Moreover the plain Diffie-Hellman key exchange
928 requires parameters to be generated and associated with a credentials
929 structure by the server (see @ref{Parameter generation}). 
931 The available special keywords are shown in @ref{tab:prio-special}. 
933 @float Table,tab:prio-special
934 @multitable @columnfractions .45 .45
935 @headitem Keyword @tab Description
937 @item %COMPAT @tab
938 will enable compatibility mode. It might mean that violations
939 of the protocols are allowed as long as maximum compatibility with
940 problematic clients and servers is achieved. More specifically this
941 string would disable TLS record random padding and tolerate packets
942 over the maximum allowed TLS record.
944 @item %NO_EXTENSIONS @tab
945 will prevent the sending of any TLS extensions in client side. Note
946 that TLS 1.2 requires extensions to be used, as well as safe
947 renegotiation thus this option must be used with care.
949 @item %SERVER_PRECEDENCE @tab
950 The ciphersuite will be selected according to server priorities
951 and not the client's.
953 @item %DISABLE_SAFE_RENEGOTIATION @tab
954 will disable safe renegotiation
955 completely.  Do not use unless you know what you are doing.
956 Testing purposes only.
958 @item %UNSAFE_RENEGOTIATION @tab
959 will allow handshakes and re-handshakes
960 without the safe renegotiation extension.  Note that for clients
961 this mode is insecure (you may be under attack), and for servers it
962 will allow insecure clients to connect (which could be fooled by an
963 attacker).  Do not use unless you know what you are doing and want
964 maximum compatibility.
966 @item %PARTIAL_RENEGOTIATION @tab
967 will allow initial handshakes to proceed,
968 but not re-handshakes.  This leaves the client vulnerable to attack,
969 and servers will be compatible with non-upgraded clients for
970 initial handshakes.  This is currently the default for clients and
971 servers, for compatibility reasons.
973 @item %SAFE_RENEGOTIATION @tab
974 will enforce safe renegotiation.  Clients and
975 servers will refuse to talk to an insecure peer.  Currently this
976 causes interoperability problems, but is required for full protection.
978 @item %SSL3_RECORD_VERSION @tab
979 will use SSL3.0 record version in client hello.
980 This is the default.
982 @item %LATEST_RECORD_VERSION @tab
983 will use the latest TLS version record version in client hello.
985 @item %VERIFY_ALLOW_SIGN_RSA_MD5 @tab
986 will allow RSA-MD5 signatures in certificate chains.
988 @item %VERIFY_ALLOW_X509_V1_CA_CRT @tab
989 will allow V1 CAs in chains.
991 @end multitable
992 @caption{Special priority string keywords.}
993 @end float
995 Finally the ciphersuites enabled by any priority string can be
996 listed using the @code{gnutls-cli} application (see @ref{gnutls-cli Invocation}), 
997 or by using the priority functions as in @ref{Listing the ciphersuites in a priority string}.
999 Example priority strings are:
1000 @example
1001 The default priority without the HMAC-MD5:
1002     "NORMAL:-MD5"
1004 Specifying RSA with AES-128-CBC:
1005     "NONE:+VERS-TLS-ALL:+MAC-ALL:+RSA:+AES-128-CBC:+SIGN-ALL:+COMP-NULL"
1007 Specifying the defaults except ARCFOUR-128:
1008     "NORMAL:-ARCFOUR-128"
1010 Enabling the 128-bit secure ciphers, while disabling SSL 3.0 and 
1011 enabling compression:
1012     "SECURE128:-VERS-SSL3.0:+COMP-DEFLATE"
1013 @end example
1015 @node Advanced and other topics
1016 @section Advanced and other topics
1018 @menu
1019 * Session resumption::
1020 * Parameter generation::
1021 * Keying Material Exporters::
1022 * Channel Bindings::
1023 * Interoperability::
1024 * Compatibility with the OpenSSL library::
1025 @end menu
1027 @node Session resumption
1028 @subsection Session resumption
1029 @cindex resuming sessions
1030 @cindex session resumption
1032 @subsubheading Client side
1034 To reduce time and roundtrips spent in a handshake the client can   
1035 request session resumption from a server that previously shared
1036 a session with. For that the client has to retrieve and store
1037 the session parameters. Before establishing a new session to the same 
1038 server the parameters must be re-associated with the GnuTLS session
1039 using @funcref{gnutls_session_set_data}.
1041 @showfuncC{gnutls_session_get_data,gnutls_session_get_id,gnutls_session_set_data}
1043 Keep in mind that sessions will be expired after some time, depending
1044 on the server, and a server may choose not to resume a session
1045 even when requested to.  The expiration is to prevent temporal session keys
1046 from becoming long-term keys. Also note that as a client you must enable, 
1047 using the priority functions, at least the algorithms used in the last session.
1049 It is highly recommended for clients to enable the session ticket extension using
1050 @funcref{gnutls_session_ticket_enable_client} in order to allow resumption with 
1051 servers that do not store any state.
1053 @showfuncA{gnutls_session_ticket_enable_client}
1055 @showfuncdesc{gnutls_session_is_resumed}
1057 @subsubheading Server side
1059 In order to support resumption a server can store
1060 the session security parameters in a local database or by using session
1061 tickets (see @ref{Session tickets}) to delegate storage to the client. Because
1062 session tickets might not be supported by all clients, servers
1063 could combine the two methods.
1065 A storing server needs to specify callback functions to store, retrieve and delete session data. These can be
1066 registered with the functions below. The stored sessions in the database can be checked using @funcref{gnutls_db_check_entry}
1067 for expiration.
1069 @showfuncD{gnutls_db_set_retrieve_function,gnutls_db_set_store_function,gnutls_db_set_ptr,gnutls_db_set_remove_function}
1070 @showfuncA{gnutls_db_check_entry}
1072 A server utilizing tickets should generate ticket encryption
1073 and authentication keys using @funcref{gnutls_session_ticket_key_generate}.
1074 Those keys should be associated with the GnuTLS session using
1075 @funcref{gnutls_session_ticket_enable_server}.
1077 @showfuncdesc{gnutls_session_ticket_enable_server}
1078 @showfuncdesc{gnutls_session_ticket_key_generate}
1079 @showfuncdesc{gnutls_session_resumption_requested}
1081 A server enabling both session tickets and a storage for session data
1082 would use session tickets when clients support it and the storage otherwise.
1084 @node Parameter generation
1085 @subsection Parameter generation
1086 @cindex parameter generation
1087 @cindex generating parameters
1089 Several TLS ciphersuites require additional parameters that
1090 need to be generated or provided by the application. The
1091 Diffie-Hellman based ciphersuites (ANON-DH or DHE), require
1092 the group parameters to be provided. Those can either be
1093 be generated on the fly using @funcref{gnutls_dh_params_generate2}
1094 or imported from pregenerated data using @funcref{gnutls_dh_params_import_pkcs3}.
1095 The parameters can be used in a @acronym{TLS} session by calling
1096 @funcref{gnutls_certificate_set_dh_params} or
1097 @funcref{gnutls_anon_set_server_dh_params} for anonymous sessions.
1099 @showfuncD{gnutls_dh_params_generate2,gnutls_dh_params_import_pkcs3,gnutls_certificate_set_dh_params,gnutls_anon_set_server_dh_params}
1101 Due to the time-consuming calculations required for the generation
1102 of Diffie-Hellman parameters we suggest against performing generation
1103 of them within an application. The @code{certtool} tool can be used to 
1104 generate or export known safe values that can be stored in code
1105 or in a configuration file to provide the ability to replace. We also
1106 recommend the usage of @funcref{gnutls_sec_param_to_pk_bits} 
1107 (see @ref{Selecting cryptographic key sizes}) to determine
1108 the bit size of the generated parameters.
1110 Note that the information stored in the generated PKCS #3 structure
1111 changed with GnuTLS 3.0.9. Since that version the @code{privateValueLength}
1112 member of the structure is set, allowing the server utilizing the
1113 parameters to use keys of the size of the security parameter. This
1114 provides better performance in key exchange.
1116 The ciphersuites that involve the RSA-EXPORT key exchange require
1117 additional parameters. Those ciphersuites are rarely used today
1118 because they are by design insecure, thus if you have no requirement
1119 for them, the rest of this section can be skipped. The RSA-EXPORT key exchange
1120 requires 512-bit RSA keys to be generated. It is recommended those
1121 parameters to be refreshed (regenerated) in short intervals. The
1122 following functions can be used for these parameters.
1124 @showfuncD{gnutls_rsa_params_generate2,gnutls_certificate_set_rsa_export_params,gnutls_rsa_params_import_pkcs1,gnutls_rsa_params_export_pkcs1}
1126 To allow renewal of the parameters within an application without
1127 accessing the credentials, which are a shared structure,
1128 an alternative interface is available using a callback function.  
1130 @showfuncdesc{gnutls_certificate_set_params_function}
1133 @node Keying Material Exporters
1134 @subsection Keying material exporters
1135 @cindex keying material exporters
1136 @cindex exporting keying material
1138 The TLS PRF can be used by other protocols to derive keys based on
1139 the TLS master secret.  The API to use is @funcref{gnutls_prf}.  The 
1140 function needs to be provided with the label in the parameter 
1141 @code{label}, and the extra data to mix in the
1142 @code{extra} parameter.  Depending on whether you want to mix in the
1143 client or server random data first, you can set the
1144 @code{server_random_first} parameter.
1146 For example, after establishing a TLS session using
1147 @funcref{gnutls_handshake}, you can invoke the TLS PRF with this call:
1149 @example
1150 #define MYLABEL "EXPORTER-FOO"
1151 #define MYCONTEXT "some context data"
1152 char out[32];
1153 rc = gnutls_prf (session, strlen (MYLABEL), MYLABEL, 0,
1154                  strlen (MYCONTEXT), MYCONTEXT, 32, out);
1155 @end example
1157 If you don't want to mix in the client/server random, there is a 
1158 low-level TLS PRF interface called @funcref{gnutls_prf_raw}.
1160 @node Channel Bindings
1161 @subsection Channel bindings
1162 @cindex channel bindings
1164 In user authentication protocols (e.g., EAP or SASL mechanisms) it is
1165 useful to have a unique string that identifies the secure channel that
1166 is used, to bind together the user authentication with the secure
1167 channel.  This can protect against man-in-the-middle attacks in some
1168 situations.  That unique string is called a ``channel binding''.  For
1169 background and discussion see @xcite{RFC5056}.
1171 In @acronym{GnuTLS} you can extract a channel binding using the
1172 @funcref{gnutls_session_channel_binding} function.  Currently only the
1173 type @code{GNUTLS_CB_TLS_UNIQUE} is supported, which corresponds to
1174 the @code{tls-unique} channel binding for TLS defined in
1175 @xcite{RFC5929}.
1177 The following example describes how to print the channel binding data.
1178 Note that it must be run after a successful TLS handshake.
1180 @example
1182   gnutls_datum_t cb;
1183   int rc;
1185   rc = gnutls_session_channel_binding (session,
1186                                        GNUTLS_CB_TLS_UNIQUE,
1187                                        &cb);
1188   if (rc)
1189     fprintf (stderr, "Channel binding error: %s\n",
1190              gnutls_strerror (rc));
1191   else
1192     @{
1193       size_t i;
1194       printf ("- Channel binding 'tls-unique': ");
1195       for (i = 0; i < cb.size; i++)
1196         printf ("%02x", cb.data[i]);
1197       printf ("\n");
1198     @}
1200 @end example
1202 @node Interoperability
1203 @subsection Interoperability
1205 The @acronym{TLS} protocols support many ciphersuites, extensions and version
1206 numbers. As a result, few implementations are 
1207 not able to properly interoperate once faced with extensions or version protocols
1208 they do not support and understand. The @acronym{TLS} protocol allows for a
1209 graceful downgrade to the commonly supported options, but practice shows 
1210 it is not always implemented correctly. 
1212 Because there is no way to achieve maximum interoperability with broken peers
1213 without sacrificing security, @acronym{GnuTLS} ignores such peers by default. 
1214 This might not be acceptable in cases where maximum compatibility
1215 is required. Thus we allow enabling compatibility with broken peers using
1216 priority strings (see @ref{Priority Strings}). A conservative priority
1217 string that would disable certain @acronym{TLS} protocol
1218 options that are known to cause compatibility problems, is shown below. 
1219 @verbatim
1220 NORMAL:%COMPAT
1221 @end verbatim
1223 For broken peers that do not tolerate TLS version numbers over TLS 1.0
1224 another priority string is:
1225 @verbatim
1226 NORMAL:-VERS-TLS-ALL:+VERS-TLS1.0:+VERS-SSL3.0:%COMPAT
1227 @end verbatim
1228 This priority string will in addition to above, only enable SSL 3.0 and 
1229 TLS 1.0 as protocols. Note however that
1230 there are known attacks against those protocol versions, especially over
1231 the CBC-mode ciphersuites. To mitigate them another priority string
1232 that only allows the stream cipher ARCFOUR is below.
1233 @verbatim
1234 NORMAL:-VERS-TLS-ALL:+VERS-TLS1.0:+VERS-SSL3.0:-CIPHER-ALL:+ARCFOUR-128:%COMPAT
1235 @end verbatim
1237 @node Compatibility with the OpenSSL library
1238 @subsection Compatibility with the OpenSSL library
1239 @cindex OpenSSL
1241 To ease @acronym{GnuTLS}' integration with existing applications, a
1242 compatibility layer with the OpenSSL library is included
1243 in the @code{gnutls-openssl} library. This compatibility layer is not
1244 complete and it is not intended to completely re-implement the OpenSSL
1245 API with @acronym{GnuTLS}.  It only provides limited source-level
1246 compatibility. 
1248 The prototypes for the compatibility functions are in the
1249 @file{gnutls/openssl.h} header file. The limitations 
1250 imposed by the compatibility layer include:
1252 @itemize
1254 @item Error handling is not thread safe.
1256 @end itemize
1258 @node Using the cryptographic library
1259 @section Using the cryptographic library
1261 @acronym{GnuTLS} is not a low-level cryptographic library, i.e., 
1262 it does not provide access to basic cryptographic primitives. However
1263 it abstracts the internal cryptographic back-end (see @ref{Cryptographic Backend}),
1264 providing symmetric crypto, hash and HMAC algorithms, as well access
1265 to the random number generation.
1267 @menu
1268 * Symmetric cryptography::
1269 * Hash and HMAC functions::
1270 * Random number generation::
1271 @end menu
1273 @node Symmetric cryptography
1274 @subsection Symmetric cryptography
1275 @cindex symmetric cryptography
1277 The available functions to access symmetric crypto algorithms operations
1278 are shown below. The supported algorithms are the algorithms required by the TLS protocol.
1279 They are listed in @ref{tab:ciphers}.
1281 @showfuncE{gnutls_cipher_init,gnutls_cipher_encrypt2,gnutls_cipher_decrypt2,gnutls_cipher_set_iv,gnutls_cipher_deinit}
1283 In order to support authenticated encryption with associated data (AEAD) algorithms the following
1284 functions are provided to set the associated data and retrieve the authentication tag.
1286 @showfuncB{gnutls_cipher_add_auth,gnutls_cipher_tag}
1288 @node Hash and HMAC functions
1289 @subsection Hash and HMAC functions
1290 @cindex hash functions
1291 @cindex HMAC functions
1293 The available operations to access hash functions and hash-MAC (HMAC) algorithms
1294 are shown below. HMAC algorithms provided keyed hash functionality. They supported HMAC algorithms are listed in @ref{tab:macs}.
1296 @showfuncF{gnutls_hmac_init,gnutls_hmac,gnutls_hmac_output,gnutls_hmac_deinit,gnutls_hmac_get_len,gnutls_hmac_fast}
1298 The available functions to access hash functions are shown below. The supported hash functions
1299 are the same as the HMAC algorithms.
1301 @showfuncF{gnutls_hash_init,gnutls_hash,gnutls_hash_output,gnutls_hash_deinit,gnutls_hash_get_len,gnutls_hash_fast}
1303 @node Random number generation
1304 @subsection Random number generation
1305 @cindex random numbers
1307 Access to the random number generator is provided using the @funcref{gnutls_rnd}
1308 function. It allows obtaining random data of various levels.
1310 @showenumdesc{gnutls_rnd_level_t,The random number levels.}
1311 @showfuncdesc{gnutls_rnd}
1313 @node Selecting cryptographic key sizes
1314 @section Selecting cryptographic key sizes
1315 @cindex key sizes
1317 Because many algorithms are involved in TLS, it is not easy to set
1318 a consistent security level.  For this reason in @ref{tab:key-sizes} we
1319 present some correspondence between key sizes of symmetric algorithms
1320 and public key algorithms based on @xcite{ECRYPT}. 
1321 Those can be used to generate certificates with
1322 appropriate key sizes as well as select parameters for Diffie-Hellman and SRP
1323 authentication.
1325 @float Table,tab:key-sizes
1326 @multitable @columnfractions .10 .12 .10 .20 .32
1328 @headitem Security bits @tab RSA, DH and SRP parameter size @tab ECC key size @tab Security parameter @tab Description
1330 @item 80
1331 @tab 1248
1332 @tab 160
1333 @tab @code{LOW}
1334 @tab Very short term protection against agencies
1336 @item 96
1337 @tab 1776
1338 @tab 192
1339 @tab @code{LEGACY}
1340 @tab Legacy standard level
1342 @item 112
1343 @tab 2432
1344 @tab 224
1345 @tab @code{NORMAL}
1346 @tab Medium-term protection
1348 @item 128
1349 @tab 3248
1350 @tab 256
1351 @tab @code{HIGH}
1352 @tab Long term protection
1354 @item 256
1355 @tab 15424
1356 @tab 512
1357 @tab @code{ULTRA}
1358 @tab Foreseeable future
1360 @end multitable
1361 @caption{Key sizes and security parameters.}
1362 @end float
1364 The first column  provides a security parameter in a number of bits. This
1365 gives an indication of the number of combinations to be tried by an adversary
1366 to brute force a key. For example to test all possible keys in a 112 bit security parameter
1367 @math{2^{112}} combinations have to be tried. For today's technology this is infeasible.
1368 The next two columns correlate the security
1369 parameter with actual bit sizes of parameters for DH, RSA, SRP and ECC algorithms.
1370 A mapping to @code{gnutls_sec_param_t} value is given for each security parameter, on
1371 the next column, and finally a brief description of the level.
1373 @c @showenumdesc{gnutls_sec_param_t,The @code{gnutls_sec_@-param_t} enumeration.}
1375 Note, however, that the values suggested here are nothing more than an
1376 educated guess that is valid today. There are no guarantees that an
1377 algorithm will remain unbreakable or that these values will remain
1378 constant in time. There could be scientific breakthroughs that cannot
1379 be predicted or total failure of the current public key systems by
1380 quantum computers. On the other hand though the cryptosystems used in
1381 TLS are selected in a conservative way and such catastrophic
1382 breakthroughs or failures are believed to be unlikely.
1383 The NIST publication SP 800-57 @xcite{NISTSP80057} contains a similar
1384 table.
1386 When using @acronym{GnuTLS} and a decision on bit sizes for a public
1387 key algorithm is required, use of the following functions is  
1388 recommended:
1390 @showfuncdesc{gnutls_sec_param_to_pk_bits}
1392 @showfuncdesc{gnutls_pk_bits_to_sec_param}
1394 Those functions will convert a human understandable security parameter
1395 of @code{gnutls_sec_param_t} type, to a number of bits suitable for a public 
1396 key algorithm.
1398 The following functions will set the minimum acceptable group size for Diffie-Hellman
1399 and SRP authentication. 
1400 @showfuncB{gnutls_dh_set_prime_bits,gnutls_srp_set_prime_bits}