cha-internals.texi 28.3 KB
Newer Older
1 2
@node Internal architecture of GnuTLS
@chapter Internal Architecture of GnuTLS
3
@cindex internal architecture
4 5 6 7 8 9 10 11 12 13 14 15

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

@menu
* The TLS Protocol::
* TLS Handshake Protocol::
* TLS Authentication Methods::
* TLS Extension Handling::
* Cryptographic Backend::
16
* Random Number Generators-internals::
17
* FIPS140-2 mode::
18 19 20 21
@end menu

@node The TLS Protocol
@section The TLS Protocol
22
The main use case for the TLS protocol is shown in @ref{fig-client-server}.
23 24 25 26
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.

27
@float Figure,fig-client-server
28 29 30 31
@image{gnutls-client-server-use-case,9cm}
@caption{TLS protocol use case.}
@end float

32 33 34 35
@node TLS Handshake Protocol
@section TLS Handshake Protocol
The @acronym{GnuTLS} handshake protocol is implemented as a state
machine that waits for input or returns immediately when the non-blocking
36
transport layer functions are used. The main idea is shown in @ref{fig-gnutls-handshake}.
37

38
@float Figure,fig-gnutls-handshake
39 40 41
@image{gnutls-handshake-state,9cm}
@caption{GnuTLS handshake state machine.}
@end float
42 43 44

Also the way the input is processed varies per ciphersuite. Several 
implementations of the internal handlers are available and 
45
@funcref{gnutls_handshake} only multiplexes the input to the appropriate 
46 47
handler. For example a @acronym{PSK} ciphersuite has a different 
implementation of the @code{process_client_key_exchange} than a
48
certificate ciphersuite. We illustrate the idea in @ref{fig-gnutls-handshake-sequence}.
49

50
@float Figure,fig-gnutls-handshake-sequence
51 52 53
@image{gnutls-handshake-sequence,12cm}
@caption{GnuTLS handshake process sequence.}
@end float
54 55 56 57 58 59

@node TLS Authentication Methods
@section TLS Authentication Methods
In @acronym{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
60 61 62 63 64
authentication method needs to implement the functions shown below.

@verbatim
typedef struct 
{
Nikos Mavrogiannopoulos committed
65
  const char *name;
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  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;
@end verbatim

Those functions are responsible for the
interpretation of the handshake protocol messages. It is common for such
88 89 90 91 92
functions to read data from one or more @code{credentials_t}
structures@footnote{such as the
@code{gnutls_certificate_credentials_t} structures} and write data,
such as certificates, usernames etc. to @code{auth_info_t} structures.

93

94
Simple examples of existing authentication methods can be seen in
95
@code{auth/@-psk.c} for PSK ciphersuites and @code{auth/@-srp.c} for SRP
96
ciphersuites. After implementing these functions the structure holding
97 98
its pointers has to be registered in @code{gnutls_@-algorithms.c} in the
@code{_gnutls_@-kx_@-algorithms} structure.
99 100 101 102

@node TLS Extension Handling
@section TLS Extension Handling
As with authentication methods, the TLS extensions handlers can be
103
implemented using the interface shown below.
104

105 106 107 108 109 110
@verbatim
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);
@end verbatim
111 112 113 114 115 116

Here there are two functions, one for receiving the extension data
and one for sending. These functions have to check internally whether
they operate in client or server side. 

A simple example of an extension handler can be seen in
117
@code{ext/@-srp.c} in GnuTLS' source code. After implementing these functions, 
118 119 120
together with the extension number they handle, they have to be registered 
using @funcintref{_gnutls_ext_register} in
@code{gnutls_extensions.c} typically within @funcintref{_gnutls_ext_init}.
121

122
@subheading Adding a new TLS extension
123 124 125 126 127

Adding support for a new TLS 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 sake of discussion, let's
consider adding support for the hypothetical TLS extension
128
@code{foobar}. The following section is about adding an extension to GnuTLS,
129 130
for custom application extensions you should check the exported functions
@funcref{gnutls_session_ext_register} or @funcref{gnutls_ext_register}.
131

132
@subsubheading Add @code{configure} option like @code{--enable-foobar} or @code{--disable-foobar}.
133

134 135 136 137 138
This step is useful when the extension code is large and it might be desirable
to disable the extension under some circumstances. Otherwise it can be safely
skipped.

Whether to chose enable or disable depends on whether you intend to make the extension be
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
enabled by default.  Look at existing checks (i.e., SRP, authz) for
how to model the code.  For example:

@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")
@end example

158
These lines should go in @code{m4/hooks.m4}.
159

160
@subsubheading Add IANA extension value to @code{extensions_t} in @code{gnutls_int.h}.
161 162 163 164 165 166 167 168 169

A good name for the value would be GNUTLS_EXTENSION_FOOBAR.  Check
with @url{http://www.iana.org/assignments/tls-extensiontype-values}
for allocated values.  For experiments, you could pick a number but
remember that some consider it a bad idea to deploy such modified
version since it will lead to interoperability problems in the future
when the IANA allocates that number to someone else, or when the
foobar protocol is allocated another number.

170
@subsubheading Add an entry to @code{_gnutls_extensions} in @code{gnutls_extensions.c}.
171 172 173 174 175 176 177

A typical entry would be:

@example
  int ret;

#if ENABLE_FOOBAR
178
  ret = _gnutls_ext_register (&foobar_ext);
179 180 181 182 183
  if (ret != GNUTLS_E_SUCCESS)
    return ret;
#endif
@end example

184
Most likely you'll need to add an @code{#include "ext/@-foobar.h"}, that
185 186 187
will contain something like
like:
@example
Nikos Mavrogiannopoulos committed
188
  extension_entry_st foobar_ext = @{
189 190 191 192 193 194 195 196
    .name = "FOOBAR",
    .type = GNUTLS_EXTENSION_FOOBAR,
    .parse_type = GNUTLS_EXT_TLS,
    .recv_func = _foobar_recv_params,
    .send_func = _foobar_send_params,
    .pack_func = _foobar_pack,
    .unpack_func = _foobar_unpack,
    .deinit_func = NULL
Nikos Mavrogiannopoulos committed
197
  @}
198 199
@end example

200
The GNUTLS_EXTENSION_FOOBAR is the integer value you added to
201 202 203 204 205
@code{gnutls_int.h} earlier.  In this structure you specify the
functions to read the extension from the hello message, the function
to send the reply to, and two more functions to pack and unpack from
stored session data (e.g. when resumming a session). The @code{deinit} function
will be called to deinitialize the extension's private parameters, if any.
206

207 208 209
Note that the conditional @code{ENABLE_FOOBAR} definition should only be 
used if step 1 with the @code{configure} options has taken place.

210
@subsubheading Add new files that implement the extension.
211 212

The functions you are responsible to add are those mentioned in the
213 214 215
previous step.  They should be added in a file such as @code{ext/@-foobar.c} 
and headers should be placed in @code{ext/@-foobar.h}.
As a starter, you could add this:
216 217 218

@example
int
219 220
_foobar_recv_params (gnutls_session_t session, const opaque * data,
                     size_t data_size)
221 222 223 224 225
@{
  return 0;
@}

int
226
_foobar_send_params (gnutls_session_t session, gnutls_buffer_st* data)
227 228 229
@{
  return 0;
@}
230 231 232 233 234 235 236 237 238 239 240 241 242 243

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

int
_foobar_unpack (gnutls_buffer_st * ps, extension_priv_data_t * epriv)
@{
   /* Read the internal state from buffer */
   return 0;
@}
244 245
@end example

246
The @funcintref{_foobar_recv_params} function is responsible for
247 248
parsing incoming extension data (both in the client and server).

249
The @funcintref{_foobar_send_params} function is responsible for
250 251 252 253 254 255 256
sending extension data (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
@code{GNUTLS_E_INT_RET_0}.
257

258
If you receive length fields that don't match, return
259 260
@code{GNUTLS_E_@-UNEXPECTED_@-PACKET_@-LENGTH}.  If you receive invalid
data, return @code{GNUTLS_E_@-RECEIVED_@-ILLEGAL_@-PARAMETER}.  You can use
261 262 263 264 265 266
other error codes from the list in @ref{Error codes}.  Return 0 on success.

An extension typically stores private information in the @code{session}
data for later usage. That can be done using the functions 
@funcintref{_gnutls_ext_set_session_data} and
@funcintref{_gnutls_ext_get_session_data}. You can check simple examples
267
at @code{ext/@-max_@-record.c} and @code{ext/@-server_@-name.c} extensions.
268 269 270 271 272
That private information can be saved and restored across session 
resumption if the following functions are set:

The @funcintref{_foobar_pack} function is responsible for packing
internal extension data to save them in the session resumption storage.
273

274 275
The @funcintref{_foobar_unpack} function is responsible for
restoring session data from the session resumption storage.
276

277
Recall that both the client and server, send and receive
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
parameters, and your code most likely will need to do different things
depending on which mode it is in.  It may be useful to make this
distinction explicit in the code.  Thus, for example, a better
template than above would be:

@example
int
_gnutls_foobar_recv_params (gnutls_session_t session,
                            const opaque * 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,
297
                            gnutls_buffer_st * data)
298 299
@{
  if (session->security_parameters.entity == GNUTLS_CLIENT)
300
    return foobar_send_client (session, data);
301
  else
302
    return foobar_send_server (session, data);
303 304 305 306 307
@}
@end example

The functions used would be declared as @code{static} functions, of
the appropriate prototype, in the same file.
308
When adding the files, you'll need to add them to @code{ext/@-Makefile.am}
309 310 311 312
as well, for example:

@example
if ENABLE_FOOBAR
313
libgnutls_ext_la_SOURCES += ext/foobar.c ext/foobar.h
314 315 316
endif
@end example

317
@subsubheading Add API functions to enable/disable the extension.
318

319 320 321
It might be desirable to allow users of the extension to
request use of the extension, or set extension specific data.  
This can be implemented by adding extension specific function calls
322
that can be added to @code{includes/@-gnutls/@-gnutls.h},
Nikos Mavrogiannopoulos committed
323
as long as the LGPLv2.1+ applies.
324
The implementation of the function should lie in the @code{ext/@-foobar.c} file.
325 326

To make the API available in the shared library you need to add the
327
symbol in @code{lib/@-libgnutls.map}, so that the symbol
328 329 330 331 332 333
is exported properly.

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

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
@subsubheading Heartbeat extension.

One such extension is HeartBeat protocol (RFC6520:
@url{https://tools.ietf.org/html/rfc6520}) implementation. To enable
it use option --heartbeat with example client and server supplied with
gnutls:

@example
./doc/credentials/gnutls-http-serv --priority "NORMAL:-CIPHER-ALL:+NULL" -d 100 \
    --heartbeat --echo
./src/gnutls-cli --priority "NORMAL:-CIPHER-ALL:+NULL" -d 100 localhost -p 5556 \
    --insecure --heartbeat
@end example

After that pasting
@example
**HEARTBEAT**
@end example
command into gnutls-cli will trigger corresponding command on the server and it will send HeartBeat Request with random length to client.

Another way is to run capabilities check with:

@example
./doc/credentials/gnutls-http-serv -d 100 --heartbeat
./src/gnutls-cli-debug localhost -p 5556
@end example

Carolin Latze committed
361 362 363
@subheading Adding a new Supplemental Data Handshake Message

TLS handshake extensions allow to send so called supplemental data
364 365
handshake messages @xcite{RFC4680}. This short section explains how to 
implement a supplemental data handshake message for a given TLS extension.
Carolin Latze committed
366

367 368
First of all, modify your extension @code{foobar} in the way, to instruct
the handshake process to send and receive supplemental data, as shown below.
Carolin Latze committed
369 370 371 372 373 374 375

@example
int
_gnutls_foobar_recv_params (gnutls_session_t session, const opaque * data,
                                 size_t _data_size)
@{
   ...
376
   gnutls_supplemental_recv(session, 1);
Carolin Latze committed
377 378 379 380 381 382 383
   ...
@}

int
_gnutls_foobar_send_params (gnutls_session_t session, gnutls_buffer_st *extdata)
@{
   ...
384
   gnutls_supplemental_send(session, 1);
Carolin Latze committed
385 386 387 388
   ...
@}
@end example

389 390 391 392 393 394 395 396 397 398 399 400 401 402
Furthermore you'll need two new functions @funcintref{_foobar_supp_recv_params}
and @funcintref{_foobar_supp_send_params}, which must conform to the following 
prototypes.

@example
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);
@end example

The following example code shows how to send a
``Hello World'' string in the supplemental data handshake message.
Carolin Latze committed
403 404 405

@example
int 
406
_foobar_supp_recv_params(gnutls_session_t session, const opaque *data, size_t _data_size)
Carolin Latze committed
407
@{
408
   uint8_t len = _data_size;
Carolin Latze committed
409 410
   unsigned char *msg;

411 412 413 414
   msg = gnutls_malloc(len);
   if (msg == NULL) return GNUTLS_E_MEMORY_ERROR;

   memcpy(msg, data, len);
Carolin Latze committed
415 416
   msg[len]='\0';

417 418 419
   /* do something with msg */
   gnutls_free(msg);

Carolin Latze committed
420 421 422 423
   return len;
@}

int 
424
_foobar_supp_send_params(gnutls_session_t session, gnutls_buffer_t buf)
Carolin Latze committed
425 426 427 428
@{
   unsigned char *msg = "hello world";
   int len = strlen(msg);

429 430
   if (gnutls_buffer_append_data(buf, msg, len) < 0)
       abort();
Carolin Latze committed
431 432 433 434 435

   return len;
@}
@end example

436 437
Afterwards, register the new supplemental data using @funcref{gnutls_session_supplemental_register},
or @funcref{gnutls_supplemental_register} at some point in your program.
438

439 440
@node Cryptographic Backend
@section Cryptographic Backend
441

442 443 444 445
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 
Nikos Mavrogiannopoulos committed
446 447
library. GnuTLS handles the cryptographic provider in a modular
way, following a layered approach to access
448
cryptographic operations as in @ref{fig-crypto-layers}.
449

450
@float Figure,fig-crypto-layers
451 452 453
@image{gnutls-crypto-layers,12cm}
@caption{GnuTLS cryptographic back-end design.}
@end float
454 455

The TLS layer uses a cryptographic provider layer, that will in turn either 
456
use the default crypto provider -- a software crypto library, or use an external
457 458 459 460 461
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 @code{/dev/crypto} or CPU-optimized cryptography in
an efficient way.
462

463
@subheading Cryptographic library layer
464
The Cryptographic library layer, currently supports only
465 466 467 468 469
libnettle. Older versions of GnuTLS used to support libgcrypt,
but it was switched with nettle mainly for performance reasons@footnote{See
@url{http://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.
470

471
@subheading External cryptography provider
472 473 474
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
475
by another implementation, i.e., the one provided by the driver. The
476 477 478 479 480 481 482
FreeBSD, OpenBSD and Linux kernels@footnote{Check @url{http://home.gna.org/cryptodev-linux/} 
for the Linux kernel implementation of @code{/dev/crypto}.} include already 
a number of hardware assisted implementations, and also provide an interface 
to access them, called @code{/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 
483
actually harm performance.
484

485 486 487
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
Nikos Mavrogiannopoulos committed
488 489
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
Nikos Mavrogiannopoulos committed
490
overrides parts of crypto back-end at runtime.
Nikos Mavrogiannopoulos committed
491 492 493 494
The next section discusses the registration of a detected algorithm
optimization. For more information please consult the @acronym{GnuTLS}
source code in @code{lib/accelerated/}.

495
@subsubheading Overriding specific algorithms
496 497
When an optimized implementation of a single algorithm is available,
say a hardware assisted version of @acronym{AES-CBC} then the
498
following functions, from @code{crypto.h}, can 
499
be used to register those algorithms.
500 501 502

@itemize

503
@item @funcref{gnutls_crypto_register_cipher}:
504 505
To register a cipher algorithm.

506 507 508 509 510 511 512 513
@item @funcref{gnutls_crypto_register_aead_cipher}:
To register an AEAD cipher algorithm.

@item @funcref{gnutls_crypto_register_mac}:
To register a MAC algorithm.

@item @funcref{gnutls_crypto_register_digest}:
To register a hash algorithm.
514 515 516 517 518 519 520

@end itemize

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


521 522 523 524 525 526
@subheading 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 @ref{Hardware security modules and abstract key types}.

527 528 529 530

@node Random Number Generators-internals
@section Random Number Generators

531 532 533 534 535 536 537
@subheading 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.

@subheading The default generator - inner workings
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553

The random number generator levels in @code{gnutls_rnd_level_t} map to two CHACHA-based random generators which
are initially seeded using the OS random device, e.g., @code{/dev/urandom}
or @code{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 @funcref{gnutls_rnd}. At the same time
554 555 556
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.
557 558 559 560

On the first call to @funcref{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.
561 562 563 564 565 566 567

One generator is dedicated for the @code{GNUTLS_RND_NONCE} level, and the
second is shared for the @code{GNUTLS_RND_KEY} and @code{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 outputing a fixed amount of bytes
568 569 570 571
(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.
572

573 574
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
575 576 577 578 579 580
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 @code{GNUTLS_RND_RANDOM}
and @code{GNUTLS_RND_KEY} levels is identical, when used with the @code{GNUTLS_RND_KEY} level
581 582
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.
583 584


585 586 587 588 589 590 591 592 593 594 595
@subheading The AES-DRBG generator - inner workings

Similar with the default generator, the random number generator levels in @code{gnutls_rnd_level_t} map to two
AES-DRBG random generators which are initially seeded using the OS random device,
e.g., @code{/dev/urandom} or @code{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.


596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
@subheading 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 @xcite{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.

@subsubheading 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.

@subsubheading 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 @code{/dev/urandom} or
@code{getentropy}/@code{getrandom} system calls. As such, GnuTLS' PRNG
is as strong as the system random generator can assure with regards to
input-based attacks.

@subsubheading 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 @code{GNUTLS_RND_RANDOM} and @code{GNUTLS_RND_KEY},
since @code{GNUTLS_RND_NONCE} is intended to output non-secret data.
The @code{GNUTLS_RND_RANDOM} generator at the time of writing can output
629
2MB prior to being re-seeded thus this is its upper bound for previously
630
generated data recovered using this attack. That assumes that the state
631
of the operating system random generator is unknown to the attacker, and we carry that
632 633 634 635 636 637 638 639 640 641 642 643 644
assumption on the next paragraphs. The usage of @code{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.

@subsubheading 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 @code{GNUTLS_RND_RANDOM}
645
and the @code{GNUTLS_RND_KEY} will recover after 2MB of data have been generated
646 647 648
or few hours have passed (two at the time of writing). Similarly the @code{GNUTLS_RND_NONCE}
level generator will recover after several megabytes of output is generated,
or its re-key time is reached.
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664

@subsubheading 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.

@subsubheading 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.

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
@node FIPS140-2 mode
@section 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. The operation of the library is then modified, as follows.

@itemize
@item FIPS140-2 mode is enabled when @code{/proc/sys/crypto/fips_enabled} contains '1' and @code{/etc/system-fips} is present.
@item Only approved by FIPS140-2 algorithms are enabled
@item Only approved by FIPS140-2 key lengths are allowed for key generation
@item The random generator used switches to DRBG-AES
@item The integrity of the GnuTLS and dependent libraries is checked on startup
@item Algorithm self-tests are run on library load
@item Any cryptographic operation will be refused if any of the self-tests failed
@end itemize

There is a 'zombie' FIPS140-2 mode which is enabled when only one of the files
described in the first step is available. In that case the self tests will
be performed without affecting the operation of the library.

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.

There are also few environment variables which modify that operation. The
environment variable @code{GNUTLS_SKIP_FIPS_INTEGRITY_CHECKS} will disable
the library integrity tests on startup, and the variable
@code{GNUTLS_FORCE_FIPS_MODE} when set to '1' will enable the FIPS140-2
mode, when set to '0' will force a disable of it.

On runtime an application can verify whether the library is in FIPS140-2
using the @funcref{gnutls_fips140_mode_enabled} function.