1 @node How to use GnuTLS in applications
2 @chapter How to use @acronym{GnuTLS} in applications
5 * Introduction to the library::
7 * Session initialization::
8 * Associating the credentials::
9 * Setting up the transport layer::
11 * Data transfer and termination::
14 * Selecting cryptographic key sizes::
18 @node Introduction to the library
21 This chapter tries to explain the basic functionality of the current GnuTLS
22 library. Note that there may be additional functionality not discussed here
23 but included in the library. Checking the header files in @file{/usr/include/gnutls/}
24 and the manpages is recommended.
30 * Debugging and auditing::
32 * Callback functions::
36 @subsection General idea
38 A brief description of how @acronym{GnuTLS} sessions operate is shown
39 at @ref{fig:gnutls-design}. This section will become more clear when it
41 As shown in the figure, there is a read-only global state that is
42 initialized once by the global initialization function. This global
43 structure, among others, contains the memory allocation functions
44 used, structures needed for the @acronym{ASN.1} parser and depending
45 on the system's CPU, pointers to hardware accelerated encryption functions. This
46 structure is never modified by any @acronym{GnuTLS} function, except
47 for the deinitialization function which frees all allocated memory
48 and must be called after the program has permanently
49 finished using @acronym{GnuTLS}.
51 @float Figure,fig:gnutls-design
52 @image{gnutls-internals,12cm}
53 @caption{High level design of GnuTLS.}
56 The credentials structures are used by the authentication methods, such
57 as certificate authentication. They store certificates, privates keys,
58 and other information that is needed to prove the identity to the peer,
59 and/or verify the indentity of the peer. The information stored in
60 the credentials structures is initialized once and then can be
61 shared by many @acronym{TLS} sessions.
63 A @acronym{GnuTLS} session contains all the required information
64 to handle one secure connection. The session communicates with the
65 peers using the provided functions of the transport layer.
66 Every session has a unique session ID shared with the peer.
68 Since TLS sessions can be resumed, servers need a
69 database back-end to hold the session's parameters. Every
70 @acronym{GnuTLS} session after a successful handshake calls the
71 appropriate back-end function (see @ref{resume})
72 to store the newly negotiated session. The session
73 database is examined by the server just after having received the
74 client hello@footnote{The first message in a @acronym{TLS} handshake},
75 and if the session ID sent by the client, matches a stored session,
76 the stored session will be retrieved, and the new session will be a
77 resumed one, and will share the same session ID with the previous one.
80 @subsection Error handling
82 In @acronym{GnuTLS} most functions return an integer type as a result.
83 In almost all cases a zero or a positive number means success, and a
84 negative number indicates failure, or a situation that some action has
85 to be taken. Thus negative error codes may be fatal or not.
87 Fatal errors terminate the connection immediately and further sends
88 and receives will be disallowed. Such an example is
89 @code{GNUTLS_@-E_@-DECRYPTION_@-FAILED}. Non-fatal errors may warn about
90 something, i.e., a warning alert was received, or indicate the some
91 action has to be taken. This is the case with the error code
92 @code{GNUTLS_@-E_@-REHANDSHAKE} returned by @funcref{gnutls_record_recv}.
93 This error code indicates that the server requests a re-handshake. The
94 client may ignore this request, or may reply with an alert. You can
95 test if an error code is a fatal one by using the
96 @funcref{gnutls_error_is_fatal}.
97 All errors can be converted to a descriptive string using @funcref{gnutls_strerror}.
99 If any non fatal errors, that require an action, are to be returned by
100 a function, these error codes will be documented in the function's
101 reference. For example the error codes @code{GNUTLS_@-E_@-WARNING_@-ALERT_@-RECEIVED} and @code{GNUTLS_@-E_@-FATAL_@-ALERT_@-RECEIVED}
102 that may returned when receiving data, should be handled by notifying the
103 user of the alert (as explained in @ref{Handling alerts}).
104 See @ref{Error codes}, for a description of the available error codes.
107 @subsection Common types
109 All strings that are to provided as input to @acronym{GnuTLS} functions
110 should be in UTF-8 unless otherwise specified. Output strings are also
111 in UTF-8 format unless otherwise specified.
113 When data of a fixed size are provided to @acronym{GnuTLS} functions then
114 the helper structure @code{gnutls_datum_t} is often used. Its definition is
124 Other functions that require data for scattered read use a structure similar
125 to @code{struct iovec} typically used by @funcintref{readv}. It is shown
130 void *iov_base; /* Starting address */
131 size_t iov_len; /* Number of bytes to transfer */
136 @node Debugging and auditing
137 @subsection Debugging and auditing
139 In many cases things may not go as expected and further information,
140 to assist debugging, from @acronym{GnuTLS} is desired.
141 Those are the cases where the @funcref{gnutls_global_set_log_level} and
142 @funcref{gnutls_global_set_log_function} are to be used. Those will print
143 verbose information on the @acronym{GnuTLS} functions internal flow.
145 @showfuncB{gnutls_global_set_log_level,gnutls_global_set_log_function}
147 When debugging is not required, important issues, such as detected
148 attacks on the protocol still need to be logged. This is provided
149 by the logging function set by
150 @funcref{gnutls_global_set_audit_log_function}. The provided function
151 will receive an message and the corresponding
152 TLS session. The session information might be used to derive IP addresses
153 or other information about the peer involved.
155 @showfuncdesc{gnutls_global_set_audit_log_function}
158 @subsection Thread safety
159 @cindex thread safety
161 The @acronym{GnuTLS} library is thread safe by design, meaning that
162 objects of the library such as TLS sessions, can be safely divided across
163 threads as long as a single thread accesses a single object. This is
164 sufficient to support a server which handles several sessions per thread.
165 If, however, an object needs to be shared across threads then access must be
166 protected with a mutex. Read-only access to objects, for example the
167 credentials holding structures, is also thread-safe.
169 The random generator of the cryptographic back-end, is not thread safe and requires
170 mutex locks which are setup by @acronym{GnuTLS}.
171 Applications can either call @funcref{gnutls_global_init} which will initialize the default
172 operating system provided locks (i.e. @code{pthreads} on GNU/Linux and
173 @code{CriticalSection} on Windows), or manually specify the locking system using
174 the function @funcref{gnutls_global_set_mutex} before calling @funcref{gnutls_global_init}.
175 Setting mutexes manually is recommended
176 only for applications that have full control of the underlying libraries. If this
177 is not the case, the use of the operating system defaults is recommended. An example of
178 non-native thread usage is shown below.
181 #include <gnutls/gnutls.h>
185 /* When the system mutexes are not to be used
186 * gnutls_global_set_mutex() must be called explicitly
188 gnutls_global_set_mutex (mutex_init, mutex_deinit,
189 mutex_lock, mutex_unlock);
190 gnutls_global_init();
194 @showfuncdesc{gnutls_global_set_mutex}
196 @node Callback functions
197 @subsection Callback functions
198 @cindex callback functions
200 There are several cases where @acronym{GnuTLS} may need out of
201 band input from your program. This is now implemented using some
202 callback functions, which your program is expected to register.
204 An example of this type of functions are the push and pull callbacks
205 which are used to specify the functions that will retrieve and send
206 data to the transport layer.
208 @showfuncB{gnutls_transport_set_push_function,gnutls_transport_set_pull_function}
210 Other callback functions may require more complicated input and data
211 to be allocated. Such an example is
212 @funcref{gnutls_srp_set_server_credentials_function}.
213 All callbacks should allocate and free memory using
214 @funcintref{gnutls_malloc} and @funcintref{gnutls_free}.
220 To use @acronym{GnuTLS}, you have to perform some changes to your
221 sources and your build system. The necessary changes are explained in
222 the following subsections.
228 * Building the source::
234 All the data types and functions of the @acronym{GnuTLS} library are
235 defined in the header file @file{gnutls/gnutls.h}. This must be
236 included in all programs that make use of the @acronym{GnuTLS}
240 @subsection Initialization
242 GnuTLS must be initialized before it can be used. The library is
243 initialized by calling @funcref{gnutls_global_init}. The resources
244 allocated by the initialization process can be released if the
245 application no longer has a need to call GnuTLS functions, this is
246 done by calling @funcref{gnutls_global_deinit}.
248 In order to take advantage of the internationalization features in
249 GnuTLS, such as translated error messages, the application must set
250 the current locale using @code{setlocale} before initializing GnuTLS.
253 @subsection Version check
255 It is often desirable to check that the version of `gnutls' used is
256 indeed one which fits all requirements. Even with binary
257 compatibility new features may have been introduced but due to problem
258 with the dynamic linker an old version is actually used. So you may
259 want to check that the version is okay right after program start-up.
260 See the function @funcref{gnutls_check_version}.
262 @node Building the source
263 @subsection Building the source
265 If you want to compile a source file including the
266 @file{gnutls/gnutls.h} header file, you must make sure that the
267 compiler can find it in the directory hierarchy. This is accomplished
268 by adding the path to the directory in which the header file is
269 located to the compilers include file search path (via the @option{-I}
272 However, the path to the include file is determined at the time the
273 source is configured. To solve this problem, the library uses the
274 external package @command{pkg-config} that knows the path to the
275 include file and other configuration options. The options that need
276 to be added to the compiler invocation at compile time are output by
277 the @option{--cflags} option to @command{pkg-config gnutls}. The
278 following example shows how it can be used at the command line:
281 gcc -c foo.c `pkg-config gnutls --cflags`
284 Adding the output of @samp{pkg-config gnutls --cflags} to the
285 compilers command line will ensure that the compiler can find the
286 @file{gnutls/gnutls.h} header file.
288 A similar problem occurs when linking the program with the library.
289 Again, the compiler has to find the library files. For this to work,
290 the path to the library files has to be added to the library search
291 path (via the @option{-L} option). For this, the option
292 @option{--libs} to @command{pkg-config gnutls} can be used. For
293 convenience, this option also outputs all other options that are
294 required to link the program with the library (for instance, the
295 @samp{-ltasn1} option). The example shows how to link @file{foo.o}
296 with the library to a program @command{foo}.
299 gcc -o foo foo.o `pkg-config gnutls --libs`
302 Of course you can also combine both examples to a single command by
303 specifying both options to @command{pkg-config}:
306 gcc -o foo foo.c `pkg-config gnutls --cflags --libs`
309 When a program uses the GNU autoconf system, then the following
310 line or similar can be used to detect the presence of GnuTLS.
313 PKG_CHECK_MODULES([LIBGNUTLS], [gnutls >= 3.0.0])
315 AC_SUBST([LIBGNUTLS_CFLAGS])
316 AC_SUBST([LIBGNUTLS_LIBS])
319 @node Session initialization
320 @section Session initialization
322 In the previous sections we have discussed the global initialization
323 required for GnuTLS as well as the initialization required for each
324 authentication method's credentials (see @ref{Authentication}).
325 In this section we elaborate on the TLS or DTLS session initiation.
326 Each session is initialized using @funcref{gnutls_init} which among
327 others is used to specify the type of the connection (server or client),
328 and the underlying protocol type, i.e., datagram (UDP) or reliable (TCP).
330 @showfuncdesc{gnutls_init}
332 After the session initialization details on the allowed ciphersuites
333 and protocol versions should be set using the priority functions
334 such as @funcref{gnutls_priority_set_direct}. We elaborate on them
335 in @ref{Priority Strings}.
336 The credentials used for the key exchange method, such as certificates
337 or usernames and passwords should also be associated with the session
338 current session using @funcref{gnutls_credentials_set}.
340 @showfuncdesc{gnutls_credentials_set}
342 @node Associating the credentials
343 @section Associating the credentials
346 * Certificate credentials::
349 * Anonymous credentials::
352 Each authentication method is associated with a key exchange method, and a credentials type.
353 The contents of the credentials is method-dependent, e.g. certificates
354 for certificate authentication and should be initialized and associated
355 with a session (see @funcref{gnutls_credentials_set}). A mapping of the key exchange methods
356 with the credential types is shown in @ref{tab:key-exchange-cred}.
358 @float Table,tab:key-exchange-cred
359 @multitable @columnfractions .25 .25 .2 .2
361 @headitem Authentication method @tab Key exchange @tab Client credentials @tab Server credentials
368 @code{KX_ECDHE_ECDSA},
370 @tab @code{CRD_CERTIFICATE}
371 @tab @code{CRD_CERTIFICATE}
373 @item Password and certificate
374 @tab @code{KX_SRP_RSA}, @code{KX_SRP_DSS}
376 @tab @code{CRD_CERTIFICATE}, @code{CRD_SRP}
384 @tab @code{KX_ANON_DH},
391 @code{KX_DHE_PSK}, @code{KX_ECDHE_PSK}
396 @caption{Key exchange algorithms and the corresponding credential types.}
399 @node Certificate credentials
400 @subsection Certificates
401 @subsubheading Server certificate authentication
403 When using certificates the server is required to have at least one
404 certificate and private key pair. Clients may not hold such
405 a pair, but a server could require it. In this section we discuss
406 general issues applying to both client and server certificates. The next
407 section will elaborate on issues arising from client authentication only.
409 @showfuncB{gnutls_certificate_allocate_credentials,gnutls_certificate_free_credentials}
411 After the credentials structures are initialized, the certificate
412 and key pair must be loaded. This occurs before any @acronym{TLS}
413 session is initialized, and the same structures are reused for multiple sessions.
414 Depending on the certificate type different loading functions
415 are available, as shown below.
416 For @acronym{X.509} certificates, the functions will
417 accept and use a certificate chain that leads to a trusted
418 authority. The certificate chain must be ordered in such way that every
419 certificate certifies the one before it. The trusted authority's
420 certificate need not to be included since the peer should possess it
423 @showfuncC{gnutls_certificate_set_x509_key_mem,gnutls_certificate_set_x509_key,gnutls_certificate_set_x509_key_file}
425 @showfuncC{gnutls_certificate_set_openpgp_key_mem,gnutls_certificate_set_openpgp_key,gnutls_certificate_set_openpgp_key_file}
427 Note however, that since functions like @funcref{gnutls_certificate_set_x509_key_file}
428 may accept URLs that specify objects stored in token, another important
429 function is @funcref{gnutls_certificate_set_pin_function}. That
430 allows setting a callback function to retrieve a PIN if the input keys are
431 protected by PIN by the token.
433 @showfuncdesc{gnutls_certificate_set_pin_function}
435 If the imported keys and certificates need to be accessed before any TLS session
436 is established, it is convenient to use @funcref{gnutls_certificate_set_key}
437 in combination with @funcref{gnutls_pcert_import_x509_raw} and @funcref{gnutls_privkey_import_x509_raw}.
439 @showfuncdesc{gnutls_certificate_set_key}
441 If multiple certificates are used with the functions above each
442 client's request will be served with the certificate that matches the
443 requested name (see @ref{Server name indication}).
445 As an alternative to loading from files or buffers, a callback may be used for the
446 server or the client to specify the certificate and the key at the handshake time.
447 In that case a certificate should be selected according the peer's signature
448 algorithm preferences. To get those preferences use
449 @funcref{gnutls_sign_algorithm_get_requested}. Both functions are shown below.
451 @showfuncC{gnutls_certificate_set_retrieve_function,gnutls_certificate_set_retrieve_function2,gnutls_sign_algorithm_get_requested}
453 The functions above do not handle the requested server name automatically.
454 A server would need to check the name requested by the client
455 using @funcref{gnutls_server_name_get}, and serve the appropriate
456 certificate. Note that some of these functions require the @code{gnutls_pcert_st} structure to be
457 filled in. Helper functions to make the required structures are listed below.
460 typedef struct gnutls_pcert_st
462 gnutls_pubkey_t pubkey;
464 gnutls_certificate_type_t type;
468 @showfuncE{gnutls_pcert_import_x509,gnutls_pcert_import_openpgp,gnutls_pcert_import_x509_raw,gnutls_pcert_import_openpgp_raw,gnutls_pcert_deinit}
470 In a handshake, the negotiated cipher suite depends on the
471 certificate's parameters, so some key exchange methods might not be
472 available with all certificates. @acronym{GnuTLS} will disable
473 ciphersuites that are not compatible with the key, or the enabled
474 authentication methods. For example keys marked as sign-only, will
475 not be able to access the plain RSA ciphersuites, that require
476 decryption. It is not recommended to use RSA keys for both
477 signing and encryption. If possible use a different key for the
478 @code{DHE-RSA} which uses signing and @code{RSA} that requires decryption.
479 All the key exchange methods shown in @ref{tab:key-exchange} are
480 available in certificate authentication.
483 @subsubheading Client certificate authentication
485 If a certificate is to be requested from the client during the handshake, the server
486 will send a certificate request message. This behavior is controlled @funcref{gnutls_certificate_server_set_request}.
487 The request contains a list of the acceptable by the server certificate signers. This list
488 is constructed using the trusted certificate authorities of the server.
489 In cases where the server supports a large number of certificate authorities
490 it makes sense not to advertise all of the names to save bandwidth. That can
491 be controlled using the function @funcref{gnutls_certificate_send_x509_rdn_sequence}.
492 This however will have the side-effect of not restricting the client to certificates
493 signed by server's acceptable signers.
495 @showfuncdesc{gnutls_certificate_server_set_request}
497 @showfuncdesc{gnutls_certificate_send_x509_rdn_sequence}
500 @subsubheading Client or server certificate verification
502 Certificate verification is possible by loading the trusted
503 authorities into the credentials structure by using
504 the following functions, applicable to X.509 and OpenPGP certificates.
506 @showfuncC{gnutls_certificate_set_x509_system_trust,gnutls_certificate_set_x509_trust_file,gnutls_certificate_set_openpgp_keyring_file}
508 The peer's certificate is not automatically verified and one
509 must call @funcref{gnutls_certificate_verify_peers3}
510 after a successful handshake to verify the certificate's signature and the owner
511 of the certificate. The verification status returned can be printed using
512 @funcref{gnutls_certificate_verification_status_print}.
514 Alternatively the verification can occur during the handshake
515 by using @funcref{gnutls_certificate_set_verify_function}.
517 The functions above provide a brief verification output. If a
518 detailed output is required one should call @funcref{gnutls_certificate_get_peers}
519 to obtain the raw certificate of the peer and verify it using the
520 functions discussed in @ref{X.509 certificates}.
522 @showfuncdesc{gnutls_certificate_verify_peers3}
524 @showfuncdesc{gnutls_certificate_set_verify_function}
527 @node SRP credentials
530 The initialization functions in SRP credentials differ between
532 Clients supporting @acronym{SRP} should set the username and password
533 prior to connection, to the credentials structure.
534 Alternatively @funcref{gnutls_srp_set_client_credentials_function}
535 may be used instead, to specify a callback function that should return the
536 SRP username and password.
537 The callback is called once during the @acronym{TLS} handshake.
539 @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}
541 @showfuncdesc{gnutls_srp_set_client_credentials_function}
543 In server side the default behavior of @acronym{GnuTLS} is to read
544 the usernames and @acronym{SRP} verifiers from password files. These
545 password file format is compatible the with the @emph{Stanford srp libraries}
546 format. If a different password file format is to be used, then
547 @funcref{gnutls_srp_set_server_credentials_function} should be called,
548 to set an appropriate callback.
550 @showfuncdesc{gnutls_srp_set_server_credentials_file}
552 @showfuncdesc{gnutls_srp_set_server_credentials_function}
555 @node PSK credentials
557 The initialization functions in PSK credentials differ between
560 @showfuncD{gnutls_psk_allocate_server_credentials,gnutls_psk_allocate_client_credentials,gnutls_psk_free_server_credentials,gnutls_psk_free_client_credentials}
562 Clients supporting @acronym{PSK} should supply the username and key
563 before a TLS session is established. Alternatively
564 @funcref{gnutls_psk_set_client_credentials_function} can be used to
565 specify a callback function. This has the
566 advantage that the callback will be called only if @acronym{PSK} has
569 @showfuncA{gnutls_psk_set_client_credentials}
571 @showfuncdesc{gnutls_psk_set_client_credentials_function}
573 In server side the default behavior of @acronym{GnuTLS} is to read
574 the usernames and @acronym{PSK} keys from a password file. The
575 password file should contain usernames and keys in hexadecimal
576 format. The name of the password file can be stored to the credentials
577 structure by calling @funcref{gnutls_psk_set_server_credentials_file}. If
578 a different password file format is to be used, then
579 a callback should be set instead by @funcref{gnutls_psk_set_server_credentials_function}.
581 The server can help the client chose a suitable username and password,
582 by sending a hint. Note that there is no common profile for the PSK hint and applications
583 are discouraged to use it.
584 A server, may specify the hint by calling
585 @funcref{gnutls_psk_set_server_credentials_hint}. The client can retrieve
586 the hint, for example in the callback function, using
587 @funcref{gnutls_psk_client_get_hint}.
589 @showfuncdesc{gnutls_psk_set_server_credentials_file}
591 @showfuncC{gnutls_psk_set_server_credentials_function,gnutls_psk_set_server_credentials_hint,gnutls_psk_client_get_hint}
593 @node Anonymous credentials
594 @subsection Anonymous
595 The key exchange methods for anonymous authentication
596 might require Diffie-Hellman parameters to be generated by the server and
597 associated with an anonymous credentials structure. Check
598 @ref{Parameter generation} for more information.
599 The initialization functions for the credentials are shown below.
601 @showfuncD{gnutls_anon_allocate_server_credentials,gnutls_anon_allocate_client_credentials,gnutls_anon_free_server_credentials,gnutls_anon_free_client_credentials}
605 @node Setting up the transport layer
606 @section Setting up the transport layer
608 The next step is to setup the underlying transport layer details. The
609 Berkeley sockets are implicitly used by GnuTLS, thus a
610 call to @funcref{gnutls_transport_set_ptr2} would be sufficient to
611 specify the socket descriptor.
613 @showfuncdesc{gnutls_transport_set_ptr2}
615 @showfuncA{gnutls_transport_set_ptr}
617 If however another transport layer than TCP is selected, then
618 the following functions have to be specified.
620 @showfuncdesc{gnutls_transport_set_push_function}
621 @showfuncdesc{gnutls_transport_set_vec_push_function}
622 @showfuncdesc{gnutls_transport_set_pull_function}
624 The functions above accept a callback function which
625 should return the number of bytes written, or -1 on
626 error and should set @code{errno} appropriately.
627 In some environments, setting @code{errno} is unreliable. For example
628 Windows have several errno variables in different CRTs, or in other
629 systems it may be a non thread-local variable. If this is a concern to
630 you, call @funcref{gnutls_transport_set_errno} with the intended errno
631 value instead of setting @code{errno} directly.
633 @showfuncdesc{gnutls_transport_set_errno}
635 @acronym{GnuTLS} currently only interprets the EINTR, EAGAIN and EMSGSIZE errno
636 values and returns the corresponding @acronym{GnuTLS} error codes:
638 @item @code{GNUTLS_E_INTERRUPTED}
639 @item @code{GNUTLS_E_AGAIN}
640 @item @code{GNUTLS_E_LARGE_PACKET}
642 The EINTR and EAGAIN values are returned by interrupted system calls,
643 or when non blocking IO is used. All @acronym{GnuTLS} functions can be
644 resumed (called again), if any of the above error codes is returned. The
645 EMSGSIZE value is returned when attempting to send a large datagram.
647 In the case of DTLS it is also desirable to override the generic
648 transport functions with functions that emulate the operation
649 of @code{recvfrom} and @code{sendto}. In addition
650 @acronym{DTLS} requires timers during the receive of a handshake
651 message, set using the @funcref{gnutls_transport_set_pull_timeout_function}
652 function. To check the retransmission timers the function
653 @funcref{gnutls_dtls_get_timeout} is provided, which returns the time
654 remaining until the next retransmission, or better the time until
655 @funcref{gnutls_handshake} should be called again.
657 @showfuncdesc{gnutls_transport_set_pull_timeout_function}
658 @showfuncdesc{gnutls_dtls_get_timeout}
661 * Asynchronous operation::
665 @node Asynchronous operation
666 @subsection Asynchronous operation
667 @acronym{GnuTLS} can be used with asynchronous socket or event-driven programming.
668 The approach is similar to using Berkeley sockets under such an environment.
669 The blocking, due to network interaction, calls such as
670 @funcref{gnutls_handshake}, @funcref{gnutls_record_recv},
671 can be set to non-blocking by setting the underlying sockets to non-blocking.
672 If other push and pull functions are setup, then they should behave the same
673 way as @funcintref{recv} and @funcintref{send} when used in a non-blocking
674 way, i.e., set errno to @code{EAGAIN}. Since, during a TLS protocol session
675 @acronym{GnuTLS} does not block except for network interaction, the non blocking
676 @code{EAGAIN} errno will be propagated and @acronym{GnuTLS} functions
677 will return the @code{GNUTLS_E_AGAIN} error code. Such calls can be resumed the
678 same way as a system call would.
679 The only exception is @funcref{gnutls_record_send},
680 which if interrupted subsequent calls need not to include the data to be
681 sent (can be called with NULL argument).
683 The @funcintref{select} system call can also be used in combination with the
684 @acronym{GnuTLS} functions. @funcintref{select} allows monitoring of sockets
685 and notifies on them being ready for reading or writing data. Note however
686 that this system call cannot notify on data present in @acronym{GnuTLS}
687 read buffers, it is only applicable to the kernel sockets API. Thus if
688 you are using it for reading from a @acronym{GnuTLS} session, make sure
689 that any cached data are read completely. That can be achieved by checking there
690 are no data waiting to be read (using @funcref{gnutls_record_check_pending}),
691 either before the @funcintref{select} system call, or after a call to
692 @funcref{gnutls_record_recv}. @acronym{GnuTLS} does not keep a write buffer,
693 thus when writing no additional actions are required.
695 Although in the TLS protocol implementation each call to receive or send
696 function implies to restoring the same function that was interrupted, in
697 the DTLS protocol this requirement isn't true.
698 There are cases where a retransmission is required, which are indicated by
699 a received message and thus @funcref{gnutls_record_get_direction} must be called
700 to decide which direction to check prior to restoring a function call.
701 @showfuncdesc{gnutls_record_get_direction}
703 Moreover, to prevent blocking from DTLS' retransmission timers to block a
704 handshake, the @funcref{gnutls_init} function should be called with the
705 @code{GNUTLS_NONBLOCK} flag set (see @ref{Session initialization}).
709 @subsection DTLS sessions
711 Because datagram TLS can operate over connections where the peer
712 of a server cannot be reliably verified, functionality is available to prevent
713 denial of service attacks. @acronym{GnuTLS} requires a server
714 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.}.
715 That cookie is sent to the client using @funcref{gnutls_dtls_cookie_send}, and
716 the client must reply using the correct cookie. The server side
717 should verify the initial message sent by client using @funcref{gnutls_dtls_cookie_verify}.
718 If successful the session should be initialized and associated with
719 the cookie using @funcref{gnutls_dtls_prestate_set}, before proceeding to
722 @showfuncD{gnutls_key_generate,gnutls_dtls_cookie_send,gnutls_dtls_cookie_verify,gnutls_dtls_prestate_set}
724 Note that the above apply to server side only and they are not mandatory to be
725 used. Not using them, however, allows denial of service attacks.
726 The client side cookie handling is part of @funcref{gnutls_handshake}.
728 Datagrams are typically restricted by a maximum transfer unit (MTU). For that
729 both client and server side should set the correct maximum transfer unit for
730 the layer underneath @acronym{GnuTLS}. This will allow proper fragmentation
731 of DTLS messages and prevent messages from being silently discarded by the
732 transport layer. The ``correct'' maximum transfer unit can be obtained through
733 a path MTU discovery mechanism @xcite{RFC4821}.
735 @showfuncC{gnutls_dtls_set_mtu,gnutls_dtls_get_mtu,gnutls_dtls_get_data_mtu}
739 @section TLS handshake
740 Once a session has been initialized and a network
741 connection has been set up, TLS and DTLS protocols
742 perform a handshake. The handshake is the actual key
745 @showfuncdesc{gnutls_handshake}
747 @showfuncdesc{gnutls_handshake_set_timeout}
749 The handshake process doesn't ensure the verification
750 of the peer's identity. When certificates are in use,
751 this can be done, either after the handshake is complete, or during
752 the handshake if @funcref{gnutls_certificate_set_verify_function}
753 has been used. In both cases the @funcref{gnutls_certificate_verify_peers2} function can be
754 used to verify the peer's certificate (see @ref{Certificate authentication}
755 for more information).
757 @showfuncA{gnutls_certificate_verify_peers2}
759 @node Data transfer and termination
760 @section Data transfer and termination
761 Once the handshake is complete and peer's identity
762 has been verified data can be exchanged. The available
763 functions resemble the POSIX @code{recv} and @code{send}
764 functions. It is suggested to use @funcref{gnutls_error_is_fatal}
765 to check whether the error codes returned by these functions are
766 fatal for the protocol or can be ignored.
768 @showfuncdesc{gnutls_record_send}
770 @showfuncdesc{gnutls_record_recv}
772 @showfuncdesc{gnutls_error_is_fatal}
774 Although, in the TLS protocol the receive function can be called
775 at any time, when DTLS is used the GnuTLS receive functions must be
776 called once a message is available for reading, even if no data are
777 expected. This is because in DTLS various (internal) actions
778 may be required due to retransmission timers. Moreover,
779 an extended receive function is shown below, which allows the extraction
780 of the message's sequence number. Due to the unreliable nature of the
781 protocol, this field allows distinguishing out-of-order messages.
783 @showfuncdesc{gnutls_record_recv_seq}
785 The @funcref{gnutls_record_check_pending} helper function is available to
786 allow checking whether data are available to be read in a @acronym{GnuTLS} session
787 buffers. Note that this function complements but does not replace @funcintref{select},
788 i.e., @funcref{gnutls_record_check_pending} reports no data to be read, @funcintref{select}
789 should be called to check for data in the network buffers.
791 @showfuncdesc{gnutls_record_check_pending}
792 @showfuncA{gnutls_record_get_direction}
794 Once a TLS or DTLS session is no longer needed, it is
795 recommended to use @funcref{gnutls_bye} to terminate the
796 session. That way the peer is notified securely about the
797 intention of termination, which allows distinguishing it
798 from a malicious connection termination.
799 A session can be deinitialized with the @funcref{gnutls_deinit} function.
801 @showfuncdesc{gnutls_bye}
802 @showfuncdesc{gnutls_deinit}
804 @node Handling alerts
805 @section Handling alerts
806 During a TLS connection alert messages may be exchanged by the
807 two peers. Those messages may be fatal, meaning the connection
808 must be terminated afterwards, or warning when something needs
809 to be reported to the peer, but without interrupting the session.
810 The error codes @code{GNUTLS_E_@-WARNING_@-ALERT_@-RECEIVED}
811 or @code{GNUTLS_E_@-FATAL_@-ALERT_@-RECEIVED} signal those alerts
812 when received, and may be returned by all GnuTLS functions that receive
813 data from the peer, being @funcref{gnutls_handshake} and @funcref{gnutls_record_recv}.
815 If those error codes are received the alert and its level should be logged
816 or reported to the peer using the functions below.
818 @showfuncdesc{gnutls_alert_get}
819 @showfuncdesc{gnutls_alert_get_name}
821 The peer may also be warned or notified of a fatal issue
822 by using one of the functions below. All the available alerts
823 are listed in @ref{The Alert Protocol}.
825 @showfuncdesc{gnutls_alert_send}
826 @showfuncdesc{gnutls_error_to_alert}
829 @node Priority Strings
830 @section Priority strings
831 @cindex Priority strings
833 In order to specify cipher suite preferences on a TLS session
834 there are priority functions that accept a string
835 specifying the enabled for the handshake algorithms.
836 That string may contain a single initial keyword such as
837 in @ref{tab:prio-keywords} and may be followed by
838 additional algorithm or special keywords.
840 @showfuncB{gnutls_priority_set_direct,gnutls_priority_set}
842 @float Table,tab:prio-keywords
843 @multitable @columnfractions .20 .70
844 @headitem Keyword @tab Description
845 @item PERFORMANCE @tab
846 All the known to be secure ciphersuites are enabled,
847 limited to 128 bit ciphers and sorted by terms of speed
848 performance. The message authenticity security level is of 64 bits or more.
851 Means all the known to be secure ciphersuites. The ciphers are sorted by security
852 margin, although the 256-bit ciphers are included as a fallback only.
853 The message authenticity security level is of 64 bits or more.
856 Means all known to be secure ciphersuites that offer a
857 security level 128-bit or more and a message authenticity
858 security level of 80 bits or more.
861 Means all the known to be secure ciphersuites that offer a
862 security level 192-bit or more and a message authenticity
863 security level of 128 bits or more.
866 Currently alias for SECURE192.
869 Means all the NSA Suite B cryptography (RFC5430) ciphersuites
870 with an 128 bit security level.
873 Means all the NSA Suite B cryptography (RFC5430) ciphersuites
874 with an 192 bit security level.
877 Means all ciphersuites are enabled, including the
878 low-security 40 bit ciphers.
881 Means nothing is enabled. This disables even protocols and
882 compression methods. It should be followed by the
883 algorithms to be enabled.
886 @caption{Supported initial keywords.}
889 Unless the initial keyword is "NONE" the defaults (in preference
890 order) are for TLS protocols TLS 1.2, TLS1.1, TLS1.0, SSL3.0; for
891 compression NULL; for certificate types X.509.
892 In key exchange algorithms when in NORMAL or SECURE levels the
893 perfect forward secrecy algorithms take precedence of the other
894 protocols. In all cases all the supported key exchange algorithms
895 are enabled@footnote{Except for the RSA-EXPORT which is only enabled in
898 Note that the SECURE levels distinguish between overall security level and
899 message authenticity security level. That is because the message
900 authenticity security level requires the adversary to break
901 the algorithms at real-time during the protocol run, whilst
902 the overall security level refers to off-line adversaries
903 (e.g. adversaries breaking the ciphertext years after it was captured).
905 The NONE keyword, if used, must followed by keywords specifying
906 the algorithms and protocols to be enabled. The other initial keywords
907 do not require, but may be followed by such keywords. All level keywords
908 can be combined, and for example a level of "SECURE256:+SECURE128" is
911 The order with which every algorithm or protocol
912 is specified is significant. Algorithms specified before others
913 will take precedence. The supported algorithms and protocols
914 are shown in @ref{tab:prio-algorithms}.
915 To avoid collisions in order to specify a compression algorithm in
916 the priority string you have to prefix it with "COMP-", protocol versions
917 with "VERS-", signature algorithms with "SIGN-" and certificate types with "CTYPE-".
918 All other algorithms don't need a prefix. Each specified keyword can
919 be prefixed with any of the following characters.
923 appended with an algorithm will remove this algorithm.
925 appended with an algorithm will add this algorithm.
928 @float Table,tab:prio-algorithms
929 @multitable @columnfractions .20 .70
930 @headitem Type @tab Keywords
932 AES-128-CBC, AES-256-CBC, AES-128-GCM, CAMELLIA-128-CBC,
933 CAMELLIA-256-CBC, ARCFOUR-128, 3DES-CBC ARCFOUR-40. Catch all
934 name is CIPHER-ALL which will add all the algorithms from NORMAL
937 @item Key exchange @tab
938 RSA, DHE-RSA, DHE-DSS, SRP, SRP-RSA, SRP-DSS,
939 PSK, DHE-PSK, ECDHE-RSA, ANON-ECDH, ANON-DH, RSA-EXPORT. The
940 Catch all name is KX-ALL which will add all the algorithms from NORMAL
944 MD5, SHA1, SHA256, AEAD (used with
945 GCM ciphers only). All algorithms from NORMAL priority can be accessed with MAC-ALL.
947 @item Compression algorithms @tab
948 COMP-NULL, COMP-DEFLATE. Catch all is COMP-ALL.
950 @item TLS versions @tab
951 VERS-SSL3.0, VERS-TLS1.0, VERS-TLS1.1,
952 VERS-TLS1.2, VERS-DTLS1.0. Catch all is VERS-TLS-ALL.
954 @item Signature algorithms @tab
955 SIGN-RSA-SHA1, SIGN-RSA-SHA224,
956 SIGN-RSA-SHA256, SIGN-RSA-SHA384, SIGN-RSA-SHA512, SIGN-DSA-SHA1,
957 SIGN-DSA-SHA224, SIGN-DSA-SHA256, SIGN-RSA-MD5. Catch all
958 is SIGN-ALL. This is only valid for TLS 1.2 and later.
960 @item Elliptic curves @tab
961 CURVE-SECP192R1, CURVE-SECP224R1, CURVE-SECP256R1, CURVE-SECP384R1, CURVE-SECP521R1. Catch all is CURVE-ALL.
964 @caption{The supported algorithm keywords in priority strings.}
967 Note that the DHE key exchange methods are generally
968 slower@footnote{It depends on the group used. Primes with
969 lesser bits are always faster, but also easier to break. See @ref{Selecting cryptographic key sizes}
970 for the acceptable security levels.} than their elliptic curves counterpart
971 (ECDHE). Moreover the plain Diffie-Hellman key exchange
972 requires parameters to be generated and associated with a credentials
973 structure by the server (see @ref{Parameter generation}).
975 The available special keywords are shown in @ref{tab:prio-special1}
976 and @ref{tab:prio-special2}.
978 @float Table,tab:prio-special1
979 @multitable @columnfractions .45 .45
980 @headitem Keyword @tab Description
983 will enable compatibility mode. It might mean that violations
984 of the protocols are allowed as long as maximum compatibility with
985 problematic clients and servers is achieved. More specifically this
986 string would disable TLS record random padding and tolerate packets
987 over the maximum allowed TLS record.
989 @item %NO_EXTENSIONS @tab
990 will prevent the sending of any TLS extensions in client side. Note
991 that TLS 1.2 requires extensions to be used, as well as safe
992 renegotiation thus this option must be used with care.
994 @item %SERVER_PRECEDENCE @tab
995 The ciphersuite will be selected according to server priorities
996 and not the client's.
998 @item %SSL3_RECORD_VERSION @tab
999 will use SSL3.0 record version in client hello.
1000 This is the default.
1002 @item %LATEST_RECORD_VERSION @tab
1003 will use the latest TLS version record version in client hello.
1006 @caption{Special priority string keywords.}
1009 @float Table,tab:prio-special2
1010 @multitable @columnfractions .45 .45
1011 @headitem Keyword @tab Description
1013 @item %STATELESS_COMPRESSION @tab
1014 will disable keeping state across records when compressing. This may
1015 help to mitigate attacks when compression is used but an attacker
1016 is in control of input data. This has to be used only when the
1017 data that are possibly controlled by an attacker are placed in
1020 @item %DISABLE_SAFE_RENEGOTIATION @tab
1021 will completely disable safe renegotiation
1022 completely. Do not use unless you know what you are doing.
1024 @item %UNSAFE_RENEGOTIATION @tab
1025 will allow handshakes and re-handshakes
1026 without the safe renegotiation extension. Note that for clients
1027 this mode is insecure (you may be under attack), and for servers it
1028 will allow insecure clients to connect (which could be fooled by an
1029 attacker). Do not use unless you know what you are doing and want
1030 maximum compatibility.
1032 @item %PARTIAL_RENEGOTIATION @tab
1033 will allow initial handshakes to proceed,
1034 but not re-handshakes. This leaves the client vulnerable to attack,
1035 and servers will be compatible with non-upgraded clients for
1036 initial handshakes. This is currently the default for clients and
1037 servers, for compatibility reasons.
1039 @item %SAFE_RENEGOTIATION @tab
1040 will enforce safe renegotiation. Clients and
1041 servers will refuse to talk to an insecure peer. Currently this
1042 causes interoperability problems, but is required for full protection.
1044 @item %VERIFY_ALLOW_SIGN_RSA_MD5 @tab
1045 will allow RSA-MD5 signatures in certificate chains.
1047 @item %VERIFY_DISABLE_CRL_CHECKS @tab
1048 will disable CRL or OCSP checks in the verification of the certificate chain.
1050 @item %VERIFY_ALLOW_X509_V1_CA_CRT @tab
1051 will allow V1 CAs in chains.
1054 @caption{More priority string keywords.}
1057 Finally the ciphersuites enabled by any priority string can be
1058 listed using the @code{gnutls-cli} application (see @ref{gnutls-cli Invocation}),
1059 or by using the priority functions as in @ref{Listing the ciphersuites in a priority string}.
1061 Example priority strings are:
1063 The default priority without the HMAC-MD5:
1066 Specifying RSA with AES-128-CBC:
1067 "NONE:+VERS-TLS-ALL:+MAC-ALL:+RSA:+AES-128-CBC:+SIGN-ALL:+COMP-NULL"
1069 Specifying the defaults except ARCFOUR-128:
1070 "NORMAL:-ARCFOUR-128"
1072 Enabling the 128-bit secure ciphers, while disabling SSL 3.0 and enabling compression:
1073 "SECURE128:-VERS-SSL3.0:+COMP-DEFLATE"
1075 Enabling the 128-bit and 192-bit secure ciphers, while disabling all TLS versions
1077 "SECURE128:+SECURE192:-VERS-TLS-ALL:+VERS-TLS1.2"
1080 @node Selecting cryptographic key sizes
1081 @section Selecting cryptographic key sizes
1084 Because many algorithms are involved in TLS, it is not easy to set
1085 a consistent security level. For this reason in @ref{tab:key-sizes} we
1086 present some correspondence between key sizes of symmetric algorithms
1087 and public key algorithms based on @xcite{ECRYPT}.
1088 Those can be used to generate certificates with
1089 appropriate key sizes as well as select parameters for Diffie-Hellman and SRP
1092 @float Table,tab:key-sizes
1093 @multitable @columnfractions .10 .12 .10 .20 .32
1095 @headitem Security bits @tab RSA, DH and SRP parameter size @tab ECC key size @tab Security parameter @tab Description
1100 @tab @code{INSECURE}
1101 @tab Considered to be insecure
1107 @tab Short term protection against small organizations
1113 @tab Very short term protection against agencies
1119 @tab Legacy standard level
1125 @tab Medium-term protection
1131 @tab Long term protection
1137 @tab Foreseeable future
1140 @caption{Key sizes and security parameters.}
1143 The first column provides a security parameter in a number of bits. This
1144 gives an indication of the number of combinations to be tried by an adversary
1145 to brute force a key. For example to test all possible keys in a 112 bit security parameter
1146 @math{2^{112}} combinations have to be tried. For today's technology this is infeasible.
1147 The next two columns correlate the security
1148 parameter with actual bit sizes of parameters for DH, RSA, SRP and ECC algorithms.
1149 A mapping to @code{gnutls_sec_param_t} value is given for each security parameter, on
1150 the next column, and finally a brief description of the level.
1152 @c @showenumdesc{gnutls_sec_param_t,The @code{gnutls_sec_@-param_t} enumeration.}
1154 Note, however, that the values suggested here are nothing more than an
1155 educated guess that is valid today. There are no guarantees that an
1156 algorithm will remain unbreakable or that these values will remain
1157 constant in time. There could be scientific breakthroughs that cannot
1158 be predicted or total failure of the current public key systems by
1159 quantum computers. On the other hand though the cryptosystems used in
1160 TLS are selected in a conservative way and such catastrophic
1161 breakthroughs or failures are believed to be unlikely.
1162 The NIST publication SP 800-57 @xcite{NISTSP80057} contains a similar
1165 When using @acronym{GnuTLS} and a decision on bit sizes for a public
1166 key algorithm is required, use of the following functions is
1169 @showfuncdesc{gnutls_sec_param_to_pk_bits}
1171 @showfuncdesc{gnutls_pk_bits_to_sec_param}
1173 Those functions will convert a human understandable security parameter
1174 of @code{gnutls_sec_param_t} type, to a number of bits suitable for a public
1177 The following functions will set the minimum acceptable group size for Diffie-Hellman
1178 and SRP authentication.
1179 @showfuncB{gnutls_dh_set_prime_bits,gnutls_srp_set_prime_bits}
1182 @node Advanced topics
1183 @section Advanced topics
1186 * Session resumption::
1187 * Certificate verification::
1188 * Parameter generation::
1189 * Keying Material Exporters::
1190 * Channel Bindings::
1191 * Interoperability::
1192 * Compatibility with the OpenSSL library::
1195 @node Session resumption
1196 @subsection Session resumption
1197 @cindex resuming sessions
1198 @cindex session resumption
1200 @subsubheading Client side
1202 To reduce time and roundtrips spent in a handshake the client can
1203 request session resumption from a server that previously shared
1204 a session with. For that the client has to retrieve and store
1205 the session parameters. Before establishing a new session to the same
1206 server the parameters must be re-associated with the GnuTLS session
1207 using @funcref{gnutls_session_set_data}.
1209 @showfuncC{gnutls_session_get_data2,gnutls_session_get_id2,gnutls_session_set_data}
1211 Keep in mind that sessions will be expired after some time, depending
1212 on the server, and a server may choose not to resume a session
1213 even when requested to. The expiration is to prevent temporal session keys
1214 from becoming long-term keys. Also note that as a client you must enable,
1215 using the priority functions, at least the algorithms used in the last session.
1217 @showfuncdesc{gnutls_session_is_resumed}
1219 @subsubheading Server side
1221 In order to support resumption a server can store
1222 the session security parameters in a local database or by using session
1223 tickets (see @ref{Session tickets}) to delegate storage to the client. Because
1224 session tickets might not be supported by all clients, servers
1225 could combine the two methods.
1227 A storing server needs to specify callback functions to store, retrieve and delete session data. These can be
1228 registered with the functions below. The stored sessions in the database can be checked using @funcref{gnutls_db_check_entry}
1231 @showfuncD{gnutls_db_set_retrieve_function,gnutls_db_set_store_function,gnutls_db_set_ptr,gnutls_db_set_remove_function}
1232 @showfuncA{gnutls_db_check_entry}
1234 A server utilizing tickets should generate ticket encryption
1235 and authentication keys using @funcref{gnutls_session_ticket_key_generate}.
1236 Those keys should be associated with the GnuTLS session using
1237 @funcref{gnutls_session_ticket_enable_server}.
1239 @showfuncdesc{gnutls_session_ticket_enable_server}
1240 @showfuncdesc{gnutls_session_ticket_key_generate}
1241 @showfuncdesc{gnutls_session_resumption_requested}
1243 A server enabling both session tickets and a storage for session data
1244 would use session tickets when clients support it and the storage otherwise.
1246 @node Certificate verification
1247 @subsection Certificate verification
1250 @cindex SSH-style authentication
1251 @cindex Trust on first use
1253 @tindex gnutls_certificate_verify_flags
1255 In this section the functionality for additional certificate verification methods is listed.
1256 These methods are intended to be used in addition to normal PKI verification, in order to reduce
1257 the risk of a compromised CA being undetected.
1259 @subsubsection Trust on first use
1261 The GnuTLS library includes functionlity to use an SSH-like trust on first use authentication.
1262 The available functions to store and verify public keys are listed below.
1264 @showfuncdesc{gnutls_verify_stored_pubkey}
1265 @showfuncdesc{gnutls_store_pubkey}
1267 In addition to the above the @funcref{gnutls_store_commitment} can be
1268 used to implement a key-pinning architecture as in @xcite{KEYPIN}.
1269 This provides a way for web server to commit on a public key that is
1272 @showfuncdesc{gnutls_store_commitment}
1274 The storage and verification functions may be used with the default
1275 text file based back-end, or another back-end may be specified. That
1276 should contain storage and retrieval functions and specified as below.
1278 @showfuncE{gnutls_tdb_init,gnutls_tdb_deinit,gnutls_tdb_set_verify_func,gnutls_tdb_set_store_func,gnutls_tdb_set_store_commitment_func}
1280 @subsubsection DANE verification
1281 Since the DANE library is not included in GnuTLS it requires programs
1282 to be linked against it. This can be achieved with the following commands.
1285 gcc -o foo foo.c `pkg-config gnutls-dane --cflags --libs`
1288 When a program uses the GNU autoconf system, then the following
1289 line or similar can be used to detect the presence of the library.
1292 PKG_CHECK_MODULES([LIBDANE], [gnutls-dane >= 3.0.0])
1294 AC_SUBST([LIBDANE_CFLAGS])
1295 AC_SUBST([LIBDANE_LIBS])
1298 The high level functionality provided by the DANE library is shown below.
1300 @showfuncdesc{dane_verify_crt}
1302 @showfuncB{dane_verify_session_crt,dane_strerror}
1304 Note that the @code{dane_state_t} structure that is accepted by both
1305 verification functions is optional. It is required when many queries
1306 are performed to facilitate caching.
1307 The following flags are returned by the verify functions to
1308 indicate the status of the verification.
1310 @showenumdesc{dane_verify_status_t,The DANE verification status flags.}
1312 In order to generate a DANE TLSA entry to use in a DNS server
1313 you may use danetool (see @ref{danetool Invocation}).
1317 @node Parameter generation
1318 @subsection Parameter generation
1319 @cindex parameter generation
1320 @cindex generating parameters
1322 Several TLS ciphersuites require additional parameters that
1323 need to be generated or provided by the application. The
1324 Diffie-Hellman based ciphersuites (ANON-DH or DHE), require
1325 the group parameters to be provided. Those can either be
1326 be generated on the fly using @funcref{gnutls_dh_params_generate2}
1327 or imported from pregenerated data using @funcref{gnutls_dh_params_import_pkcs3}.
1328 The parameters can be used in a @acronym{TLS} session by calling
1329 @funcref{gnutls_certificate_set_dh_params} or
1330 @funcref{gnutls_anon_set_server_dh_params} for anonymous sessions.
1332 @showfuncD{gnutls_dh_params_generate2,gnutls_dh_params_import_pkcs3,gnutls_certificate_set_dh_params,gnutls_anon_set_server_dh_params}
1334 Due to the time-consuming calculations required for the generation
1335 of Diffie-Hellman parameters we suggest against performing generation
1336 of them within an application. The @code{certtool} tool can be used to
1337 generate or export known safe values that can be stored in code
1338 or in a configuration file to provide the ability to replace. We also
1339 recommend the usage of @funcref{gnutls_sec_param_to_pk_bits}
1340 (see @ref{Selecting cryptographic key sizes}) to determine
1341 the bit size of the generated parameters.
1343 Note that the information stored in the generated PKCS #3 structure
1344 changed with GnuTLS 3.0.9. Since that version the @code{privateValueLength}
1345 member of the structure is set, allowing the server utilizing the
1346 parameters to use keys of the size of the security parameter. This
1347 provides better performance in key exchange.
1349 The ciphersuites that involve the RSA-EXPORT key exchange require
1350 additional parameters. Those ciphersuites are rarely used today
1351 because they are by design insecure, thus if you have no requirement
1352 for them, the rest of this section can be skipped. The RSA-EXPORT key exchange
1353 requires 512-bit RSA keys to be generated. It is recommended those
1354 parameters to be refreshed (regenerated) in short intervals. The
1355 following functions can be used for these parameters.
1357 @showfuncD{gnutls_rsa_params_generate2,gnutls_certificate_set_rsa_export_params,gnutls_rsa_params_import_pkcs1,gnutls_rsa_params_export_pkcs1}
1359 To allow renewal of the parameters within an application without
1360 accessing the credentials, which are a shared structure,
1361 an alternative interface is available using a callback function.
1363 @showfuncdesc{gnutls_certificate_set_params_function}
1366 @node Keying Material Exporters
1367 @subsection Keying material exporters
1368 @cindex keying material exporters
1369 @cindex exporting keying material
1371 The TLS PRF can be used by other protocols to derive keys based on
1372 the TLS master secret. The API to use is @funcref{gnutls_prf}. The
1373 function needs to be provided with the label in the parameter
1374 @code{label}, and the extra data to mix in the
1375 @code{extra} parameter. Depending on whether you want to mix in the
1376 client or server random data first, you can set the
1377 @code{server_random_first} parameter.
1379 For example, after establishing a TLS session using
1380 @funcref{gnutls_handshake}, you can invoke the TLS PRF with this call:
1383 #define MYLABEL "EXPORTER-FOO"
1384 #define MYCONTEXT "some context data"
1386 rc = gnutls_prf (session, strlen (MYLABEL), MYLABEL, 0,
1387 strlen (MYCONTEXT), MYCONTEXT, 32, out);
1390 If you don't want to mix in the client/server random, there is a
1391 low-level TLS PRF interface called @funcref{gnutls_prf_raw}.
1393 @node Channel Bindings
1394 @subsection Channel bindings
1395 @cindex channel bindings
1397 In user authentication protocols (e.g., EAP or SASL mechanisms) it is
1398 useful to have a unique string that identifies the secure channel that
1399 is used, to bind together the user authentication with the secure
1400 channel. This can protect against man-in-the-middle attacks in some
1401 situations. That unique string is called a ``channel binding''. For
1402 background and discussion see @xcite{RFC5056}.
1404 In @acronym{GnuTLS} you can extract a channel binding using the
1405 @funcref{gnutls_session_channel_binding} function. Currently only the
1406 type @code{GNUTLS_CB_TLS_UNIQUE} is supported, which corresponds to
1407 the @code{tls-unique} channel binding for TLS defined in
1410 The following example describes how to print the channel binding data.
1411 Note that it must be run after a successful TLS handshake.
1418 rc = gnutls_session_channel_binding (session,
1419 GNUTLS_CB_TLS_UNIQUE,
1422 fprintf (stderr, "Channel binding error: %s\n",
1423 gnutls_strerror (rc));
1427 printf ("- Channel binding 'tls-unique': ");
1428 for (i = 0; i < cb.size; i++)
1429 printf ("%02x", cb.data[i]);
1435 @node Interoperability
1436 @subsection Interoperability
1438 The @acronym{TLS} protocols support many ciphersuites, extensions and version
1439 numbers. As a result, few implementations are
1440 not able to properly interoperate once faced with extensions or version protocols
1441 they do not support and understand. The @acronym{TLS} protocol allows for a
1442 graceful downgrade to the commonly supported options, but practice shows
1443 it is not always implemented correctly.
1445 Because there is no way to achieve maximum interoperability with broken peers
1446 without sacrificing security, @acronym{GnuTLS} ignores such peers by default.
1447 This might not be acceptable in cases where maximum compatibility
1448 is required. Thus we allow enabling compatibility with broken peers using
1449 priority strings (see @ref{Priority Strings}). A conservative priority
1450 string that would disable certain @acronym{TLS} protocol
1451 options that are known to cause compatibility problems, is shown below.
1456 For broken peers that do not tolerate TLS version numbers over TLS 1.0
1457 another priority string is:
1459 NORMAL:-VERS-TLS-ALL:+VERS-TLS1.0:+VERS-SSL3.0:%COMPAT
1461 This priority string will in addition to above, only enable SSL 3.0 and
1462 TLS 1.0 as protocols. Note however that
1463 there are known attacks against those protocol versions, especially over
1464 the CBC-mode ciphersuites. To mitigate them another priority string
1465 that only allows the stream cipher ARCFOUR is below.
1467 NORMAL:-VERS-TLS-ALL:+VERS-TLS1.0:+VERS-SSL3.0:-CIPHER-ALL:+ARCFOUR-128:%COMPAT
1472 @node Compatibility with the OpenSSL library
1473 @subsection Compatibility with the OpenSSL library
1476 To ease @acronym{GnuTLS}' integration with existing applications, a
1477 compatibility layer with the OpenSSL library is included
1478 in the @code{gnutls-openssl} library. This compatibility layer is not
1479 complete and it is not intended to completely re-implement the OpenSSL
1480 API with @acronym{GnuTLS}. It only provides limited source-level
1483 The prototypes for the compatibility functions are in the
1484 @file{gnutls/openssl.h} header file. The limitations
1485 imposed by the compatibility layer include:
1489 @item Error handling is not thread safe.