Internal Architecture of GnuTLS
*******************************

This chapter is to give a brief description of the way GnuTLS works. The focus is to give an idea to potential developers and those who want to know what happens inside the black box.

The TLS Protocol
================

The main use case for the TLS protocol is shown in fig-client-server. A user of a library implementing the protocol expects no less than this functionality, i.e., to be able to set parameters such as the accepted security level, perform a negotiation with the peer and be able to exchange data.

Figure: TLS protocol use case.

TLS Handshake Protocol
======================

The GnuTLS handshake protocol is implemented as a state machine that waits for input or returns immediately when the non-blocking transport layer functions are used. The main idea is shown in fig-gnutls-handshake.

Figure: GnuTLS handshake state machine.

Also the way the input is processed varies per ciphersuite. Several implementations of the internal handlers are available and gnutls_handshake only multiplexes the input to the appropriate handler. For example a PSK ciphersuite has a different implementation of the process_client_key_exchange than a certificate ciphersuite. We illustrate the idea in fig-gnutls-handshake-sequence.

Figure: GnuTLS handshake process sequence.

TLS Authentication Methods
==========================

In GnuTLS authentication methods can be implemented quite easily.  Since the required changes to add a new authentication method affect only the handshake protocol, a simple interface is used. An authentication method needs to implement the functions shown below.

typedef struct
{
  const char *name;
  int (*gnutls_generate_server_certificate) (gnutls_session_t, gnutls_buffer_st*);
  int (*gnutls_generate_client_certificate) (gnutls_session_t, gnutls_buffer_st*);
  int (*gnutls_generate_server_kx) (gnutls_session_t, gnutls_buffer_st*);
  int (*gnutls_generate_client_kx) (gnutls_session_t, gnutls_buffer_st*);
  int (*gnutls_generate_client_cert_vrfy) (gnutls_session_t, gnutls_buffer_st *);
  int (*gnutls_generate_server_certificate_request) (gnutls_session_t,
                                                     gnutls_buffer_st *);

  int (*gnutls_process_server_certificate) (gnutls_session_t, opaque *,
                                            size_t);
  int (*gnutls_process_client_certificate) (gnutls_session_t, opaque *,
                                            size_t);
  int (*gnutls_process_server_kx) (gnutls_session_t, opaque *, size_t);
  int (*gnutls_process_client_kx) (gnutls_session_t, opaque *, size_t);
  int (*gnutls_process_client_cert_vrfy) (gnutls_session_t, opaque *, size_t);
  int (*gnutls_process_server_certificate_request) (gnutls_session_t,
                                                    opaque *, size_t);
} mod_auth_st;

Those functions are responsible for the interpretation of the handshake protocol messages. It is common for such functions to read data from one or more credentials_t structures (such as the gnutls_certificate_credentials_t structures) and write data, such as certificates, usernames etc. to auth_info_t structures.

Simple examples of existing authentication methods can be seen in auth/psk.c for PSK ciphersuites and auth/srp.c for SRP ciphersuites. After implementing these functions the structure holding its pointers has to be registered in gnutls_algorithms.c in the _gnutls_kx_algorithms structure.

TLS Extension Handling
======================

As with authentication methods, adding TLS hello extensions can be done quite easily by implementing the interface shown below.

typedef int (*gnutls_ext_recv_func) (gnutls_session_t session,
                                     const unsigned char *data, size_t len);
typedef int (*gnutls_ext_send_func) (gnutls_session_t session,
                                     gnutls_buffer_st *extdata);

Here there are two main functions, one for parsing the received extension data and one for formatting the extension data that must be send. These functions have to check internally whether they operate within a client or a server session.

A simple example of an extension handler can be seen in lib/ext/srp.c in GnuTLS' source code. After implementing these functions, the extension has to be registered. Registering an extension can be done in two ways. You can create a GnuTLS internal extension and register it in hello_ext.c or write an external extension (not inside GnuTLS but inside an application using GnuTLS) and register it via the exported functions gnutls_session_ext_register or gnutls_ext_register.

Adding a new TLS hello extension
--------------------------------

Adding support for a new TLS hello extension is done from time to time, and the process to do so is not difficult. Here are the steps you need to follow if you wish to do this yourself. For the sake of discussion, let's consider adding support for the hypothetical TLS extension foobar. The following section is about adding an hello extension to GnuTLS itself. For custom application extensions you should check the exported functions gnutls_session_ext_register or gnutls_ext_register.

Add configure option like --enable-foobar or --disable-foobar.
..............................................................

This step is useful when the extension code is large and it might be desirable under some circumstances to be able to leave out the extension during compilation of GnuTLS. If you don't need this kind of feature this step can be safely skipped.

Whether to choose enable or disable depends on whether you intend to make the extension be enabled by default. Look at existing checks (i.e., SRP, authz) for how to model the code. For example:

     AC_MSG_CHECKING([whether to disable foobar support])
     AC_ARG_ENABLE(foobar,
     	AS_HELP_STRING([--disable-foobar],
     		[disable foobar support]),
     	ac_enable_foobar=no)
     if test x$ac_enable_foobar != xno; then
      AC_MSG_RESULT(no)
      AC_DEFINE(ENABLE_FOOBAR, 1, [enable foobar])
     else
      ac_full=0
      AC_MSG_RESULT(yes)
     fi
     AM_CONDITIONAL(ENABLE_FOOBAR, test "$ac_enable_foobar" != "no")

These lines should go in lib/m4/hooks.m4.

Add an extension identifier to extensions_t in gnutls_int.h.
............................................................

A good name for the identifier would be GNUTLS_EXTENSION_FOOBAR. If the extension that you are implementing is an extension that is officially registered by IANA then it is recommended to use its official name such that the extension can be correctly identified by other developers. Check with https://www.iana.org/assignments/tls-extensiontype-values for registered extensions.

Register the extension in lib/hello_ext.c.
..........................................

In order for the extension to be executed you need to register it in the static hello_ext_entry_st const *extfunc[] list in lib/hello_ext.c.

A typical entry would be:

     #ifdef ENABLE_FOOBAR
     	[GNUTLS_EXTENSION_FOOBAR] = &ext_mod_foobar,
     #endif

Also for every extension you need to create an hello_ext_entry_st that describes the extension. This structure is placed in the designated c file for your extension and its name is used in the registration entry as depicted above.

The structure of hello_ext_entry_st is as follows:

       const hello_ext_entry_st ext_mod_foobar = {
         .name = "FOOBAR",
         .tls_id = 255,
         .gid = GNUTLS_EXTENSION_FOOBAR,
         .parse_type = GNUTLS_EXT_TLS,
         .validity = GNUTLS_EXT_FLAG_CLIENT_HELLO |
     	GNUTLS_EXT_FLAG_TLS12_SERVER_HELLO |
     	GNUTLS_EXT_FLAG_TLS13_SERVER_HELLO |
     	GNUTLS_EXT_FLAG_TLS,
         .recv_func = _gnutls_foobar_recv_params,
         .send_func = _gnutls_foobar_send_params,
         .pack_func = _gnutls_foobar_pack,
         .unpack_func = _gnutls_foobar_unpack,
         .deinit_func = _gnutls_foobar_deinit,
         .cannot_be_overriden = 1
       };

The GNUTLS_EXTENSION_FOOBAR is the identifier that you've added to gnutls_int.h earlier. The .tls_id should contain the number that IANA has assigned to this extension, or an unassigned number of your choice if this is an unregistered extension. In the rest of this structure you specify the functions to handle the extension data. The receive function will be called upon reception of the data and will be used to parse or interpret the extension data. The send function will be called prior to sending the extension data on the wire and will be used to format the data such that it can be send over the wire. The pack and unpack functions will be used to prepare the data for storage in case of session resumption (and vice versa). The deinit function will be called to deinitialize the extension's private parameters, if any.

Look at gnutls_ext_parse_type_t and gnutls_ext_flags_t for a complete list of available flags.

Note that the conditional ENABLE_FOOBAR definition should only be used if step 1 with the configure options has taken place.

Add new files that implement the hello extension.
.................................................

To keep things structured every extension should have its own files. The functions that you should (at least) add are those referenced in the struct from the previous step. Use descriptive file names such as lib/ext/foobar.c and for the corresponding header lib/ext/foobar.h. As a starter, you could add this:

     int
     _gnutls_foobar_recv_params (gnutls_session_t session, const uint8_t * data,
                          size_t data_size)
     {
       return 0;
     }

     int
     _gnutls_foobar_send_params (gnutls_session_t session, gnutls_buffer_st* data)
     {
       return 0;
     }

     int
     _gnutls_foobar_pack (extension_priv_data_t epriv, gnutls_buffer_st * ps)
     {
        /* Append the extension's internal state to buffer */
        return 0;
     }

     int
     _gnutls_foobar_unpack (gnutls_buffer_st * ps, extension_priv_data_t * epriv)
     {
        /* Read the internal state from buffer */
        return 0;
     }

The _gnutls_foobar_recv_params function is responsible for parsing incoming extension data (both in the client and server).

The _gnutls_foobar_send_params function is responsible for formatting extension data such that it can be send over the wire (both in the client and server). It should append data to provided buffer and return a positive (or zero) number on success or a negative error code. Previous to 3.6.0 versions of GnuTLS required that function to return the number of bytes that were written. If zero is returned and no bytes are appended the extension will not be sent. If a zero byte extension is to be sent this function must return GNUTLS_E_INT_RET_0.

If you receive length fields that don't match, return GNUTLS_E_UNEXPECTED_PACKET_LENGTH.  If you receive invalid data, return GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER.  You can use other error codes from the list in Error codes. Return 0 on success.

An extension typically stores private information in the session data for later usage. That can be done using the functions _gnutls_hello_ext_set_datum and _gnutls_hello_ext_get_datum. You can check simple examples at lib/ext/max_record.c and lib/ext/server_name.c extensions. That private information can be saved and restored across session resumption if the following functions are set:

The _gnutls_foobar_pack function is responsible for packing internal extension data to save them in the session resumption storage.

The _gnutls_foobar_unpack function is responsible for restoring session data from the session resumption storage.

When the internal data is stored using the _gnutls_hello_ext_set_datum, then you can rely on the default pack and unpack functions: _gnutls_hello_ext_default_pack and _gnutls_hello_ext_default_unpack.

Recall that both for the client and server, the send and receive functions most likely will need to do different things depending on which mode they are in. It may be useful to make this distinction explicit in the code. Thus, for example, a better template than above would be:

     int
     _gnutls_foobar_recv_params (gnutls_session_t session,
                                 const uint8_t * data,
                                 size_t data_size)
     {
       if (session->security_parameters.entity == GNUTLS_CLIENT)
         return foobar_recv_client (session, data, data_size);
       else
         return foobar_recv_server (session, data, data_size);
     }

     int
     _gnutls_foobar_send_params (gnutls_session_t session,
                                 gnutls_buffer_st * data)
     {
       if (session->security_parameters.entity == GNUTLS_CLIENT)
         return foobar_send_client (session, data);
       else
         return foobar_send_server (session, data);
     }

The functions used would be declared as static functions, of the appropriate prototype, in the same file.

When adding the new extension files, you'll need to add them to lib/ext/Makefile.am as well, for example:

     if ENABLE_FOOBAR
     libgnutls_ext_la_SOURCES += ext/foobar.c ext/foobar.h
     endif

Add API functions to use the extension.
.......................................

It might be desirable to allow users of the extension to request the use of the extension, or set extension specific data. This can be implemented by adding extension specific function calls that can be added to includes/gnutls/gnutls.h, as long as the LGPLv2.1+ applies. The implementation of these functions should lie in the lib/ext/foobar.c file.

To make the API available in the shared library you need to add the added symbols in lib/libgnutls.map, so that the symbols are exported properly.

When writing GTK-DOC style documentation for your new APIs, don't forget to add Since: tags to indicate the GnuTLS version the API was introduced in.

Adding a new Supplemental Data Handshake Message
------------------------------------------------

TLS handshake extensions allow to send so called supplemental data handshake messages RFC4680. This short section explains how to implement a supplemental data handshake message for a given TLS extension.

First of all, modify your extension foobar in the way, to instruct the handshake process to send and receive supplemental data, as shown below.

     int
     _gnutls_foobar_recv_params (gnutls_session_t session, const opaque * data,
                                      size_t _data_size)
     {
        ...
        gnutls_supplemental_recv(session, 1);
        ...
     }

     int
     _gnutls_foobar_send_params (gnutls_session_t session, gnutls_buffer_st *extdata)
     {
        ...
        gnutls_supplemental_send(session, 1);
        ...
     }

Furthermore you'll need two new functions _foobar_supp_recv_params and _foobar_supp_send_params, which must conform to the following prototypes.

     typedef int (*gnutls_supp_recv_func)(gnutls_session_t session,
                                          const unsigned char *data,
                                          size_t data_size);
     typedef int (*gnutls_supp_send_func)(gnutls_session_t session,
                                          gnutls_buffer_t buf);

The following example code shows how to send a ``Hello World'' string in the supplemental data handshake message.

     int
     _foobar_supp_recv_params(gnutls_session_t session, const opaque *data, size_t _data_size)
     {
        uint8_t len = _data_size;
        unsigned char *msg;

        msg = gnutls_malloc(len);
        if (msg == NULL) return GNUTLS_E_MEMORY_ERROR;

        memcpy(msg, data, len);
        msg[len]='\0';

        /* do something with msg */
        gnutls_free(msg);

        return len;
     }

     int
     _foobar_supp_send_params(gnutls_session_t session, gnutls_buffer_t buf)
     {
        unsigned char *msg = "hello world";
        int len = strlen(msg);

        if (gnutls_buffer_append_data(buf, msg, len) < 0)
            abort();

        return len;
     }

Afterwards, register the new supplemental data using gnutls_session_supplemental_register, or gnutls_supplemental_register at some point in your program.

Cryptographic Backend
=====================

Today most new processors, either for embedded or desktop systems include either instructions  intended to speed up cryptographic operations, or a co-processor with cryptographic capabilities. Taking advantage of those is a challenging task for every cryptographic  application or library. GnuTLS handles the cryptographic provider in a modular way, following a layered approach to access cryptographic operations as in fig-crypto-layers.

Figure: GnuTLS cryptographic back-end design.

The TLS layer uses a cryptographic provider layer, that will in turn either use the default crypto provider -- a software crypto library, or use an external crypto provider, if available in the local system. The reason of handling the external cryptographic provider in GnuTLS and not delegating it to the cryptographic libraries, is that none of the supported cryptographic libraries support /dev/crypto or CPU-optimized cryptography in an efficient way.

Cryptographic library layer
---------------------------

The Cryptographic library layer, currently supports only libnettle. Older versions of GnuTLS used to support libgcrypt, but it was switched with nettle mainly for performance reasons (See https://lists.gnu.org/archive/html/gnutls-devel/2011-02/msg00079.html.) and secondary because it is a simpler library to use. In the future other cryptographic libraries might be supported as well.

External cryptography provider
------------------------------

Systems that include a cryptographic co-processor, typically come with kernel drivers to utilize the operations from software. For this reason GnuTLS provides a layer where each individual algorithm used can be replaced by another implementation, i.e., the one provided by the driver. The FreeBSD, OpenBSD and Linux kernels (Check https://home.gna.org/cryptodev-linux/ for the Linux kernel implementation of /dev/crypto.) include already a number of hardware assisted implementations, and also provide an interface to access them, called /dev/crypto. GnuTLS will take advantage of this interface if compiled with special options. That is because in most systems where hardware-assisted cryptographic operations are not available, using this interface might actually harm performance.

In systems that include cryptographic instructions with the CPU's instructions set, using the kernel interface will introduce an unneeded layer. For this reason GnuTLS includes such optimizations found in popular processors such as the AES-NI or VIA PADLOCK instruction sets. This is achieved using a mechanism that detects CPU capabilities and overrides parts of crypto back-end at runtime. The next section discusses the registration of a detected algorithm optimization. For more information please consult the GnuTLS source code in lib/accelerated/.

Overriding specific algorithms
..............................

When an optimized implementation of a single algorithm is available, say a hardware assisted version of AES-CBC then the following functions, from crypto.h, can be used to register those algorithms.

  * gnutls_crypto_register_cipher: To register a cipher algorithm.

  * gnutls_crypto_register_aead_cipher: To register an AEAD cipher algorithm.

  * gnutls_crypto_register_mac: To register a MAC algorithm.

  * gnutls_crypto_register_digest: To register a hash algorithm.

Those registration functions will only replace the specified algorithm and leave the rest of subsystem intact.

Protecting keys through isolation
---------------------------------

For asymmetric or public keys, GnuTLS supports PKCS #11 which allows operation without access to long term keys, in addition to CPU offloading. For more information see Hardware security modules and abstract key types.

Random Number Generators
========================

About the generators
--------------------

GnuTLS provides two random generators. The default, and the AES-DRBG random generator which is only used when the library is compiled with support for FIPS140-2 and the system is in FIPS140-2 mode.

The default generator - inner workings
--------------------------------------

The random number generator levels in gnutls_rnd_level_t map to two CHACHA-based random generators which are initially seeded using the OS random device, e.g., /dev/urandom or getrandom(). These random generators are unique per thread, and are automatically re-seeded when a fork is detected.

The reason the CHACHA cipher was selected for the GnuTLS' PRNG is the fact that CHACHA is considered a secure and fast stream cipher, and is already defined for use in TLS protocol. As such, the utilization of it would not stress the CPU caches, and would allow for better performance on busy servers, irrespective of their architecture (e.g., even if AES is not available with an optimized instruction set).

The generators are unique per thread to allow lock-free operation. That induces a cost of around 140-bytes for the state of the generators per thread, on threads that would utilize gnutls_rnd. At the same time it allows fast and lock-free access to the generators. The lock-free access benefits servers which utilize more than 4 threads, while imposes no cost on single threaded processes.

On the first call to gnutls_rnd the generators are seeded with two independent keys obtained from the OS random device. Their seed is used to output a fixed amount of bytes before re-seeding; the number of bytes output varies per generator.

One generator is dedicated for the GNUTLS_RND_NONCE level, and the second is shared for the GNUTLS_RND_KEY and GNUTLS_RND_RANDOM levels. For the rest of this section we refer to the first as the nonce generator and the second as the key generator.

The nonce generator will reseed after outputting a fixed amount of bytes (typically few megabytes), or after few hours of operation without reaching the limit has passed. It is being re-seed using the key generator to obtain a new key for the CHACHA cipher, which is mixed with its old one.

Similarly, the key generator, will also re-seed after a fixed amount of bytes is generated (typically less than the nonce), and will also re-seed based on time, i.e., after few hours of operation without reaching the limit for a re-seed. For its re-seed it mixes mixes data obtained from the OS random device with the previous key.

Although the key generator used to provide data for the GNUTLS_RND_RANDOM and GNUTLS_RND_KEY levels is identical, when used with the GNUTLS_RND_KEY level a re-key of the PRNG using its own output, is additionally performed. That ensures that the recovery of the PRNG state will not be sufficient to recover previously generated values.

The AES-DRBG generator - inner workings
---------------------------------------

Similar with the default generator, the random number generator levels in gnutls_rnd_level_t map to two AES-DRBG random generators which are initially seeded using the OS random device, e.g., /dev/urandom or getrandom(). These random generators are unique per thread, and are automatically re-seeded when a fork is detected.

The AES-DRBG generator is based on the AES cipher in counter mode and is re-seeded after a fixed amount of bytes are generated.

Defense against PRNG attacks
----------------------------

This section describes the counter-measures available in the Pseudo-random number generator (PRNG) of GnuTLS for known attacks as described in PRNGATTACKS. Note that, the attacks on a PRNG such as state-compromise, assume a quite powerful adversary which has in practice access to the PRNG state.

Cryptanalytic
.............

To defend against cryptanalytic attacks GnuTLS' PRNG is a stream cipher designed to defend against the same attacks. As such, GnuTLS' PRNG strength with regards to this attack relies on the underlying crypto block, which at the time of writing is CHACHA. That is easily replaceable in the future if attacks are found to be possible in that cipher.

Input-based attacks
...................

These attacks assume that the attacker can influence the input that is used to form the state of the PRNG. To counter these attacks GnuTLS does not gather input from the system environment but rather relies on the OS provided random generator. That is the /dev/urandom or getentropy/getrandom system calls. As such, GnuTLS' PRNG is as strong as the system random generator can assure with regards to input-based attacks.

State-compromise: Backtracking
..............................

A backtracking attack, assumes that an adversary obtains at some point of time access to the generator state, and wants to recover past bytes. As the GnuTLS generator is fine-tuned to provide multiple levels, such an attack mainly concerns levels GNUTLS_RND_RANDOM and GNUTLS_RND_KEY, since GNUTLS_RND_NONCE is intended to output non-secret data. The GNUTLS_RND_RANDOM generator at the time of writing can output 2MB prior to being re-seeded thus this is its upper bound for previously generated data recovered using this attack. That assumes that the state of the operating system random generator is unknown to the attacker, and we carry that assumption on the next paragraphs. The usage of GNUTLS_RND_KEY level ensures that no backtracking is possible for all output data, by re-keying the PRNG using its own output.

Such an attack reflects the real world scenario where application's memory is temporarily compromised, while the kernel's memory is inaccessible.

State-compromise: Permanent Compromise Attack
.............................................

A permanent compromise attack implies that once an attacker compromises the state of GnuTLS' random generator at a specific time, future and past outputs from the generator are compromised. For past outputs the previous paragraph applies. For future outputs, both the GNUTLS_RND_RANDOM and the GNUTLS_RND_KEY will recover after 2MB of data have been generated or few hours have passed (two at the time of writing). Similarly the GNUTLS_RND_NONCE level generator will recover after several megabytes of output is generated, or its re-key time is reached.

State-compromise: Iterative guessing
....................................

This attack assumes that after an attacker obtained the PRNG state at some point, is able to recover the state at a later time by observing outputs of the PRNG. That is countered by switching the key to generators using a combination of a fresh key and the old one (using XOR), at re-seed time. All levels are immune to such attack after a re-seed.

State-compromise: Meet-in-the-Middle
....................................

This attack assumes that the attacker obtained the PRNG state at two distinct times, and being able to recover the state at the third time after observing the output of the PRNG. Given the approach described on the above paragraph, all levels are immune to such attack.

FIPS140-2 mode
==============

GnuTLS can operate in a special mode for FIPS140-2. That mode of operation is for the conformance to NIST's FIPS140-2 publication, which consists of policies for cryptographic modules (such as software libraries). Its implementation in GnuTLS is designed for Red Hat Enterprise Linux, and can only be enabled when the library is explicitly compiled with the '--enable-fips140-mode' configure option.

There are two distinct library states with regard to FIPS140-2: the FIPS140-2 mode is installed if /etc/system-fips is present, and the FIPS140-2 mode is enabled if /proc/sys/crypto/fips_enabled contains '1', which is typically set with the ``fips=1'' kernel command line option.

When the FIPS140-2 mode is installed, the operation of the library is modified as follows.

  * The random generator used switches to DRBG-AES

  * The integrity of the GnuTLS and dependent libraries is checked on startup

  * Algorithm self-tests are run on library load

When the FIPS140-2 mode is enabled, The operation of the library is in addition modified as follows.

  * Only approved by FIPS140-2 algorithms are enabled

  * Only approved by FIPS140-2 key lengths are allowed for key generation

  * Any cryptographic operation will be refused if any of the self-tests failed

There are also few environment variables which modify that operation. The environment variable GNUTLS_SKIP_FIPS_INTEGRITY_CHECKS will disable the library integrity tests on startup, and the variable GNUTLS_FORCE_FIPS_MODE can be set to force a value from gnutls_fips_mode_t, i.e., '1' will enable the FIPS140-2 mode, while '0' will disable it.

The integrity checks for the dependent libraries and GnuTLS are performed using '.hmac' files which are present at the same path as the library. The key for the operations can be provided on compile-time with the configure option '--with-fips140-key'. The MAC algorithm used is HMAC-SHA256.

On runtime an application can verify whether the library is in FIPS140-2 mode using the gnutls_fips140_mode_enabled function.

Relaxing FIPS140-2 requirements
-------------------------------

The library by default operates in a strict enforcing mode, ensuring that all constraints imposed by the FIPS140-2 specification are enforced. However the application can relax these requirements via gnutls_fips140_set_mode which can switch to alternative modes as in gnutls_fips_mode_t.

gnutls_fips_mode_t,The gnutls_fips_mode_t enumeration.

The intention of this API is to be used by applications which may run in FIPS140-2 mode, while they utilize few algorithms not in the allowed set, e.g., for non-security related purposes. In these cases applications should wrap the non-compliant code within blocks like the following.

     GNUTLS_FIPS140_SET_LAX_MODE();

     _gnutls_hash_fast(GNUTLS_DIG_MD5, buffer, sizeof(buffer), output);

     GNUTLS_FIPS140_SET_STRICT_MODE();

The GNUTLS_FIPS140_SET_LAX_MODE and GNUTLS_FIPS140_SET_STRICT_MODE are macros to simplify the following sequence of calls.

     if (gnutls_fips140_mode_enabled())
       gnutls_fips140_set_mode(GNUTLS_FIPS140_LAX, GNUTLS_FIPS140_SET_MODE_THREAD);

     _gnutls_hash_fast(GNUTLS_DIG_MD5, buffer, sizeof(buffer), output);

     if (gnutls_fips140_mode_enabled())
       gnutls_fips140_set_mode(GNUTLS_FIPS140_STRICT, GNUTLS_FIPS140_SET_MODE_THREAD);

The reason of the GNUTLS_FIPS140_SET_MODE_THREAD flag in the previous calls is to localize the change in the mode. Note also, that such a block has no effect when the library is not operating under FIPS140-2 mode, and thus it can be considered a no-op.

Applications could also switch FIPS140-2 mode explicitly off, by calling

     gnutls_fips140_set_mode(GNUTLS_FIPS140_LAX, 0);

Service indicator
-----------------

The above restrictions may not cover all the requirements in every usage context, and as the FIPS140 standard evolves (like FIPS140-3), GnuTLS may not be able to add new restrictions without breaking compatibility.

Therefore an additional set of API functions is provided to communicate with the user whether any approved mode of operations is performed within a given context.

gnutls_fips140_context_init,gnutls_fips140_context_deinit,gnutls_fips140_push_context,gnutls_fips140_pop_context

The gnutls_fips140_context_t represents the FIPS140-2 mode of operation.  It can be attached to the current execution thread with gnutls_fips140_push_context and its internal state will be updated until it is detached with gnutls_fips140_pop_context.  Afterwards gnutls_fips140_get_operation_state allows the user to examine whether any approved (or non-approved) security function is invoked.

gnutls_fips140_get_operation_state