summaryrefslogtreecommitdiff
path: root/doc/cha-internals.texi
blob: 6a04ac221d996a4fd6e1a2954cfc667fa6fd730e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
@node Internal architecture of GnuTLS
@chapter Internal Architecture of GnuTLS
@cindex internal architecture

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::
@end menu

@node The TLS Protocol
@section The TLS Protocol
The main use case for the TLS protocol is shown in @ref{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.

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

@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
transport layer functions are used. The main idea is shown in @ref{fig-gnutls-handshake}.

@float Figure,fig-gnutls-handshake
@image{gnutls-handshake-state,9cm}
@caption{GnuTLS handshake state machine.}
@end float

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

@float Figure,fig-gnutls-handshake-sequence
@image{gnutls-handshake-sequence,12cm}
@caption{GnuTLS handshake process sequence.}
@end float

@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
authentication method needs to implement the functions shown below.

@verbatim
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;
@end verbatim

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


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

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

@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

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
@code{ext/@-srp.c} in GnuTLS' source code. After implementing these functions, 
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}.

@subheading Adding a new TLS extension

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
@code{foobar}.

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

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
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

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

@subsubheading Add IANA extension value to @code{extensions_t} in @code{gnutls_int.h}.

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.

@subsubheading Add an entry to @code{_gnutls_extensions} in @code{gnutls_extensions.c}.

A typical entry would be:

@example
  int ret;

#if ENABLE_FOOBAR
  ret = _gnutls_ext_register (&foobar_ext);
  if (ret != GNUTLS_E_SUCCESS)
    return ret;
#endif
@end example

Most likely you'll need to add an @code{#include "ext/@-foobar.h"}, that
will contain something like
like:
@example
  extension_entry_st foobar_ext = @{
    .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
  @}
@end example

The GNUTLS_EXTENSION_FOOBAR is the integer value you added to
@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.

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

@subsubheading Add new files that implement the extension.

The functions you are responsible to add are those mentioned in the
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:

@example
int
_foobar_recv_params (gnutls_session_t session, const opaque * data,
                     size_t data_size)
@{
  return 0;
@}

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

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

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

The @funcintref{_foobar_send_params} function is responsible for
sending extension data (both in the client and server).

If you receive length fields that don't match, return
@code{GNUTLS_E_@-UNEXPECTED_@-PACKET_@-LENGTH}.  If you receive invalid
data, return @code{GNUTLS_E_@-RECEIVED_@-ILLEGAL_@-PARAMETER}.  You can use
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
at @code{ext/@-max_@-record.c} and @code{ext/@-server_@-name.c} extensions.
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.

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

Recall that both the client and server, send and receive
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,
                            gnutls_buffer_st * data)
@{
  if (session->security_parameters.entity == GNUTLS_CLIENT)
    return foobar_send_client (session, data);
  else
    return foobar_send_server (session, data);
@}
@end example

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

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

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

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
that can be added to @code{includes/@-gnutls/@-gnutls.h},
as long as the LGPLv2.1+ applies.
The implementation of the function should lie in the @code{ext/@-foobar.c} file.

To make the API available in the shared library you need to add the
symbol in @code{lib/@-libgnutls.map}, so that the symbol
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.

@subheading Adding a new Supplemental Data Handshake Message

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

First of all, modify your extension @code{foobar} in the way, the that
flags
@code{session->security_parameters.@-do_send_supplemental}
and
@code{session->security_parameters.@-do_recv_supplemental}
are set:

@example
int
_gnutls_foobar_recv_params (gnutls_session_t session, const opaque * data,
                                 size_t _data_size)
@{
   ...
   session->security_parameters.do_recv_supplemental=1;
   ...
@}

int
_gnutls_foobar_send_params (gnutls_session_t session, gnutls_buffer_st *extdata)
@{
   ...
   session->security_parameters.do_send_supplemental=1;
   ...
@}
@end example

Furthermore add the functions @funcintref{_foobar_supp_recv_params}
and @funcintref{_foobar_supp_send_params} to @code{_foobar.h} and
@code{_foobar.c}. The following example code shows how to send a
``Hello World'' string in the supplemental data handshake message:

@example
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_st *buf)
@{
   unsigned char *msg = "hello world";
   int len = strlen(msg);

   _gnutls_buffer_append_data_prefix(buf, 8, msg, len);

   return len;
@}
@end example

Afterwards, add the new supplemental data handshake message to
@code{lib/gnutls_supplemental.c} by adding a new entry to the
@code{_gnutls_supplemental[]} structure:

@example
gnutls_supplemental_entry _gnutls_supplemental[] = 
@{
  @{"foobar",
   GNUTLS_SUPPLEMENTAL_FOOBAR_DATA,
   _foobar_supp_recv_params,
   _foobar_supp_send_params@},
  @{0, 0, 0, 0@}
@};
@end example

You have to include your @code{foobar.h} header file as well:

@example
#include "foobar.h"
@end example

Lastly, add the new supplemental data type to
@code{lib/includes/gnutls/gnutls.h}:

@example
typedef enum
@{
    GNUTLS_SUPPLEMENTAL_USER_MAPPING_DATA = 0,
    GNUTLS_SUPPLEMENTAL_FOOBAR_DATA = 1
@} gnutls_supplemental_data_format_type_t;
@end example

@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

@node Cryptographic Backend
@section 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. Unfortunately the cryptographic library that GnuTLS is based 
on takes no advantage of these capabilities. For this reason GnuTLS handles 
this internally by following a layered approach to accessing
cryptographic operations as in @ref{fig-crypto-layers}.

@float Figure,fig-crypto-layers
@image{gnutls-crypto-layers,12cm}
@caption{GnuTLS cryptographic back-end design.}
@end float

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 @code{/dev/crypto} or CPU-optimized cryptography in
an efficient way.

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

@subheading 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@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 
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 @acronym{GnuTLS}
source code in @code{lib/accelerated/}.

@subsubheading Overriding specific algorithms
When an optimized implementation of a single algorithm is available,
say a hardware assisted version of @acronym{AES-CBC} then the
following (internal) functions, from @code{crypto-backend.h}, can 
be used to register those algorithms.

@itemize

@item @code{gnutls_crypto_single_cipher_register}:
To register a cipher algorithm.

@item @code{gnutls_crypto_single_digest_register}:
To register a hash (digest) or MAC algorithm.

@end itemize

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

@subsubheading Overriding the cryptographic library
In some systems, that might contain a broad acceleration engine, it 
might be desirable to override big parts of the cryptographic back-end, 
or even all of them. The following functions are provided for this reason.

@itemize

@item @code{gnutls_crypto_cipher_register}:
To override the cryptographic algorithms back-end.

@item @code{gnutls_crypto_digest_register}:
To override the digest algorithms back-end.

@item @code{gnutls_crypto_rnd_register}:
To override the random number generator back-end.

@item @code{gnutls_crypto_bigint_register}:
To override the big number number operations back-end.

@item @code{gnutls_crypto_pk_register}:
To override the public key encryption back-end. This is tied to the
big number operations so either none or both of them should be overridden.

@end itemize