1 \input texinfo @c -*-texinfo-*-
2 @comment %**start of header
3 @setfilename gnutls.info
5 @settitle GNU TLS @value{VERSION}
7 @c don't indent the paragraphs.
10 @c Unify some of the indices.
14 @comment %**end of header
17 This manual is last updated @value{UPDATED} for version
18 @value{VERSION} of GNU TLS.
20 Copyright @copyright{} 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
23 Permission is granted to copy, distribute and/or modify this document
24 under the terms of the GNU Free Documentation License, Version 1.3 or
25 any later version published by the Free Software Foundation; with no
26 Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A
27 copy of the license is included in the section entitled ``GNU Free
28 Documentation License''.
32 @dircategory Software libraries
34 * GnuTLS: (gnutls). GNU Transport Layer Security Library.
37 @dircategory System Administration
39 * certtool: (gnutls)Invoking certtool. Manipulate certificates and keys.
40 * gnutls-serv: (gnutls)Invoking gnutls-serv. GNU TLS test server.
41 * gnutls-cli: (gnutls)Invoking gnutls-cli. GNU TLS test client.
42 * gnutls-cli-debug: (gnutls)Invoking gnutls-cli-debug. GNU TLS debug client.
43 * psktool: (gnutls)Invoking psktool. Simple TLS-Pre-Shared-Keys manager.
44 * srptool: (gnutls)Invoking srptool. Simple SRP password tool.
49 @subtitle Transport Layer Security Library for the GNU system
50 @subtitle for version @value{VERSION}, @value{UPDATED}
52 @image{gnutls-logo,6cm,6cm}
53 @author Nikos Mavrogiannopoulos
54 @author Simon Josefsson (@email{bug-gnutls@@gnu.org})
56 @vskip 0pt plus 1filll
61 [\ref\] (@pxref{Bibliography})
76 * Introduction to TLS::
77 * Authentication methods::
78 * More on certificate authentication::
79 * How to use TLS in application protocols::
80 * How to use GnuTLS in applications::
82 * Function reference::
83 * All the supported ciphersuites in GnuTLS::
85 * Internal architecture of GnuTLS::
86 * Copying Information::
88 * Function and Data Index::
97 This document tries to demonstrate and explain the @acronym{GnuTLS}
98 library API. A brief introduction to the protocols and the technology
99 involved, is also included so that an application programmer can
100 better understand the @acronym{GnuTLS} purpose and actual offerings.
101 Even if @acronym{GnuTLS} is a typical library software, it operates
102 over several security and cryptographic protocols, which require the
103 programmer to make careful and correct usage of them, otherwise he
104 risks to offer just a false sense of security. Security and the
105 network security terms are very general terms even for computer
106 software thus cannot be easily restricted to a single cryptographic
107 library. For that reason, do not consider a program secure just
108 because it uses @acronym{GnuTLS}; there are several ways to compromise
109 a program or a communication line and @acronym{GnuTLS} only helps with
112 Although this document tries to be self contained, basic network
113 programming and PKI knowlegde is assumed in most of it. A good
114 introduction to networking can be found in @xcite{STEVENS} and for
115 Public Key Infrastructure in @xcite{GUTPKI}.
117 @anchor{Availability}
119 Updated versions of the @acronym{GnuTLS} software and this document
120 will be available from @url{http://www.gnutls.org/} and
121 @url{http://www.gnu.org/software/gnutls/}.
125 * Commercial Support::
126 * Downloading and Installing::
132 @section Getting Help
134 A mailing list where users may help each other exists, and you can
135 reach it by sending e-mail to @email{help-gnutls@@gnu.org}. Archives
136 of the mailing list discussions, and an interface to manage
137 subscriptions, is available through the World Wide Web at
138 @url{http://lists.gnu.org/mailman/listinfo/help-gnutls}.
140 A mailing list for developers are also available, see
141 @url{http://www.gnu.org/software/gnutls/lists.html}.
143 Bug reports should be sent to @email{bug-gnutls@@gnu.org}, see
146 @node Commercial Support
147 @section Commercial Support
149 Commercial support is available for users of GnuTLS. The kind of
150 support that can be purchased may include:
154 @item Implement new features.
155 Such as a new TLS extension.
157 @item Port GnuTLS to new platforms.
158 This could include porting to an embedded platforms that may need
159 memory or size optimization.
161 @item Integrating TLS as a security environment in your existing project.
163 @item System design of components related to TLS.
167 If you are interested, please write to:
170 Simon Josefsson Datakonsult
175 E-mail: simon@josefsson.org
178 If your company provides support related to GnuTLS and would like to
179 be mentioned here, contact the author (@pxref{Bug Reports}).
181 @node Downloading and Installing
182 @section Downloading and Installing
186 GnuTLS is available for download from the following URL:
188 @url{http://www.gnutls.org/download.html}
190 The latest version is stored in a file, e.g.,
191 @samp{gnutls-@value{VERSION}.tar.gz} where the @samp{@value{VERSION}}
192 value is the highest version number in the directory.
194 GnuTLS uses a Linux-like development cycle: even minor version numbers
195 indicate a stable release and a odd minor version number indicates a
196 development release. For example, GnuTLS 1.6.3 denote a stable
197 release since 6 is even, and GnuTLS 1.7.11 denote a development
198 release since 7 is odd.
200 GnuTLS depends on Libgcrypt,
201 and you will need to install Libgcrypt
202 before installing GnuTLS. Libgcrypt is available from
203 @url{ftp://ftp.gnupg.org/gcrypt/libgcrypt}. Libgcrypt needs another
204 library, libgpg-error, and you need to install libgpg-error before
205 installing Libgcrypt. Libgpg-error is available from
206 @url{ftp://ftp.gnupg.org/gcrypt/libgpg-error}.
208 Don't forget to verify the cryptographic signature after downloading
209 source code packages.
211 The package is then extracted, configured and built like many other
212 packages that use Autoconf. For detailed information on configuring
213 and building it, refer to the @file{INSTALL} file that is part of the
214 distribution archive. Typically you invoke @code{./configure} and
215 then @code{make check install}. There are a number of compile-time
216 parameters, as discussed below.
218 The compression libraries (libz and lzo) are optional dependencies.
219 You can get libz from @url{http://www.zlib.net/}. You can get lzo
220 from @url{http://www.oberhumer.com/opensource/lzo/}.
222 The X.509 part of GnuTLS needs ASN.1 functionality, from a library
223 called libtasn1. A copy of libtasn1 is included in GnuTLS. If you
224 want to install it separately (e.g., to make it possibly to use
225 libtasn1 in other programs), you can get it from
226 @url{http://www.gnu.org/software/gnutls/download.html}.
228 The OpenPGP part of GnuTLS uses a stripped down version of OpenCDK for
229 parsing OpenPGP packets. It is included GnuTLS. Use parameter
230 @code{--disable-openpgp-authentication} to disable the OpenPGP
231 functionality in GnuTLS. Unfortunately, we didn't have resources to
232 maintain the code in a separate library.
234 Regarding the Guile bindings, there are additional installation
235 considerations, see @xref{Guile Preparations}.
237 A few @code{configure} options may be relevant, summarized in the
242 @item --disable-srp-authentication
243 @itemx --disable-psk-authentication
244 @itemx --disable-anon-authentication
245 @itemx --disable-extra-pki
246 @itemx --disable-openpgp-authentication
247 @itemx --disable-openssl-compatibility
248 Disable or enable particular features. Generally not recommended.
252 For the complete list, refer to the output from @code{configure
257 @cindex Reporting Bugs
259 If you think you have found a bug in GnuTLS, please investigate it and
264 @item Please make sure that the bug is really in GnuTLS, and
265 preferably also check that it hasn't already been fixed in the latest
268 @item You have to send us a test case that makes it possible for us to
271 @item You also have to explain what is wrong; if you get a crash, or
272 if the results printed are not good and in that case, in what way.
273 Make sure that the bug report includes all information you would need
274 to fix this kind of bug for someone else.
278 Please make an effort to produce a self-contained report, with
279 something definite that can be tested or debugged. Vague queries or
280 piecemeal messages are difficult to act on and don't help the
283 If your bug report is good, we will do our best to help you to get a
284 corrected version of the software; if the bug report is poor, we won't
285 do anything about it (apart from asking you to send better bug
288 If you think something in this manual is unclear, or downright
289 incorrect, or if the language needs to be improved, please also send a
292 Send your bug report to:
294 @center @samp{bug-gnutls@@gnu.org}
297 @section Contributing
301 If you want to submit a patch for inclusion -- from solve a typo you
302 discovered, up to adding support for a new feature -- you should
303 submit it as a bug report (@pxref{Bug Reports}). There are some
304 things that you can do to increase the chances for it to be included
305 in the official package.
307 Unless your patch is very small (say, under 10 lines) we require that
308 you assign the copyright of your work to the Free Software Foundation.
309 This is to protect the freedom of the project. If you have not
310 already signed papers, we will send you the necessary information when
311 you submit your contribution.
313 For contributions that doesn't consist of actual programming code, the
314 only guidelines are common sense. Use it.
316 For code contributions, a number of style guides will help you:
321 Follow the GNU Standards document (@pxref{top, GNU Coding Standards,,
324 If you normally code using another coding standard, there is no
325 problem, but you should use @samp{indent} to reformat the code
326 (@pxref{top, GNU Indent,, indent}) before submitting your work.
328 @item Use the unified diff format @samp{diff -u}.
331 No reason whatsoever should abort the execution of the library. Even
332 memory allocation errors, e.g. when malloc return NULL, should work
333 although result in an error code.
335 @item Design with thread safety in mind.
336 Don't use global variables. Don't even write to per-handle global
337 variables unless the documented behaviour of the function you write is
338 to write to the per-handle global variable.
340 @item Avoid using the C math library.
341 It causes problems for embedded implementations, and in most
342 situations it is very easy to avoid using it.
344 @item Document your functions.
345 Use comments before each function headers, that, if properly
346 formatted, are extracted into Texinfo manuals and GTK-DOC web pages.
348 @item Supply a ChangeLog and NEWS entries, where appropriate.
354 In brief @acronym{GnuTLS} can be described as a library which offers an API
355 to access secure communication protocols. These protocols provide
356 privacy over insecure lines, and were designed to prevent
357 eavesdropping, tampering, or message forgery.
359 Technically @acronym{GnuTLS} is a portable ANSI C based library which
360 implements the TLS 1.1 and SSL 3.0 protocols (@xref{Introduction to
361 TLS}, for a more detailed description of the protocols), accompanied
362 with the required framework for authentication and public key
363 infrastructure. Important features of the @acronym{GnuTLS} library
368 @item Support for TLS 1.0, TLS 1.1, and SSL 3.0 protocols.
370 @item Support for both @acronym{X.509} and @acronym{OpenPGP} certificates.
372 @item Support for handling and verification of certificates.
374 @item Support for @acronym{SRP} for TLS authentication.
376 @item Support for @acronym{PSK} for TLS authentication.
378 @item Support for TLS Extension mechanism.
380 @item Support for TLS Compression Methods.
384 Additionally @acronym{GnuTLS} provides a limited emulation API for the
385 widely used OpenSSL@footnote{@url{http://www.openssl.org/}} library,
386 to ease integration with existing applications.
388 @acronym{GnuTLS} consists of three independent parts, namely the ``TLS
389 protocol part'', the ``Certificate part'', and the ``Cryptographic
390 backend'' part. The `TLS protocol part' is the actual protocol
391 implementation, and is entirely implemented within the
392 @acronym{GnuTLS} library. The `Certificate part' consists of the
393 certificate parsing, and verification functions which is partially
394 implemented in the @acronym{GnuTLS} library. The
395 @acronym{Libtasn1}@footnote{@url{ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/libtasn1/}},
396 a library which offers @acronym{ASN.1} parsing capabilities, is used
397 for the @acronym{X.509} certificate parsing functions. A smaller
399 @acronym{OpenCDK}@footnote{@url{ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/opencdk/}}
400 is used for the @acronym{OpenPGP} key support in @acronym{GnuTLS}.
401 The ``Cryptographic backend'' is provided by the
402 @acronym{Libgcrypt}@footnote{@url{ftp://ftp.gnupg.org/gcrypt/alpha/libgcrypt/}}
403 library@footnote{On current versions of GnuTLS it is possible to
404 override the default crypto backend. Check @pxref{Cryptographic
405 Backend} for details}.
407 In order to ease integration in embedded systems, parts of the
408 @acronym{GnuTLS} library can be disabled at compile time. That way a
409 small library, with the required features, can be generated.
415 * Callback functions::
419 @section General Idea
421 A brief description of how @acronym{GnuTLS} works internally is shown
422 at the figure below. This section may be easier to understand after
423 having seen the examples (@pxref{examples}).
425 @image{gnutls-internals,12cm,8cm}
427 As shown in the figure, there is a read-only global state that is
428 initialized once by the global initialization function. This global
429 structure, among others, contains the memory allocation functions
430 used, and some structures needed for the @acronym{ASN.1} parser. This
431 structure is never modified by any @acronym{GnuTLS} function, except
432 for the deinitialization function which frees all memory allocated in
433 the global structure and is called after the program has permanently
434 finished using @acronym{GnuTLS}.
436 The credentials structure is used by some authentication methods, such
437 as certificate authentication (@pxref{Certificate Authentication}). A
438 credentials structure may contain certificates, private keys,
439 temporary parameters for Diffie-Hellman or RSA key exchange, and other
440 stuff that may be shared between several TLS sessions.
442 This structure should be initialized using the appropriate
443 initialization functions. For example an application which uses
444 certificate authentication would probably initialize the credentials,
445 using the appropriate functions, and put its trusted certificates in
446 this structure. The next step is to associate the credentials
447 structure with each @acronym{TLS} session.
449 A @acronym{GnuTLS} session contains all the required stuff for a
450 session to handle one secure connection. This session calls directly
451 to the transport layer functions, in order to communicate with the
452 peer. Every session has a unique session ID shared with the peer.
454 Since TLS sessions can be resumed, servers would probably need a
455 database backend to hold the session's parameters. Every
456 @acronym{GnuTLS} session after a successful handshake calls the
457 appropriate backend function (@xref{resume}, for information on
458 initialization) to store the newly negotiated session. The session
459 database is examined by the server just after having received the
460 client hello@footnote{The first message in a @acronym{TLS} handshake},
461 and if the session ID sent by the client, matches a stored session,
462 the stored session will be retrieved, and the new session will be a
463 resumed one, and will share the same session ID with the previous one.
466 @section Error Handling
468 In @acronym{GnuTLS} most functions return an integer type as a result.
469 In almost all cases a zero or a positive number means success, and a
470 negative number indicates failure, or a situation that some action has
471 to be taken. Thus negative error codes may be fatal or not.
473 Fatal errors terminate the connection immediately and further sends
474 and receives will be disallowed. An example of a fatal error code is
475 @code{GNUTLS_E_DECRYPTION_FAILED}. Non-fatal errors may warn about
476 something, i.e., a warning alert was received, or indicate the some
477 action has to be taken. This is the case with the error code
478 @code{GNUTLS_E_REHANDSHAKE} returned by @ref{gnutls_record_recv}.
479 This error code indicates that the server requests a re-handshake. The
480 client may ignore this request, or may reply with an alert. You can
481 test if an error code is a fatal one by using the
482 @ref{gnutls_error_is_fatal}.
484 If any non fatal errors, that require an action, are to be returned by
485 a function, these error codes will be documented in the function's
486 reference. @xref{Error Codes}, for all the error codes.
488 @node Memory handling
489 @section Memory Handling
491 @acronym{GnuTLS} internally handles heap allocated objects
492 differently, depending on the sensitivity of the data they
493 contain. However for performance reasons, the default memory functions
494 do not overwrite sensitive data from memory, nor protect such objects
495 from being written to the swap. In order to change the default
496 behavior the @ref{gnutls_global_set_mem_functions} function is
497 available which can be used to set other memory handlers than the
500 The @acronym{Libgcrypt} library on which @acronym{GnuTLS} depends, has
501 such secure memory allocation functions available. These should be
502 used in cases where even the system's swap memory is not considered
503 secure. See the documentation of @acronym{Libgcrypt} for more
506 @node Callback functions
507 @section Callback Functions
508 @cindex Callback functions
510 There are several cases where @acronym{GnuTLS} may need some out of
511 band input from your program. This is now implemented using some
512 callback functions, which your program is expected to register.
514 An example of this type of functions are the push and pull callbacks
515 which are used to specify the functions that will retrieve and send
516 data to the transport layer.
520 @item @ref{gnutls_transport_set_push_function}
522 @item @ref{gnutls_transport_set_pull_function}
526 Other callback functions such as the one set by
527 @ref{gnutls_srp_set_server_credentials_function}, may require more
528 complicated input, including data to be allocated. These callbacks
529 should allocate and free memory using the functions shown below.
533 @item @ref{gnutls_malloc}
535 @item @ref{gnutls_free}
539 @node Introduction to TLS
540 @chapter Introduction to @acronym{TLS}
542 @acronym{TLS} stands for ``Transport Layer Security'' and is the
543 successor of SSL, the Secure Sockets Layer protocol @xcite{SSL3}
544 designed by Netscape. @acronym{TLS} is an Internet protocol, defined
545 by @acronym{IETF}@footnote{IETF, or Internet Engineering Task Force,
546 is a large open international community of network designers,
547 operators, vendors, and researchers concerned with the evolution of
548 the Internet architecture and the smooth operation of the Internet.
549 It is open to any interested individual.}, described in @acronym{RFC}
550 4346 and also in @xcite{RESCORLA}. The protocol provides
551 confidentiality, and authentication layers over any reliable transport
552 layer. The description, below, refers to @acronym{TLS} 1.0 but also
553 applies to @acronym{TLS} 1.1 @xcite{RFC4346} and @acronym{SSL} 3.0,
554 since the differences of these protocols are minor. Older protocols
555 such as @acronym{SSL} 2.0 are not discussed nor implemented in
556 @acronym{GnuTLS} since they are not considered secure today. GnuTLS
557 also supports @acronym{X.509} and @acronym{OpenPGP} @xcite{RFC4880}.
561 * The transport layer::
562 * The TLS record protocol::
563 * The TLS Alert Protocol::
564 * The TLS Handshake Protocol::
566 * Selecting cryptographic key sizes::
567 * On SSL 2 and older protocols::
568 * On Record Padding::
575 @acronym{TLS} is a layered protocol, and consists of the Record
576 Protocol, the Handshake Protocol and the Alert Protocol. The Record
577 Protocol is to serve all other protocols and is above the transport
578 layer. The Record protocol offers symmetric encryption, data
579 authenticity, and optionally compression.
581 The Alert protocol offers some signaling to the other protocols. It
582 can help informing the peer for the cause of failures and other error
583 conditions. @xref{The Alert Protocol}, for more information. The
584 alert protocol is above the record protocol.
586 The Handshake protocol is responsible for the security parameters'
587 negotiation, the initial key exchange and authentication. @xref{The
588 Handshake Protocol}, for more information about the handshake
589 protocol. The protocol layering in TLS is shown in the figure below.
591 @image{gnutls-layers,12cm,8cm}
593 @node The transport layer
594 @section The Transport Layer
595 @cindex Transport protocol
597 @acronym{TLS} is not limited to one transport layer, it can be used
598 above any transport layer, as long as it is a reliable one. A set of
599 functions is provided and their purpose is to load to @acronym{GnuTLS} the
600 required callbacks to access the transport layer.
603 @item @ref{gnutls_transport_set_push_function}
604 @item @ref{gnutls_transport_set_pull_function}
605 @item @ref{gnutls_transport_set_ptr}
606 @item @ref{gnutls_transport_set_lowat}
607 @item @ref{gnutls_transport_set_errno}
610 These functions accept a callback function as a parameter. The
611 callback functions should return the number of bytes written, or -1 on
612 error and should set @code{errno} appropriately.
614 In some environments, setting @code{errno} is unreliable, for example
615 Windows have several errno variables in different CRTs, or it may be
616 that errno is not a thread-local variable. If this is a concern to
617 you, call @code{gnutls_transport_set_errno} with the intended errno
618 value instead of setting @code{errno} directly.
620 @acronym{GnuTLS} currently only interprets the EINTR and EAGAIN errno
621 values and returns the corresponding @acronym{GnuTLS} error codes
622 @code{GNUTLS_E_INTERRUPTED} and @code{GNUTLS_E_AGAIN}. These values
623 are usually returned by interrupted system calls, or when non blocking
624 IO is used. All @acronym{GnuTLS} functions can be resumed (called
625 again), if any of these error codes is returned. The error codes
626 above refer to the system call, not the @acronym{GnuTLS} function,
627 since signals do not interrupt @acronym{GnuTLS}' functions.
629 For non blocking sockets or other custom made pull/push functions
630 the @ref{gnutls_transport_set_lowat} must be called, with a zero
631 low water mark value.
633 By default, if the transport functions are not set, @acronym{GnuTLS}
634 will use the Berkeley Sockets functions. In this case
635 @acronym{GnuTLS} will use some hacks in order for @code{select} to
636 work, thus making it easy to add @acronym{TLS} support to existing
639 @node The TLS record protocol
640 @section The TLS Record Protocol
641 @cindex Record protocol
643 The Record protocol is the secure communications provider. Its purpose
644 is to encrypt, authenticate and ---optionally--- compress packets.
645 The following functions are available:
649 @item @ref{gnutls_record_send}:
650 To send a record packet (with application data).
652 @item @ref{gnutls_record_recv}:
653 To receive a record packet (with application data).
655 @item @ref{gnutls_record_get_direction}:
656 To get the direction of the last interrupted function call.
659 As you may have already noticed, the functions which access the Record
660 protocol, are quite limited, given the importance of this protocol in
661 @acronym{TLS}. This is because the Record protocol's parameters are
662 all set by the Handshake protocol.
664 The Record protocol initially starts with NULL parameters, which means
665 no encryption, and no MAC is used. Encryption and authentication begin
666 just after the handshake protocol has finished.
669 * Encryption algorithms used in the record layer::
670 * Compression algorithms used in the record layer::
671 * Weaknesses and countermeasures::
674 @node Encryption algorithms used in the record layer
675 @subsection Encryption Algorithms Used in the Record Layer
676 @cindex Symmetric encryption algorithms
678 Confidentiality in the record layer is achieved by using symmetric
679 block encryption algorithms like @code{3DES}, @code{AES}@footnote{AES,
680 or Advanced Encryption Standard, is actually the RIJNDAEL algorithm.
681 This is the algorithm that replaced DES.}, or stream algorithms like
682 @code{ARCFOUR_128}@footnote{@code{ARCFOUR_128} is a compatible
683 algorithm with RSA's RC4 algorithm, which is considered to be a trade
684 secret.}. Ciphers are encryption algorithms that use a single, secret,
685 key to encrypt and decrypt data. Block algorithms in TLS also provide
686 protection against statistical analysis of the data. Thus, if you're
687 using the @acronym{TLS} protocol, a random number of blocks will be
688 appended to data, to prevent eavesdroppers from guessing the actual
691 Supported cipher algorithms:
695 @code{3DES_CBC} is the DES block cipher algorithm used with triple
696 encryption (EDE). Has 64 bits block size and is used in CBC mode.
699 ARCFOUR is a fast stream cipher.
702 This is the ARCFOUR cipher that is fed with a 40 bit key,
703 which is considered weak.
706 AES or RIJNDAEL is the block cipher algorithm that replaces the old
707 DES algorithm. Has 128 bits block size and is used in CBC mode. This
708 is not officially supported in TLS.
711 Supported MAC algorithms:
715 MD5 is a cryptographic hash algorithm designed by Ron Rivest. Outputs
719 SHA is a cryptographic hash algorithm designed by NSA. Outputs 160
724 @node Compression algorithms used in the record layer
725 @subsection Compression Algorithms Used in the Record Layer
726 @cindex Compression algorithms
728 The TLS record layer also supports compression. The algorithms
729 implemented in @acronym{GnuTLS} can be found in the table below.
730 All the algorithms except for DEFLATE which is
731 referenced in @xcite{RFC3749}, should be considered as
732 @acronym{GnuTLS}' extensions@footnote{You should use
733 @ref{gnutls_handshake_set_private_extensions} to enable private
734 extensions.}, and should be advertised only when the peer is known to
735 have a compliant client, to avoid interoperability problems.
737 The included algorithms perform really good when text, or other
738 compressible data are to be transfered, but offer nothing on already
739 compressed data, such as compressed images, zipped archives etc.
740 These compression algorithms, may be useful in high bandwidth TLS
741 tunnels, and in cases where network usage has to be minimized. As a
742 drawback, compression increases latency.
744 The record layer compression in @acronym{GnuTLS} is implemented based
745 on the proposal @xcite{RFC3749}.
746 The supported compression algorithms are:
750 Zlib compression, using the deflate algorithm.
753 LZO is a very fast compression algorithm. This algorithm is only
754 available if the @acronym{GnuTLS-extra} library has been initialized
755 and the private extensions are enabled, and if GnuTLS was built with
760 @node Weaknesses and countermeasures
761 @subsection Weaknesses and Countermeasures
763 Some weaknesses that may affect the security of the Record layer have
764 been found in @acronym{TLS} 1.0 protocol. These weaknesses can be
765 exploited by active attackers, and exploit the facts that
770 @acronym{TLS} has separate alerts for ``decryption_failed'' and
774 The decryption failure reason can be detected by timing the response
778 The IV for CBC encrypted packets is the last block of the previous
783 Those weaknesses were solved in @acronym{TLS} 1.1 @xcite{RFC4346}
784 which is implemented in @acronym{GnuTLS}. For a detailed discussion
785 see the archives of the TLS Working Group mailing list and the paper
788 @node The TLS Alert Protocol
789 @section The TLS Alert Protocol
790 @anchor{The Alert Protocol}
791 @cindex Alert protocol
793 The Alert protocol is there to allow signals to be sent between peers.
794 These signals are mostly used to inform the peer about the cause of a
795 protocol failure. Some of these signals are used internally by the
796 protocol and the application protocol does not have to cope with them
797 (see @code{GNUTLS_A_CLOSE_NOTIFY}), and others refer to the
798 application protocol solely (see @code{GNUTLS_A_USER_CANCELLED}). An
799 alert signal includes a level indication which may be either fatal or
800 warning. Fatal alerts always terminate the current connection, and
801 prevent future renegotiations using the current session ID.
803 The alert messages are protected by the record protocol, thus the
804 information that is included does not leak. You must take extreme care
805 for the alert information not to leak to a possible attacker, via
806 public log files etc.
809 @item @ref{gnutls_alert_send}:
810 To send an alert signal.
812 @item @ref{gnutls_error_to_alert}:
813 To map a gnutls error number to an alert signal.
815 @item @ref{gnutls_alert_get}:
816 Returns the last received alert.
818 @item @ref{gnutls_alert_get_name}:
819 Returns the name, in a character array, of the given alert.
823 @node The TLS Handshake Protocol
824 @section The TLS Handshake Protocol
825 @anchor{The Handshake Protocol}
826 @cindex Handshake protocol
828 The Handshake protocol is responsible for the ciphersuite negotiation,
829 the initial key exchange, and the authentication of the two peers.
830 This is fully controlled by the application layer, thus your program
831 has to set up the required parameters. Available functions to control
832 the handshake protocol include:
835 @item @ref{gnutls_priority_init}:
836 To initialize a priority set of ciphers.
838 @item @ref{gnutls_priority_deinit}:
839 To deinitialize a priority set of ciphers.
841 @item @ref{gnutls_priority_set}:
842 To associate a priority set with a @acronym{TLS} session.
844 @item @ref{gnutls_priority_set_direct}:
845 To directly associate a session with a given priority string.
847 @item @ref{gnutls_credentials_set}:
848 To set the appropriate credentials structures.
850 @item @ref{gnutls_certificate_server_set_request}:
851 To set whether client certificate is required or not.
853 @item @ref{gnutls_handshake}:
854 To initiate the handshake.
857 @subsection TLS Cipher Suites
859 The Handshake Protocol of @acronym{TLS} negotiates cipher suites of
860 the form @code{TLS_DHE_RSA_WITH_3DES_CBC_SHA}. The usual cipher
861 suites contain these parameters:
865 @item The key exchange algorithm.
866 @code{DHE_RSA} in the example.
868 @item The Symmetric encryption algorithm and mode
869 @code{3DES_CBC} in this example.
871 @item The MAC@footnote{MAC stands for Message Authentication Code. It can be described as a keyed hash algorithm. See RFC2104.} algorithm used for authentication.
872 @code{MAC_SHA} is used in the above example.
876 The cipher suite negotiated in the handshake protocol will affect the
877 Record Protocol, by enabling encryption and data authentication. Note
878 that you should not over rely on @acronym{TLS} to negotiate the
879 strongest available cipher suite. Do not enable ciphers and algorithms
880 that you consider weak.
882 The priority functions, dicussed above, allow the application layer to
883 enable and set priorities on the individual ciphers. It may imply that
884 all combinations of ciphersuites are allowed, but this is not
885 true. For several reasons, not discussed here, some combinations were
886 not defined in the @acronym{TLS} protocol. The supported ciphersuites
887 are shown in @ref{ciphersuites}.
889 @subsection Client Authentication
890 @cindex Client Certificate authentication
892 In the case of ciphersuites that use certificate authentication, the
893 authentication of the client is optional in @acronym{TLS}. A server
894 may request a certificate from the client --- using the
895 @ref{gnutls_certificate_server_set_request} function. If a certificate
896 is to be requested from the client during the handshake, the server
897 will send a certificate request message that contains a list of
898 acceptable certificate signers. In @acronym{GnuTLS} the certificate
899 signers list is constructed using the trusted Certificate Authorities
900 by the server. That is the ones set using
902 @item @ref{gnutls_certificate_set_x509_trust_file}
903 @item @ref{gnutls_certificate_set_x509_trust_mem}
906 Sending of the names of the CAs can be controlled using
907 @ref{gnutls_certificate_send_x509_rdn_sequence}. The client, then, may
908 send a certificate, signed by one of the server's acceptable signers.
910 @subsection Resuming Sessions
912 @cindex Resuming sessions
914 The @ref{gnutls_handshake} function, is expensive since a lot of
915 calculations are performed. In order to support many fast connections
916 to the same server a client may use session resuming. @strong{Session
917 resuming} is a feature of the @acronym{TLS} protocol which allows a
918 client to connect to a server, after a successful handshake, without
919 the expensive calculations. This is achieved by using the previously
920 established keys. @acronym{GnuTLS} supports this feature, and the
921 example (@pxref{ex:resume-client}) illustrates a typical use of it.
923 Keep in mind that sessions are expired after some time, for security
924 reasons, thus it may be normal for a server not to resume a session
925 even if you requested that. Also note that you must enable, using the
926 priority functions, at least the algorithms used in the last session.
928 @subsection Resuming Internals
930 The resuming capability, mostly in the server side, is one of the
931 problems of a thread-safe TLS implementations. The problem is that all
932 threads must share information in order to be able to resume
933 sessions. The gnutls approach is, in case of a client, to leave all
934 the burden of resuming to the client. I.e., copy and keep the
935 necessary parameters. See the functions:
939 @item @ref{gnutls_session_get_data}
941 @item @ref{gnutls_session_get_id}
943 @item @ref{gnutls_session_set_data}
947 The server side is different. A server has to specify some callback
948 functions which store, retrieve and delete session data. These can be
953 @item @ref{gnutls_db_set_remove_function}
955 @item @ref{gnutls_db_set_store_function}
957 @item @ref{gnutls_db_set_retrieve_function}
959 @item @ref{gnutls_db_set_ptr}
963 It might also be useful to be able to check for expired sessions in
964 order to remove them, and save space. The function
965 @ref{gnutls_db_check_entry} is provided for that reason.
968 @section TLS Extensions
969 @cindex TLS Extensions
971 A number of extensions to the @acronym{TLS} protocol have been
972 proposed mainly in @xcite{TLSEXT}. The extensions supported
973 in @acronym{GnuTLS} are:
976 @item Maximum fragment length negotiation
977 @item Server name indication
978 @item Session tickets
981 and they will be discussed in the subsections that follow.
983 @subsection Maximum Fragment Length Negotiation
984 @cindex TLS Extensions
985 @cindex Maximum fragment length
987 This extension allows a @acronym{TLS} implementation to negotiate a
988 smaller value for record packet maximum length. This extension may be
989 useful to clients with constrained capabilities. See the
990 @ref{gnutls_record_set_max_size} and the
991 @ref{gnutls_record_get_max_size} functions.
993 @subsection Server Name Indication
995 @cindex TLS Extensions
996 @cindex Server name indication
998 A common problem in @acronym{HTTPS} servers is the fact that the
999 @acronym{TLS} protocol is not aware of the hostname that a client
1000 connects to, when the handshake procedure begins. For that reason the
1001 @acronym{TLS} server has no way to know which certificate to send.
1003 This extension solves that problem within the @acronym{TLS} protocol,
1004 and allows a client to send the HTTP hostname before the handshake
1005 begins within the first handshake packet. The functions
1006 @ref{gnutls_server_name_set} and @ref{gnutls_server_name_get} can be
1007 used to enable this extension, or to retrieve the name sent by a
1010 @subsection Session Tickets
1011 @cindex TLS Extensions
1012 @cindex Session Tickets
1015 To resume a TLS session the server normally store some state. This
1016 complicates deployment, and typical situations the client can cache
1017 information and send it to the server instead. The Session Ticket
1018 extension implements this idea, and it is documented in
1019 RFC 5077 @xcite{TLSTKT}.
1021 Clients can enable support for TLS tickets with
1022 @ref{gnutls_session_ticket_enable_client} and servers use
1023 @ref{gnutls_session_ticket_key_generate} to generate a key and
1024 @ref{gnutls_session_ticket_enable_server} to enable the extension.
1025 Clients resume sessions using the ticket using the normal session
1026 resume functions, @ref{resume}.
1028 @node Selecting cryptographic key sizes
1029 @section Selecting Cryptographic Key Sizes
1032 In TLS, since a lot of algorithms are involved, it is not easy to set
1033 a consistent security level. For this reason this section will
1034 present some correspondance between key sizes of symmetric algorithms
1035 and public key algorithms based on the most conservative values of
1036 @xcite{SELKEY}. Those can be used to generate certificates with
1037 appropriate key sizes as well as parameters for Diffie-Hellman and SRP
1040 @multitable @columnfractions .15 .20 .20 .20
1043 @tab Symmetric key size
1044 @tab RSA key size, DH and SRP prime size
1084 The first column provides an estimation of the year until these
1085 parameters are considered safe and the rest of the columns list the
1086 parameters for the various algorithms.
1088 Note however that the values suggested here are nothing more than an
1089 educated guess that is valid today. There are no guarrantees that an
1090 algorithm will remain unbreakable or that these values will remain
1091 constant in time. There could be scientific breakthroughs that cannot
1092 be predicted or total failure of the current public key systems by
1093 quantum computers. On the other hand though the cryptosystems used in
1094 TLS are selected in a conservative way and such catastrophic
1095 breakthroughs or failures are believed to be unlikely.
1097 NIST publication SP 800-57 @xcite{NISTSP80057} contains a similar
1098 table that extends beyond the key sizes given above.
1100 @multitable @columnfractions .15 .20 .20 .20
1102 @item Bits of security
1103 @tab Symmetric key algorithms
1104 @tab RSA key size, DSA, DH and SRP prime size
1134 The recommendations are fairly consistent.
1136 @node On SSL 2 and older protocols
1137 @section On SSL 2 and Older Protocols
1140 One of the initial decisions in the @acronym{GnuTLS} development was
1141 to implement the known security protocols for the transport layer.
1142 Initially @acronym{TLS} 1.0 was implemented since it was the latest at
1143 that time, and was considered to be the most advanced in security
1144 properties. Later the @acronym{SSL} 3.0 protocol was implemented
1145 since it is still the only protocol supported by several servers and
1146 there are no serious security vulnerabilities known.
1148 One question that may arise is why we didn't implement @acronym{SSL}
1149 2.0 in the library. There are several reasons, most important being
1150 that it has serious security flaws, unacceptable for a modern security
1151 library. Other than that, this protocol is barely used by anyone
1152 these days since it has been deprecated since 1996. The security
1153 problems in @acronym{SSL} 2.0 include:
1157 @item Message integrity compromised.
1158 The @acronym{SSLv2} message authentication uses the MD5 function, and
1161 @item Man-in-the-middle attack.
1162 There is no protection of the handshake in @acronym{SSLv2}, which
1163 permits a man-in-the-middle attack.
1165 @item Truncation attack.
1166 @acronym{SSLv2} relies on TCP FIN to close the session, so the
1167 attacker can forge a TCP FIN, and the peer cannot tell if it was a
1168 legitimate end of data or not.
1170 @item Weak message integrity for export ciphers.
1171 The cryptographic keys in @acronym{SSLv2} are used for both message
1172 authentication and encryption, so if weak encryption schemes are
1173 negotiated (say 40-bit keys) the message authentication code use the
1174 same weak key, which isn't necessary.
1179 Other protocols such as Microsoft's @acronym{PCT} 1 and @acronym{PCT}
1180 2 were not implemented because they were also abandoned and deprecated
1181 by @acronym{SSL} 3.0 and later @acronym{TLS} 1.0.
1183 @node On Record Padding
1184 @section On Record Padding
1185 @cindex Record padding
1186 @cindex Bad record MAC
1188 The TLS protocol allows for random padding of records, to make it more
1189 difficult to perform analysis on the length of exchanged messages.
1190 (In RFC 4346 this is specified in section 6.2.3.2.) GnuTLS appears to
1191 be one of few implementation that take advantage of this text, and pad
1192 records by a random length.
1194 The TLS implementation in the Symbian operating system, frequently
1195 used by Nokia and Sony-Ericsson mobile phones, cannot handle
1196 non-minimal record padding. What happens when one of these clients
1197 handshake with a GnuTLS server is that the client will fail to compute
1198 the correct MAC for the record. The client sends a TLS alert
1199 (@code{bad_record_mac}) and disconnects. Typically this will result
1200 in error messages such as 'A TLS fatal alert has been received', 'Bad
1201 record MAC', or both, on the GnuTLS server side.
1203 GnuTLS implements a work around for this problem. However, it has to
1204 be enabled specifically. It can be enabled by using
1205 @ref{gnutls_record_disable_padding}, or @ref{gnutls_priority_set} with
1206 the @code{%COMPAT} priority string.
1208 If you implement an application that have a configuration file, we
1209 recommend that you make it possible for users or administrators to
1210 specify a GnuTLS protocol priority string, which is used by your
1211 application via @ref{gnutls_priority_set}. To allow the best
1212 flexibility, make it possible to have a different priority string for
1213 different incoming IP addresses.
1215 To enable the workaround in the @code{gnutls-cli} client or the
1216 @code{gnutls-serv} server, for testing of other implementations, use
1217 the following parameter: @code{--priority "%COMPAT"}.
1219 This problem has been discussed on mailing lists and in bug reports.
1220 This section tries to collect all pieces of information that we know
1221 about the problem. If you wish to go back to the old discussions,
1222 here are some links:
1224 @url{http://bugs.debian.org/390712}
1226 @url{http://bugs.debian.org/402861}
1228 @url{http://bugs.debian.org/438137}
1230 @url{http://thread.gmane.org/gmane.ietf.tls/3079}
1232 @node Authentication methods
1233 @chapter Authentication Methods
1235 The @acronym{TLS} protocol provides confidentiality and encryption,
1236 but also offers authentication, which is a prerequisite for a secure
1237 connection. The available authentication methods in @acronym{GnuTLS}
1242 @item Certificate authentication
1244 @item Anonymous authentication
1246 @item @acronym{SRP} authentication
1248 @item @acronym{PSK} authentication
1253 * Certificate authentication::
1254 * Anonymous authentication::
1255 * Authentication using SRP::
1256 * Authentication using PSK::
1257 * Authentication and credentials::
1258 * Parameters stored in credentials::
1261 @node Certificate authentication
1262 @section Certificate Authentication
1264 @subsection Authentication Using @acronym{X.509} Certificates
1265 @cindex @acronym{X.509} certificates
1267 @acronym{X.509} certificates contain the public parameters, of a
1268 public key algorithm, and an authority's signature, which proves the
1269 authenticity of the parameters. @xref{The X.509 trust model}, for
1270 more information on @acronym{X.509} protocols.
1272 @subsection Authentication Using @acronym{OpenPGP} Keys
1273 @cindex @acronym{OpenPGP} Keys
1275 @acronym{OpenPGP} keys also contain public parameters of a public key
1276 algorithm, and signatures from several other parties. Depending on
1277 whether a signer is trusted the key is considered trusted or not.
1278 @acronym{GnuTLS}'s @acronym{OpenPGP} authentication implementation is
1279 based on the @xcite{TLSPGP} proposal.
1281 @xref{The OpenPGP trust model}, for more information about the
1282 @acronym{OpenPGP} trust model. For a more detailed introduction to
1283 @acronym{OpenPGP} and @acronym{GnuPG} see @xcite{GPGH}.
1285 @subsection Using Certificate Authentication
1287 In @acronym{GnuTLS} both the @acronym{OpenPGP} and @acronym{X.509}
1288 certificates are part of the certificate authentication and thus are
1289 handled using a common API.
1291 When using certificates the server is required to have at least one
1292 certificate and private key pair. A client may or may not have such a
1293 pair. The certificate and key pair should be loaded, before any
1294 @acronym{TLS} session is initialized, in a certificate credentials
1295 structure. This should be done by using
1296 @ref{gnutls_certificate_set_x509_key_file} or
1297 @ref{gnutls_certificate_set_openpgp_key_file} depending on the
1298 certificate type. In the @acronym{X.509} case, the functions will
1299 also accept and use a certificate list that leads to a trusted
1300 authority. The certificate list must be ordered in such way that every
1301 certificate certifies the one before it. The trusted authority's
1302 certificate need not to be included, since the peer should possess it
1305 As an alternative, a callback may be used so the server or the client
1306 specify the certificate and the key at the handshake time. That
1307 callback can be set using the functions:
1311 @item @ref{gnutls_certificate_server_set_retrieve_function}
1313 @item @ref{gnutls_certificate_client_set_retrieve_function}
1317 Certificate verification is possible by loading the trusted
1318 authorities into the credentials structure by using
1319 @ref{gnutls_certificate_set_x509_trust_file} or
1320 @ref{gnutls_certificate_set_openpgp_keyring_file} for openpgp
1321 keys. Note however that the peer's certificate is not automatically
1322 verified, you should call @ref{gnutls_certificate_verify_peers2},
1323 after a successful handshake, to verify the signatures of the
1324 certificate. An alternative way, which reports a more detailed
1325 verification output, is to use @ref{gnutls_certificate_get_peers} to
1326 obtain the raw certificate of the peer and verify it using the
1327 functions discussed in @ref{The X.509 trust model}.
1329 In a handshake, the negotiated cipher suite depends on the
1330 certificate's parameters, so not all key exchange methods will be
1331 available with some certificates. @acronym{GnuTLS} will disable
1332 ciphersuites that are not compatible with the key, or the enabled
1333 authentication methods. For example keys marked as sign-only, will
1334 not be able to access the plain RSA ciphersuites, but only the
1335 @code{DHE_RSA} ones. It is recommended not to use RSA keys for both
1336 signing and encryption. If possible use the same key for the
1337 @code{DHE_RSA} and @code{RSA_EXPORT} ciphersuites, which use signing,
1338 and a different key for the plain RSA ciphersuites, which use
1339 encryption. All the key exchange methods shown below are available in
1340 certificate authentication.
1342 Note that the DHE key exchange methods are generally
1343 slower@footnote{It really depends on the group used. Primes with
1344 lesser bits are always faster, but also easier to break. Values less
1345 than 768 should not be used today} than plain RSA and require Diffie
1346 Hellman parameters to be generated and associated with a credentials
1347 structure, by the server. The @code{RSA-EXPORT} method also requires
1348 512 bit RSA parameters, that should also be generated and associated
1349 with the credentials structure. See the functions:
1353 @item @ref{gnutls_dh_params_generate2}
1355 @item @ref{gnutls_certificate_set_dh_params}
1357 @item @ref{gnutls_rsa_params_generate2}
1359 @item @ref{gnutls_certificate_set_rsa_export_params}
1363 Sometimes in order to avoid bottlenecks in programs it is usefull to
1364 store and read parameters from formats that can be generated by
1365 external programs such as @code{certtool}. This is possible with
1366 @acronym{GnuTLS} by using the following functions:
1370 @item @ref{gnutls_dh_params_import_pkcs3}
1372 @item @ref{gnutls_rsa_params_import_pkcs1}
1374 @item @ref{gnutls_dh_params_export_pkcs3}
1376 @item @ref{gnutls_rsa_params_export_pkcs1}
1380 Key exchange algorithms for @acronym{OpenPGP} and @acronym{X.509}
1386 The RSA algorithm is used to encrypt a key and send it to the peer.
1387 The certificate must allow the key to be used for encryption.
1390 The RSA algorithm is used to encrypt a key and send it to the peer.
1391 In the EXPORT algorithm, the server signs temporary RSA parameters of
1392 512 bits --- which are considered weak --- and sends them to the
1396 The RSA algorithm is used to sign Ephemeral Diffie-Hellman parameters
1397 which are sent to the peer. The key in the certificate must allow the
1398 key to be used for signing. Note that key exchange algorithms which
1399 use Ephemeral Diffie-Hellman parameters, offer perfect forward
1400 secrecy. That means that even if the private key used for signing is
1401 compromised, it cannot be used to reveal past session data.
1404 The DSS algorithm is used to sign Ephemeral Diffie-Hellman parameters
1405 which are sent to the peer. The certificate must contain DSA
1406 parameters to use this key exchange algorithm. DSS stands for Digital
1411 @node Anonymous authentication
1412 @section Anonymous Authentication
1413 @cindex Anonymous authentication
1415 The anonymous key exchange performs encryption but there is no
1416 indication of the identity of the peer. This kind of authentication
1417 is vulnerable to a man in the middle attack, but this protocol can be
1418 used even if there is no prior communication and trusted parties with
1419 the peer, or when full anonymity is required. Unless really required,
1420 do not use anonymous authentication. Available key exchange methods
1423 Note that the key exchange methods for anonymous authentication
1424 require Diffie-Hellman parameters to be generated by the server and
1425 associated with an anonymous credentials structure.
1427 Supported anonymous key exchange algorithms:
1432 This algorithm exchanges Diffie-Hellman parameters.
1436 @node Authentication using SRP
1437 @section Authentication using @acronym{SRP}
1438 @cindex @acronym{SRP} authentication
1440 Authentication via the Secure Remote Password protocol,
1441 @acronym{SRP}@footnote{@acronym{SRP} is described in @xcite{RFC2945}},
1442 is supported. The @acronym{SRP} key exchange is an extension to the
1443 @acronym{TLS} protocol, and it is a password based authentication
1444 (unlike @acronym{X.509} or @acronym{OpenPGP} that use certificates).
1445 The two peers can be identified using a single password, or there can
1446 be combinations where the client is authenticated using @acronym{SRP}
1447 and the server using a certificate.
1449 The advantage of @acronym{SRP} authentication, over other proposed
1450 secure password authentication schemes, is that @acronym{SRP} does not
1451 require the server to hold the user's password. This kind of
1452 protection is similar to the one used traditionally in the @emph{UNIX}
1453 @file{/etc/passwd} file, where the contents of this file did not cause
1454 harm to the system security if they were revealed. The @acronym{SRP}
1455 needs instead of the plain password something called a verifier, which
1456 is calculated using the user's password, and if stolen cannot be used
1457 to impersonate the user. Check @xcite{TOMSRP} for a detailed
1458 description of the @acronym{SRP} protocol and the Stanford
1459 @acronym{SRP} libraries, which includes a PAM module that synchronizes
1460 the system's users passwords with the @acronym{SRP} password
1461 files. That way @acronym{SRP} authentication could be used for all the
1464 The implementation in @acronym{GnuTLS} is based on paper
1465 @xcite{TLSSRP}. The supported @acronym{SRP} key exchange methods are:
1470 Authentication using the @acronym{SRP} protocol.
1473 Client authentication using the @acronym{SRP} protocol. Server is
1474 authenticated using a certificate with DSA parameters.
1477 Client authentication using the @acronym{SRP} protocol. Server is
1478 authenticated using a certificate with RSA parameters.
1482 If clients supporting @acronym{SRP} know the username and password
1483 before the connection, should initialize the client credentials and
1484 call the function @ref{gnutls_srp_set_client_credentials}.
1485 Alternatively they could specify a callback function by using the
1486 function @ref{gnutls_srp_set_client_credentials_function}. This has
1487 the advantage that allows probing the server for @acronym{SRP}
1488 support. In that case the callback function will be called twice per
1489 handshake. The first time is before the ciphersuite is negotiated,
1490 and if the callback returns a negative error code, the callback will
1491 be called again if @acronym{SRP} has been negotiated. This uses a
1492 special @acronym{TLS}-@acronym{SRP} handshake idiom in order to avoid,
1493 in interactive applications, to ask the user for @acronym{SRP}
1494 password and username if the server does not negotiate an
1495 @acronym{SRP} ciphersuite.
1497 In server side the default behaviour of @acronym{GnuTLS} is to read
1498 the usernames and @acronym{SRP} verifiers from password files. These
1499 password files are the ones used by the @emph{Stanford srp libraries}
1500 and can be specified using the
1501 @ref{gnutls_srp_set_server_credentials_file}. If a different
1502 password file format is to be used, then the function
1503 @ref{gnutls_srp_set_server_credentials_function}, should be called,
1504 in order to set an appropriate callback.
1506 Some helper functions such as
1510 @item @ref{gnutls_srp_verifier}
1512 @item @ref{gnutls_srp_base64_encode}
1514 @item @ref{gnutls_srp_base64_decode}
1518 are included in @acronym{GnuTLS}, and can be used to generate and
1519 maintain @acronym{SRP} verifiers and password files. A program to
1520 manipulate the required parameters for @acronym{SRP} authentication is
1521 also included. @xref{srptool}, for more information.
1524 @node Authentication using PSK
1525 @section Authentication using @acronym{PSK}
1526 @cindex @acronym{PSK} authentication
1528 Authentication using Pre-shared keys is a method to authenticate using
1529 usernames and binary keys. This protocol avoids making use of public
1530 key infrastructure and expensive calculations, thus it is suitable for
1533 The implementation in @acronym{GnuTLS} is based on paper
1534 @xcite{TLSPSK}. The supported @acronym{PSK} key exchange methods are:
1539 Authentication using the @acronym{PSK} protocol.
1542 Authentication using the @acronym{PSK} protocol and Diffie-Hellman key
1543 exchange. This method offers perfect forward secrecy.
1547 Clients supporting @acronym{PSK} should supply the username and key
1548 before the connection to the client credentials by calling the
1549 function @ref{gnutls_psk_set_client_credentials}. Alternatively they
1550 could specify a callback function by using the function
1551 @ref{gnutls_psk_set_client_credentials_function}. This has the
1552 advantage that the callback will be called only if @acronym{PSK} has
1555 In server side the default behaviour of @acronym{GnuTLS} is to read
1556 the usernames and @acronym{PSK} keys from a password file. The
1557 password file should contain usernames and keys in hexadecimal
1558 format. The name of the password file can be stored to the credentials
1559 structure by calling @ref{gnutls_psk_set_server_credentials_file}. If
1560 a different password file format is to be used, then the function
1561 @ref{gnutls_psk_set_server_credentials_function}, should be used
1564 The server can help the client chose a suitable username and password,
1565 by sending a hint. In the server, specify the hint by calling
1566 @ref{gnutls_psk_set_server_credentials_hint}. The client can retrieve
1567 the hint, for example in the callback function, using
1568 @ref{gnutls_psk_client_get_hint}.
1570 There is no standard mechanism to derive a PSK key from a password
1571 specified by the TLS PSK document. However, GnuTLS provides
1572 @ref{gnutls_psk_netconf_derive_key} which follows the algorithm
1573 specified in @file{draft-ietf-netconf-tls-02.txt}.
1575 Some helper functions such as:
1579 @item @ref{gnutls_hex_encode}
1581 @item @ref{gnutls_hex_decode}
1585 are included in @acronym{GnuTLS}, and may be used to generate and
1586 maintain @acronym{PSK} keys.
1589 @node Authentication and credentials
1590 @section Authentication and Credentials
1592 In @acronym{GnuTLS} every key exchange method is associated with a
1593 credentials type. So in order to enable to enable a specific method,
1594 the corresponding credentials type should be initialized and set using
1595 @ref{gnutls_credentials_set}. A mapping is shown below.
1597 Key exchange algorithms and the corresponding credential types:
1599 @multitable @columnfractions .3 .3 .3
1601 @headitem Key exchange @tab Client credentials @tab Server credentials
1604 @item @code{KX_DHE_RSA}
1605 @item @code{KX_DHE_DSS}
1606 @item @code{KX_RSA_EXPORT}
1607 @tab @code{CRD_CERTIFICATE}
1608 @tab @code{CRD_CERTIFICATE}
1610 @item @code{KX_SRP_RSA}
1613 @item @code{KX_SRP_DSS}
1615 @tab @code{CRD_CERTIFICATE}
1621 @item @code{KX_ANON_DH}
1622 @tab @code{CRD_ANON}
1623 @tab @code{CRD_ANON}
1631 @node Parameters stored in credentials
1632 @section Parameters Stored in Credentials
1634 Several parameters such as the ones used for Diffie-Hellman
1635 authentication are stored within the credentials structures, so all
1636 sessions can access them. Those parameters are stored in structures
1637 such as @code{gnutls_dh_params_t} and @code{gnutls_rsa_params_t}, and
1638 functions like @ref{gnutls_certificate_set_dh_params} and
1639 @ref{gnutls_certificate_set_rsa_export_params} can be used to
1640 associate those parameters with the given credentials structure.
1642 Since those parameters need to be renewed from time to time and a
1643 global structure such as the credentials, may not be easy to modify
1644 since it is accessible by all sessions, an alternative interface is
1645 available using a callback function. This can be set using the
1646 @ref{gnutls_certificate_set_params_function}. An example is shown
1652 gnutls_rsa_params_t rsa_params;
1653 gnutls_dh_params_t dh_params;
1655 /* This function will be called once a session requests DH
1656 * or RSA parameters. The parameters returned (if any) will
1657 * be used for the first handshake only.
1659 static int get_params( gnutls_session_t session,
1660 gnutls_params_type_t type,
1661 gnutls_params_st *st)
1663 if (type == GNUTLS_PARAMS_RSA_EXPORT)
1664 st->params.rsa_export = rsa_params;
1665 else if (type == GNUTLS_PARAMS_DH)
1666 st->params.dh = dh_params;
1670 /* do not deinitialize those parameters.
1679 gnutls_certificate_credentials_t cert_cred;
1681 initialize_params();
1686 gnutls_certificate_set_params_function( cert_cred, get_params);
1690 @node More on certificate authentication
1691 @chapter More on Certificate Authentication
1692 @anchor{Certificate Authentication}
1693 @cindex Certificate authentication
1696 * The X.509 trust model::
1697 * The OpenPGP trust model::
1698 * Digital signatures::
1701 @node The X.509 trust model
1702 @section The @acronym{X.509} Trust Model
1703 @cindex @acronym{X.509} certificates
1705 The @acronym{X.509} protocols rely on a hierarchical trust model. In
1706 this trust model Certification Authorities (CAs) are used to certify
1707 entities. Usually more than one certification authorities exist, and
1708 certification authorities may certify other authorities to issue
1709 certificates as well, following a hierarchical model.
1711 @image{gnutls-x509,7cm,9.5cm}
1713 One needs to trust one or more CAs for his secure communications. In
1714 that case only the certificates issued by the trusted authorities are
1715 acceptable. See the figure above for a typical example. The API for
1716 handling @acronym{X.509} certificates is described at section
1717 @ref{sec:x509api}. Some examples are listed below.
1720 * X.509 certificates::
1721 * Verifying X.509 certificate paths::
1722 * PKCS #10 certificate requests::
1723 * PKCS #12 structures::
1726 @node X.509 certificates
1727 @subsection @acronym{X.509} Certificates
1729 An @acronym{X.509} certificate usually contains information about the
1730 certificate holder, the signer, a unique serial number, expiration
1731 dates and some other fields @xcite{PKIX} as shown in the table below.
1736 The field that indicates the version of the certificate.
1739 This field holds a unique serial number per certificate.
1742 Holds the issuer's distinguished name.
1745 The activation and expiration dates.
1748 The subject's distinguished name of the certificate.
1751 The extensions are fields only present in version 3 certificates.
1755 The certificate's @emph{subject or issuer name} is not just a single
1756 string. It is a Distinguished name and in the @acronym{ASN.1}
1757 notation is a sequence of several object IDs with their corresponding
1758 values. Some of available OIDs to be used in an @acronym{X.509}
1759 distinguished name are defined in @file{gnutls/x509.h}.
1761 The @emph{Version} field in a certificate has values either 1 or 3 for
1762 version 3 certificates. Version 1 certificates do not support the
1763 extensions field so it is not possible to distinguish a CA from a
1764 person, thus their usage should be avoided.
1766 The @emph{validity} dates are there to indicate the date that the
1767 specific certificate was activated and the date the certificate's key
1768 would be considered invalid.
1770 Certificate @emph{extensions} are there to include information about
1771 the certificate's subject that did not fit in the typical certificate
1772 fields. Those may be e-mail addresses, flags that indicate whether the
1773 belongs to a CA etc. All the supported @acronym{X.509} version 3
1774 extensions are shown in the table below.
1778 @item subject key id (2.5.29.14):
1779 An identifier of the key of the subject.
1781 @item authority key id (2.5.29.35):
1782 An identifier of the authority's key used to sign the certificate.
1784 @item subject alternative name (2.5.29.17):
1785 Alternative names to subject's distinguished name.
1787 @item key usage (2.5.29.15):
1788 Constraints the key's usage of the certificate.
1790 @item extended key usage (2.5.29.37):
1791 Constraints the purpose of the certificate.
1793 @item basic constraints (2.5.29.19):
1794 Indicates whether this is a CA certificate or not, and specify the
1795 maximum path lengths of certificate chains.
1797 @item CRL distribution points (2.5.29.31):
1798 This extension is set by the CA, in order to inform about the issued
1801 @item Proxy Certification Information (1.3.6.1.5.5.7.1.14):
1802 Proxy Certificates includes this extension that contains the OID of
1803 the proxy policy language used, and can specify limits on the maximum
1804 lengths of proxy chains. Proxy Certificates are specified in
1809 In @acronym{GnuTLS} the @acronym{X.509} certificate structures are
1810 handled using the @code{gnutls_x509_crt_t} type and the corresponding
1811 private keys with the @code{gnutls_x509_privkey_t} type. All the
1812 available functions for @acronym{X.509} certificate handling have
1813 their prototypes in @file{gnutls/x509.h}. An example program to
1814 demonstrate the @acronym{X.509} parsing capabilities can be found at
1815 section @ref{ex:x509-info}.
1817 @node Verifying X.509 certificate paths
1818 @subsection Verifying @acronym{X.509} Certificate Paths
1819 @cindex Verifying certificate paths
1821 Verifying certificate paths is important in @acronym{X.509}
1822 authentication. For this purpose the function
1823 @ref{gnutls_x509_crt_verify} is provided. The output of this function
1824 is the bitwise OR of the elements of the
1825 @code{gnutls_certificate_status_t} enumeration. A detailed
1826 description of these elements can be found in figure below. The
1827 function @ref{gnutls_certificate_verify_peers2} is equivalent to the
1828 previous one, and will verify the peer's certificate in a TLS session.
1833 The certificate is not signed by one of the known authorities, or
1834 the signature is invalid.
1837 The certificate has been revoked by its CA.
1839 @item CERT_SIGNER_NOT_FOUND:
1840 The certificate's issuer is not known. This is the case when the
1841 issuer is not in the trusted certificates list.
1843 @item GNUTLS_CERT_SIGNER_NOT_CA:
1844 The certificate's signer was not a CA. This may happen if
1845 this was a version 1 certificate, which is common with some CAs, or
1846 a version 3 certificate without the basic constrains extension.
1848 @anchor{GNUTLS_CERT_INSECURE_ALGORITHM}
1849 @item GNUTLS_CERT_INSECURE_ALGORITHM:
1850 The certificate was signed using an insecure algorithm such as MD2 or
1851 MD5. These algorithms have been broken and should not be trusted.
1855 There is also to possibility to pass some input to the verification
1856 functions in the form of flags. For @ref{gnutls_x509_crt_verify} the
1857 flags are passed straightforward, but
1858 @ref{gnutls_certificate_verify_peers2} depends on the flags set by
1859 calling @ref{gnutls_certificate_set_verify_flags}. All the available
1860 flags are part of the enumeration
1861 @ref{gnutls_certificate_verify_flags} and are explained in the table
1864 @anchor{gnutls_certificate_verify_flags}
1865 @tindex gnutls_certificate_verify_flags
1867 @item GNUTLS_VERIFY_DISABLE_CA_SIGN:
1868 If set a signer does not have to be a certificate authority. This
1869 flag should normaly be disabled, unless you know what this means.
1871 @item GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT:
1872 Allow only trusted CA certificates that have version 1. This is
1873 safer than GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT, and should be
1874 used instead. That way only signers in your trusted list will be
1875 allowed to have certificates of version 1.
1877 @item GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT:
1878 Allow CA certificates that have version 1 (both root and
1879 intermediate). This is dangerous since those haven't the
1880 basicConstraints extension. Must be used in combination with
1881 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT.
1883 @item GNUTLS_VERIFY_DO_NOT_ALLOW_SAME:
1884 If a certificate is not signed by anyone trusted but exists in
1885 the trusted CA list do not treat it as trusted.
1887 @item GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2:
1888 Allow certificates to be signed using the old MD2 algorithm.
1890 @item GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5:
1891 Allow certificates to be signed using the broken MD5 algorithm.
1894 Although the verification of a certificate path indicates that the
1895 certificate is signed by trusted authority, does not reveal anything
1896 about the peer's identity. It is required to verify if the
1897 certificate's owner is the one you expect. For more information
1898 consult @xcite{RFC2818} and section @ref{ex:verify} for an example.
1900 @node PKCS #10 certificate requests
1901 @subsection @acronym{PKCS} #10 Certificate Requests
1902 @cindex Certificate requests
1903 @cindex @acronym{PKCS} #10
1905 A certificate request is a structure, which contain information about
1906 an applicant of a certificate service. It usually contains a private
1907 key, a distinguished name and secondary data such as a challenge
1908 password. @acronym{GnuTLS} supports the requests defined in
1909 @acronym{PKCS} #10 @xcite{RFC2986}. Other certificate request's format
1910 such as PKIX's @xcite{RFC4211} are not currently supported.
1912 In @acronym{GnuTLS} the @acronym{PKCS} #10 structures are handled
1913 using the @code{gnutls_x509_crq_t} type. An example of a certificate
1914 request generation can be found at section @ref{ex:crq}.
1916 @node PKCS #12 structures
1917 @subsection @acronym{PKCS} #12 Structures
1918 @cindex @acronym{PKCS} #12
1920 A @acronym{PKCS} #12 structure @xcite{PKCS12} usually contains a user's
1921 private keys and certificates. It is commonly used in browsers to
1922 export and import the user's identities.
1924 In @acronym{GnuTLS} the @acronym{PKCS} #12 structures are handled
1925 using the @code{gnutls_pkcs12_t} type. This is an abstract type that
1926 may hold several @code{gnutls_pkcs12_bag_t} types. The Bag types are
1927 the holders of the actual data, which may be certificates, private
1928 keys or encrypted data. An Bag of type encrypted should be decrypted
1929 in order for its data to be accessed.
1931 An example of a @acronym{PKCS} #12 structure generation can be found
1932 at section @ref{ex:pkcs12}.
1934 @node The OpenPGP trust model
1935 @section The @acronym{OpenPGP} Trust Model
1936 @cindex @acronym{OpenPGP} Keys
1938 The @acronym{OpenPGP} key authentication relies on a distributed trust
1939 model, called the ``web of trust''. The ``web of trust'' uses a
1940 decentralized system of trusted introducers, which are the same as a
1941 CA. @acronym{OpenPGP} allows anyone to sign anyone's else public
1942 key. When Alice signs Bob's key, she is introducing Bob's key to
1943 anyone who trusts Alice. If someone trusts Alice to introduce keys,
1944 then Alice is a trusted introducer in the mind of that observer.
1946 @image{gnutls-pgp,11cm,9cm}
1948 For example: If David trusts Alice to be an introducer, and Alice
1949 signed Bob's key, Dave also trusts Bob's key to be the real one.
1951 There are some key points that are important in that model. In the
1952 example Alice has to sign Bob's key, only if she is sure that the key
1953 belongs to Bob. Otherwise she may also make Dave falsely believe that
1954 this is Bob's key. Dave has also the responsibility to know who to
1955 trust. This model is similar to real life relations.
1957 Just see how Charlie behaves in the previous example. Although he has
1958 signed Bob's key - because he knows, somehow, that it belongs to Bob -
1959 he does not trust Bob to be an introducer. Charlie decided to trust
1960 only Kevin, for some reason. A reason could be that Bob is lazy
1961 enough, and signs other people's keys without being sure that they
1962 belong to the actual owner.
1964 @subsection @acronym{OpenPGP} Keys
1966 In @acronym{GnuTLS} the @acronym{OpenPGP} key structures
1967 @xcite{RFC2440} are handled using the @code{gnutls_openpgp_crt_t} type
1968 and the corresponding private keys with the
1969 @code{gnutls_openpgp_privkey_t} type. All the prototypes for the key
1970 handling functions can be found at @file{gnutls/openpgp.h}.
1972 @subsection Verifying an @acronym{OpenPGP} Key
1974 The verification functions of @acronym{OpenPGP} keys, included in
1975 @acronym{GnuTLS}, are simple ones, and do not use the features of the
1976 ``web of trust''. For that reason, if the verification needs are
1977 complex, the assistance of external tools like @acronym{GnuPG} and
1978 GPGME (@url{http://www.gnupg.org/related_software/gpgme/}) is
1981 There is one verification function in @acronym{GnuTLS}, the
1982 @ref{gnutls_openpgp_crt_verify_ring}. This checks an
1983 @acronym{OpenPGP} key against a given set of public keys (keyring) and
1984 returns the key status. The key verification status is the same as in
1985 @acronym{X.509} certificates, although the meaning and interpretation
1986 are different. For example an @acronym{OpenPGP} key may be valid, if
1987 the self signature is ok, even if no signers were found. The meaning
1988 of verification status is shown in the figure below.
1993 A signature on the key is invalid. That means that the key was
1994 modified by somebody, or corrupted during transport.
1997 The key has been revoked by its owner.
1999 @item CERT_SIGNER_NOT_FOUND:
2000 The key was not signed by a known signer.
2002 @item GNUTLS_CERT_INSECURE_ALGORITHM:
2003 The certificate was signed using an insecure algorithm such as MD2 or
2004 MD5. These algorithms have been broken and should not be trusted.
2008 @node Digital signatures
2009 @section Digital Signatures
2010 @cindex Digital signatures
2012 In this section we will provide some information about digital
2013 signatures, how they work, and give the rationale for disabling some
2014 of the algorithms used.
2016 Digital signatures work by using somebody's secret key to sign some
2017 arbitrary data. Then anybody else could use the public key of that
2018 person to verify the signature. Since the data may be arbitrary it is
2019 not suitable input to a cryptographic digital signature algorithm. For
2020 this reason and also for performance cryptographic hash algorithms are
2021 used to preprocess the input to the signature algorithm. This works as
2022 long as it is difficult enough to generate two different messages with
2023 the same hash algorithm output. In that case the same signature could
2024 be used as a proof for both messages. Nobody wants to sign an innocent
2025 message of donating 1 @euro{} to Greenpeace and find out that he
2026 donated 1.000.000 @euro{} to Bad Inc.
2028 For a hash algorithm to be called cryptographic the following three
2029 requirements must hold:
2032 @item Preimage resistance.
2033 That means the algorithm must be one way and given the output of the
2034 hash function @math{H(x)}, it is impossible to calculate @math{x}.
2036 @item 2nd preimage resistance.
2037 That means that given a pair @math{x,y} with @math{y=H(x)} it is
2038 impossible to calculate an @math{x'} such that @math{y=H(x')}.
2040 @item Collision resistance.
2041 That means that it is impossible to calculate random @math{x} and
2042 @math{x'} such @math{H(x')=H(x)}.
2045 The last two requirements in the list are the most important in
2046 digital signatures. These protect against somebody who would like to
2047 generate two messages with the same hash output. When an algorithm is
2048 considered broken usually it means that the Collision resistance of
2049 the algorithm is less than brute force. Using the birthday paradox the
2050 brute force attack takes
2052 @math{2^{(\rm{hash\ size}) / 2}}
2055 @math{2^{((hash size) / 2)}}
2057 operations. Today colliding certificates using the MD5 hash algorithm
2058 have been generated as shown in @xcite{WEGER}.
2060 There has been cryptographic results for the SHA-1 hash algorithms as
2061 well, although they are not yet critical. Before 2004, MD5 had a
2062 presumed collision strength of @math{2^{64}}, but it has been showed
2063 to have a collision strength well under @math{2^{50}}. As of November
2064 2005, it is believed that SHA-1's collision strength is around
2065 @math{2^{63}}. We consider this sufficiently hard so that we still
2066 support SHA-1. We anticipate that SHA-256/386/512 will be used in
2067 publicly-distributed certificates in the future. When @math{2^{63}}
2068 can be considered too weak compared to the computer power available
2069 sometime in the future, SHA-1 will be disabled as well. The collision
2070 attacks on SHA-1 may also get better, given the new interest in tools
2073 @subsection Trading Security for Interoperability
2075 If you connect to a server and use GnuTLS' functions to verify the
2076 certificate chain, and get a @ref{GNUTLS_CERT_INSECURE_ALGORITHM}
2077 validation error (@pxref{Verifying X.509 certificate paths}), it means
2078 that somewhere in the certificate chain there is a certificate signed
2079 using @code{RSA-MD2} or @code{RSA-MD5}. These two digital signature
2080 algorithms are considered broken, so GnuTLS fail when attempting to
2081 verify the certificate. In some situations, it may be useful to be
2082 able to verify the certificate chain anyway, assuming an attacker did
2083 not utilize the fact that these signatures algorithms are broken.
2084 This section will give help on how to achieve that.
2086 First, it is important to know that you do not have to enable any of
2087 the flags discussed here to be able to use trusted root CA
2088 certificates signed using @code{RSA-MD2} or @code{RSA-MD5}. The only
2089 attack today is that it is possible to generate certificates with
2090 colliding signatures (collision resistance); you cannot generate a
2091 certificate that has the same signature as an already existing
2092 signature (2nd preimage resistance).
2094 If you are using @ref{gnutls_certificate_verify_peers2} to verify the
2095 certificate chain, you can call
2096 @ref{gnutls_certificate_set_verify_flags} with the
2097 @code{GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2} or
2098 @code{GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5} flag, as in:
2101 gnutls_certificate_set_verify_flags (x509cred,
2102 GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5);
2105 This will tell the verifier algorithm to enable @code{RSA-MD5} when
2106 verifying the certificates.
2108 If you are using @ref{gnutls_x509_crt_verify} or
2109 @ref{gnutls_x509_crt_list_verify}, you can pass the
2110 @code{GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5} parameter directly in the
2111 @code{flags} parameter.
2113 If you are using these flags, it may also be a good idea to warn the
2114 user when verification failure occur for this reason. The simplest is
2115 to not use the flags by default, and only fall back to using them
2116 after warning the user. If you wish to inspect the certificate chain
2117 yourself, you can use @ref{gnutls_certificate_get_peers} to extract
2118 the raw server's certificate chain, then use
2119 @ref{gnutls_x509_crt_import} to parse each of the certificates, and
2120 then use @ref{gnutls_x509_crt_get_signature_algorithm} to find out the
2121 signing algorithm used for each certificate. If any of the
2122 intermediary certificates are using @code{GNUTLS_SIGN_RSA_MD2} or
2123 @code{GNUTLS_SIGN_RSA_MD5}, you could present a warning.
2127 @node How to use TLS in application protocols
2128 @chapter How To Use @acronym{TLS} in Application Protocols
2130 This chapter is intended to provide some hints on how to use the
2131 @acronym{TLS} over simple custom made application protocols. The
2132 discussion below mainly refers to the @emph{TCP/IP} transport layer
2133 but may be extended to other ones too.
2137 * Upward negotiation::
2140 @node Separate ports
2141 @section Separate Ports
2143 Traditionally @acronym{SSL} was used in application protocols by
2144 assigning a new port number for the secure services. That way two
2145 separate ports were assigned, one for the non secure sessions, and one
2146 for the secured ones. This has the benefit that if a user requests a
2147 secure session then the client will try to connect to the secure port
2148 and fail otherwise. The only possible attack with this method is a
2149 denial of service one. The most famous example of this method is the
2150 famous ``HTTP over TLS'' or @acronym{HTTPS} protocol @xcite{RFC2818}.
2152 Despite its wide use, this method is not as good as it seems. This
2153 approach starts the @acronym{TLS} Handshake procedure just after the
2154 client connects on the ---so called--- secure port. That way the
2155 @acronym{TLS} protocol does not know anything about the client, and
2156 popular methods like the host advertising in HTTP do not
2157 work@footnote{See also the Server Name Indication extension on
2158 @ref{serverind}.}. There is no way for the client to say ``I
2159 connected to YYY server'' before the Handshake starts, so the server
2160 cannot possibly know which certificate to use.
2162 Other than that it requires two separate ports to run a single
2163 service, which is unnecessary complication. Due to the fact that there
2164 is a limitation on the available privileged ports, this approach was
2167 @node Upward negotiation
2168 @section Upward Negotiation
2170 Other application protocols@footnote{See LDAP, IMAP etc.} use a
2171 different approach to enable the secure layer. They use something
2172 called the ``TLS upgrade'' method. This method is quite tricky but it
2173 is more flexible. The idea is to extend the application protocol to
2174 have a ``STARTTLS'' request, whose purpose it to start the TLS
2175 protocols just after the client requests it. This is a really neat
2176 idea and does not require an extra port.
2178 This method is used by almost all modern protocols and there is even
2179 the @xcite{RFC2817} paper which proposes extensions to HTTP to support
2182 The tricky part, in this method, is that the ``STARTTLS'' request is
2183 sent in the clear, thus is vulnerable to modifications. A typical
2184 attack is to modify the messages in a way that the client is fooled
2185 and thinks that the server does not have the ``STARTTLS'' capability.
2186 See a typical conversation of a hypothetical protocol:
2189 (client connects to the server)
2191 CLIENT: HELLO I'M MR. XXX
2193 SERVER: NICE TO MEET YOU XXX
2195 CLIENT: PLEASE START TLS
2201 CLIENT: HERE ARE SOME CONFIDENTIAL DATA
2204 And see an example of a conversation where someone is acting
2208 (client connects to the server)
2210 CLIENT: HELLO I'M MR. XXX
2212 SERVER: NICE TO MEET YOU XXX
2214 CLIENT: PLEASE START TLS
2216 (here someone inserts this message)
2218 SERVER: SORRY I DON'T HAVE THIS CAPABILITY
2220 CLIENT: HERE ARE SOME CONFIDENTIAL DATA
2223 As you can see above the client was fooled, and was dummy enough to
2224 send the confidential data in the clear.
2226 How to avoid the above attack? As you may have already thought this
2227 one is easy to avoid. The client has to ask the user before it
2228 connects whether the user requests @acronym{TLS} or not. If the user
2229 answered that he certainly wants the secure layer the last
2230 conversation should be:
2233 (client connects to the server)
2235 CLIENT: HELLO I'M MR. XXX
2237 SERVER: NICE TO MEET YOU XXX
2239 CLIENT: PLEASE START TLS
2241 (here someone inserts this message)
2243 SERVER: SORRY I DON'T HAVE THIS CAPABILITY
2247 (the client notifies the user that the secure connection was not possible)
2250 This method, if implemented properly, is far better than the
2251 traditional method, and the security properties remain the same, since
2252 only denial of service is possible. The benefit is that the server may
2253 request additional data before the @acronym{TLS} Handshake protocol
2254 starts, in order to send the correct certificate, use the correct
2255 password file@footnote{in @acronym{SRP} authentication}, or anything
2258 @node How to use GnuTLS in applications
2259 @chapter How To Use @acronym{GnuTLS} in Applications
2261 @cindex Example programs
2265 * Multi-threaded applications::
2268 * Miscellaneous examples::
2269 * Compatibility with the OpenSSL library::
2270 * Opaque PRF Input TLS Extension::
2271 * Keying Material Exporters::
2275 @section Preparation
2277 To use @acronym{GnuTLS}, you have to perform some changes to your
2278 sources and your build system. The necessary changes are explained in
2279 the following subsections.
2286 * Building the source::
2292 All the data types and functions of the @acronym{GnuTLS} library are
2293 defined in the header file @file{gnutls/gnutls.h}. This must be
2294 included in all programs that make use of the @acronym{GnuTLS}
2297 The extra functionality of the @acronym{GnuTLS-extra} library is
2298 available by including the header file @file{gnutls/extra.h} in your
2301 @node Initialization
2302 @subsection Initialization
2304 GnuTLS must be initialized before it can be used. The library is
2305 initialized by calling @ref{gnutls_global_init}. The resources
2306 allocated by the initialization process can be released if the
2307 application no longer has a need to call GnuTLS functions, this is
2308 done by calling @ref{gnutls_global_deinit}.
2310 The extra functionality of the @acronym{GnuTLS-extra} library is
2311 available after calling @ref{gnutls_global_init_extra}.
2313 In order to take advantage of the internationalisation features in
2314 GnuTLS, such as translated error messages, the application must set
2315 the current locale using @code{setlocale} before initializing GnuTLS.
2318 @subsection Version Check
2320 It is often desirable to check that the version of `gnutls' used is
2321 indeed one which fits all requirements. Even with binary
2322 compatibility new features may have been introduced but due to problem
2323 with the dynamic linker an old version is actually used. So you may
2324 want to check that the version is okay right after program startup.
2325 See the function @ref{gnutls_check_version}.
2328 @subsection Debugging
2330 In many cases things may not go as expected and further information,
2331 to assist debugging, from @acronym{GnuTLS} is desired. Those are the
2332 case where the @ref{gnutls_global_set_log_level} and
2333 @ref{gnutls_global_set_log_function} are to be used. Those will print
2334 verbose information on the @acronym{GnuTLS} functions internal flow.
2336 @node Building the source
2337 @subsection Building the Source
2339 If you want to compile a source file including the
2340 @file{gnutls/gnutls.h} header file, you must make sure that the
2341 compiler can find it in the directory hierarchy. This is accomplished
2342 by adding the path to the directory in which the header file is
2343 located to the compilers include file search path (via the @option{-I}
2346 However, the path to the include file is determined at the time the
2347 source is configured. To solve this problem, the library uses the
2348 external package @command{pkg-config} that knows the path to the
2349 include file and other configuration options. The options that need
2350 to be added to the compiler invocation at compile time are output by
2351 the @option{--cflags} option to @command{pkg-config libgnutls}. The
2352 following example shows how it can be used at the command line:
2355 gcc -c foo.c `pkg-config libgnutls --cflags`
2358 Adding the output of @samp{pkg-config libgnutls --cflags} to the
2359 compilers command line will ensure that the compiler can find the
2360 @file{gnutls/gnutls.h} header file.
2362 A similar problem occurs when linking the program with the library.
2363 Again, the compiler has to find the library files. For this to work,
2364 the path to the library files has to be added to the library search
2365 path (via the @option{-L} option). For this, the option
2366 @option{--libs} to @command{pkg-config libgnutls} can be used. For
2367 convenience, this option also outputs all other options that are
2368 required to link the program with the libarary (for instance, the
2369 @samp{-ltasn1} option). The example shows how to link @file{foo.o}
2370 with the library to a program @command{foo}.
2373 gcc -o foo foo.o `pkg-config libgnutls --libs`
2376 Of course you can also combine both examples to a single command by
2377 specifying both options to @command{pkg-config}:
2380 gcc -o foo foo.c `pkg-config libgnutls --cflags --libs`
2383 @node Multi-threaded applications
2384 @section Multi-Threaded Applications
2386 Although the @acronym{GnuTLS} library is thread safe by design, some
2387 parts of Libgcrypt, such as the random generator, are not.
2388 Applications have to register callback functions to ensure proper
2389 locking in the sensitive parts of @emph{libgcrypt}.
2391 There are helper macros to help you properly initialize the libraries.
2392 Examples are shown below.
2401 #include <pthread.h>
2402 GCRY_THREAD_OPTION_PTHREAD_IMPL;
2406 /* The order matters.
2408 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
2409 gnutls_global_init();
2413 @item GNU PTH threads
2419 GCRY_THREAD_OPTION_PTH_IMPL;
2423 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
2424 gnutls_global_init();
2428 @item Other thread packages
2430 /* The gcry_thread_cbs structure must have been
2433 static struct gcry_thread_cbs gcry_threads_other = @{ ... @};
2437 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_other);
2442 @node Client examples
2443 @section Client Examples
2445 This section contains examples of @acronym{TLS} and @acronym{SSL}
2446 clients, using @acronym{GnuTLS}. Note that these examples contain
2447 little or no error checking. Some of the examples require functions
2448 implemented by another example.
2451 * Simple client example with anonymous authentication::
2452 * Simple client example with X.509 certificate support::
2453 * Obtaining session information::
2454 * Verifying peer's certificate::
2455 * Using a callback to select the certificate to use::
2456 * Client with Resume capability example::
2457 * Simple client example with SRP authentication::
2458 * Simple client example with TLS/IA support::
2459 * Simple client example in C++::
2460 * Helper function for TCP connections::
2463 @node Simple client example with anonymous authentication
2464 @subsection Simple Client Example with Anonymous Authentication
2466 The simplest client using TLS is the one that doesn't do any
2467 authentication. This means no external certificates or passwords are
2468 needed to set up the connection. As could be expected, the connection
2469 is vulnerable to man-in-the-middle (active or redirection) attacks.
2470 However, the data is integrity and privacy protected.
2472 @verbatiminclude examples/ex-client1.c
2474 @node Simple client example with X.509 certificate support
2475 @subsection Simple Client Example with @acronym{X.509} Certificate Support
2477 Let's assume now that we want to create a TCP client which
2478 communicates with servers that use @acronym{X.509} or
2479 @acronym{OpenPGP} certificate authentication. The following client is
2480 a very simple @acronym{TLS} client, it does not support session
2481 resuming, not even certificate verification. The TCP functions defined
2482 in this example are used in most of the other examples below, without
2485 @verbatiminclude examples/ex-client2.c
2487 @node Obtaining session information
2488 @subsection Obtaining Session Information
2490 Most of the times it is desirable to know the security properties of
2491 the current established session. This includes the underlying ciphers
2492 and the protocols involved. That is the purpose of the following
2493 function. Note that this function will print meaningful values only
2494 if called after a successful @ref{gnutls_handshake}.
2496 @verbatiminclude examples/ex-session-info.c
2498 @node Verifying peer's certificate
2499 @subsection Verifying Peer's Certificate
2502 A @acronym{TLS} session is not secure just after the handshake
2503 procedure has finished. It must be considered secure, only after the
2504 peer's certificate and identity have been verified. That is, you have
2505 to verify the signature in peer's certificate, the hostname in the
2506 certificate, and expiration dates. Just after this step you should
2507 treat the connection as being a secure one.
2509 @verbatiminclude examples/ex-rfc2818.c
2511 An other example is listed below which provides a more detailed
2512 verification output.
2514 @verbatiminclude examples/ex-verify.c
2516 @node Using a callback to select the certificate to use
2517 @subsection Using a Callback to Select the Certificate to Use
2519 There are cases where a client holds several certificate and key
2520 pairs, and may not want to load all of them in the credentials
2521 structure. The following example demonstrates the use of the
2522 certificate selection callback.
2524 @verbatiminclude examples/ex-cert-select.c
2526 @node Client with Resume capability example
2527 @subsection Client with Resume Capability Example
2528 @anchor{ex:resume-client}
2530 This is a modification of the simple client example. Here we
2531 demonstrate the use of session resumption. The client tries to connect
2532 once using @acronym{TLS}, close the connection and then try to
2533 establish a new connection using the previously negotiated data.
2535 @verbatiminclude examples/ex-client-resume.c
2537 @node Simple client example with SRP authentication
2538 @subsection Simple Client Example with @acronym{SRP} Authentication
2540 The following client is a very simple @acronym{SRP} @acronym{TLS}
2541 client which connects to a server and authenticates using a
2542 @emph{username} and a @emph{password}. The server may authenticate
2543 itself using a certificate, and in that case it has to be verified.
2545 @verbatiminclude examples/ex-client-srp.c
2547 @node Simple client example with TLS/IA support
2548 @subsection Simple Client Example with @acronym{TLS/IA} Support
2550 The following client is a simple client which uses the
2551 @acronym{TLS/IA} extension to authenticate with the server.
2553 @verbatiminclude examples/ex-client-tlsia.c
2555 @node Simple client example in C++
2556 @subsection Simple Client Example using the C++ API
2558 The following client is a simple example of a client client utilizing
2561 @verbatiminclude examples/ex-cxx.cpp
2563 @node Helper function for TCP connections
2564 @subsection Helper Function for TCP Connections
2566 This helper function abstracts away TCP connection handling from the
2567 other examples. It is required to build some examples.
2569 @verbatiminclude examples/tcp.c
2571 @node Server examples
2572 @section Server Examples
2574 This section contains examples of @acronym{TLS} and @acronym{SSL}
2575 servers, using @acronym{GnuTLS}.
2578 * Echo Server with X.509 authentication::
2579 * Echo Server with X.509 authentication II::
2580 * Echo Server with OpenPGP authentication::
2581 * Echo Server with SRP authentication::
2582 * Echo Server with anonymous authentication::
2585 @node Echo Server with X.509 authentication
2586 @subsection Echo Server with @acronym{X.509} Authentication
2588 This example is a very simple echo server which supports
2589 @acronym{X.509} authentication, using the RSA ciphersuites.
2591 @verbatiminclude examples/ex-serv1.c
2593 @node Echo Server with X.509 authentication II
2594 @subsection Echo Server with @acronym{X.509} Authentication II
2596 The following example is a server which supports @acronym{X.509}
2597 authentication. This server supports the export-grade cipher suites,
2598 the DHE ciphersuites and session resuming.
2600 @verbatiminclude examples/ex-serv-export.c
2602 @node Echo Server with OpenPGP authentication
2603 @subsection Echo Server with @acronym{OpenPGP} Authentication
2604 @cindex @acronym{OpenPGP} Server
2606 The following example is an echo server which supports
2607 @acronym{@acronym{OpenPGP}} key authentication. You can easily combine
2608 this functionality ---that is have a server that supports both
2609 @acronym{X.509} and @acronym{OpenPGP} certificates--- but we separated
2610 them to keep these examples as simple as possible.
2612 @verbatiminclude examples/ex-serv-pgp.c
2614 @node Echo Server with SRP authentication
2615 @subsection Echo Server with @acronym{SRP} Authentication
2617 This is a server which supports @acronym{SRP} authentication. It is
2618 also possible to combine this functionality with a certificate
2619 server. Here it is separate for simplicity.
2621 @verbatiminclude examples/ex-serv-srp.c
2623 @node Echo Server with anonymous authentication
2624 @subsection Echo Server with Anonymous Authentication
2626 This example server support anonymous authentication, and could be
2627 used to serve the example client for anonymous authentication.
2629 @verbatiminclude examples/ex-serv-anon.c
2631 @node Miscellaneous examples
2632 @section Miscellaneous Examples
2635 * Checking for an alert::
2636 * X.509 certificate parsing example::
2637 * Certificate request generation::
2638 * PKCS #12 structure generation::
2641 @node Checking for an alert
2642 @subsection Checking for an Alert
2644 This is a function that checks if an alert has been received in the
2647 @verbatiminclude examples/ex-alert.c
2649 @node X.509 certificate parsing example
2650 @subsection @acronym{X.509} Certificate Parsing Example
2651 @anchor{ex:x509-info}
2653 To demonstrate the @acronym{X.509} parsing capabilities an example program is
2654 listed below. That program reads the peer's certificate, and prints
2655 information about it.
2657 @verbatiminclude examples/ex-x509-info.c
2659 @node Certificate request generation
2660 @subsection Certificate Request Generation
2663 The following example is about generating a certificate request, and a
2664 private key. A certificate request can be later be processed by a CA,
2665 which should return a signed certificate.
2667 @verbatiminclude examples/ex-crq.c
2669 @node PKCS #12 structure generation
2670 @subsection @acronym{PKCS} #12 Structure Generation
2673 The following example is about generating a @acronym{PKCS} #12
2676 @verbatiminclude examples/ex-pkcs12.c
2678 @node Compatibility with the OpenSSL library
2679 @section Compatibility with the OpenSSL Library
2682 To ease @acronym{GnuTLS}' integration with existing applications, a
2683 compatibility layer with the widely used OpenSSL library is included
2684 in the @code{gnutls-openssl} library. This compatibility layer is not
2685 complete and it is not intended to completely reimplement the OpenSSL
2686 API with @acronym{GnuTLS}. It only provides source-level
2687 compatibility. There is currently no attempt to make it
2688 binary-compatible with OpenSSL.
2690 The prototypes for the compatibility functions are in the
2691 @file{gnutls/openssl.h} header file.
2693 Current limitations imposed by the compatibility layer include:
2697 @item Error handling is not thread safe.
2701 @node Opaque PRF Input TLS Extension
2702 @section Opaque PRF Input TLS Extension
2703 @cindex Opaque PRF Input
2705 GnuTLS supports the Opaque PRF Input TLS extension
2706 (@code{draft-rescorla-tls-opaque-prf-input-00.txt}). The API consists
2707 of one API for use in the client, @ref{gnutls_oprfi_enable_client},
2708 and one API for use in the server, @ref{gnutls_oprfi_enable_server}.
2709 You must invoke both functions before calling @ref{gnutls_handshake}.
2710 The server utilizes a callback function into the application. The
2711 callback can look at the random string provided by the client, and
2712 also set the server string. The string lengths must be equal
2713 according to the protocol.
2715 @node Keying Material Exporters
2716 @section Keying Material Exporters
2717 @cindex Keying Material Exporters
2718 @cindex Exporting Keying Material
2720 The TLS PRF can be used by other protocols to derive data. The API to
2721 use is @ref{gnutls_prf}. The function needs to be provided with the
2722 label in the parameter @code{label}, and the extra data to mix in the
2723 @code{extra} parameter. Depending on whether you want to mix in the
2724 client or server random data first, you can set the
2725 @code{server_random_first} parameter.
2727 For example, after establishing a TLS session using
2728 @ref{gnutls_handshake}, you can invoke the TLS PRF with this call:
2731 #define MYLABEL "EXPORTER-FOO"
2732 #define MYCONTEXT "some context data"
2734 rc = gnutls_prf (session, strlen (MYLABEL), MYLABEL, 0,
2735 strlen (MYCONTEXT), MYCONTEXT, 32, out);
2738 If you don't want to mix in the client/server random, there is a more
2739 low-level TLS PRF interface called @ref{gnutls_prf_raw}.
2741 @node Included programs
2742 @chapter Included Programs
2744 Included with @acronym{GnuTLS} are also a few command line tools that
2745 let you use the library for common tasks without writing an
2746 application. The applications are discussed in this chapter.
2749 * Invoking certtool::
2750 * Invoking gnutls-cli::
2751 * Invoking gnutls-cli-debug::
2752 * Invoking gnutls-serv::
2753 * Invoking psktool::
2754 * Invoking srptool::
2757 @node Invoking certtool
2758 @section Invoking certtool
2761 This is a program to generate @acronym{X.509} certificates, certificate
2762 requests, CRLs and private keys.
2766 Usage: certtool [options]
2767 -s, --generate-self-signed
2768 Generate a self-signed certificate.
2769 -c, --generate-certificate
2770 Generate a signed certificate.
2771 --generate-proxy Generate a proxy certificate.
2772 --generate-crl Generate a CRL.
2773 -u, --update-certificate
2774 Update a signed certificate.
2775 -p, --generate-privkey Generate a private key.
2776 -q, --generate-request Generate a PKCS #10 certificate
2778 -e, --verify-chain Verify a PEM encoded certificate chain.
2779 The last certificate in the chain must
2780 be a self signed one.
2781 --verify-crl Verify a CRL.
2782 --generate-dh-params Generate PKCS #3 encoded Diffie-Hellman
2784 --get-dh-params Get the included PKCS #3 encoded Diffie
2786 --load-privkey FILE Private key file to use.
2787 --load-request FILE Certificate request file to use.
2788 --load-certificate FILE
2789 Certificate file to use.
2790 --load-ca-privkey FILE Certificate authority's private key
2792 --load-ca-certificate FILE
2793 Certificate authority's certificate
2795 --password PASSWORD Password to use.
2796 -i, --certificate-info Print information on a certificate.
2797 -l, --crl-info Print information on a CRL.
2798 --p12-info Print information on a PKCS #12
2800 --p7-info Print information on a PKCS #7
2802 --smime-to-p7 Convert S/MIME to PKCS #7 structure.
2803 -k, --key-info Print information on a private key.
2804 --fix-key Regenerate the parameters in a private
2806 --to-p12 Generate a PKCS #12 structure.
2807 -8, --pkcs8 Use PKCS #8 format for private keys.
2809 --hash STR Hash algorithm to use for signing
2811 --export-ciphers Use weak encryption algorithms.
2812 --inder Use DER format for input certificates
2814 --outder Use DER format for output certificates
2816 --bits BITS specify the number of bits for key
2818 --outfile FILE Output file.
2819 --infile FILE Input file.
2820 --template FILE Template file to use for non
2821 interactive operation.
2822 -d, --debug LEVEL specify the debug level. Default is 1.
2823 -h, --help shows this help text
2824 -v, --version shows the program's version
2827 The program can be used interactively or non interactively by
2828 specifying the @code{--template} command line option. See below for an
2829 example of a template file.
2831 How to use certtool interactively:
2835 To generate parameters for Diffie-Hellman key exchange, use the command:
2837 $ certtool --generate-dh-params --outfile dh.pem
2841 To generate parameters for the RSA-EXPORT key exchange, use the command:
2843 $ certtool --generate-privkey --bits 512 --outfile rsa.pem
2851 To create a self signed certificate, use the command:
2853 $ certtool --generate-privkey --outfile ca-key.pem
2854 $ certtool --generate-self-signed --load-privkey ca-key.pem \
2855 --outfile ca-cert.pem
2858 Note that a self-signed certificate usually belongs to a certificate
2859 authority, that signs other certificates.
2862 To create a private key (RSA by default), run:
2865 $ certtool --generate-privkey --outfile key.pem
2868 To create a DSA private key, run:
2871 $ certtool --dsa --generate-privkey --outfile key-dsa.pem
2875 To generate a certificate using the private key, use the command:
2878 $ certtool --generate-certificate --load-privkey key.pem \
2879 --outfile cert.pem --load-ca-certificate ca-cert.pem \
2880 --load-ca-privkey ca-key.pem
2884 To create a certificate request (needed when the certificate is issued by
2885 another party), run:
2888 $ certtool --generate-request --load-privkey key.pem \
2889 --outfile request.pem
2893 To generate a certificate using the previous request, use the command:
2896 $ certtool --generate-certificate --load-request request.pem \
2897 --outfile cert.pem \
2898 --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem
2902 To view the certificate information, use:
2905 $ certtool --certificate-info --infile cert.pem
2909 To generate a @acronym{PKCS} #12 structure using the previous key and
2910 certificate, use the command:
2913 $ certtool --load-certificate cert.pem --load-privkey key.pem \
2914 --to-p12 --outder --outfile key.p12
2917 Some tools (reportedly web browsers) have problems with that file
2918 because it does not contain the CA certificate for the certificate.
2919 To work around that problem in the tool, you can use the
2920 @samp{--load-ca-certificate} parameter as follows:
2923 $ certtool --load-ca-certificate ca.pem \
2924 --load-certificate cert.pem --load-privkey key.pem \
2925 --to-p12 --outder --outfile key.p12
2929 Proxy certificate can be used to delegate your credential to a
2930 temporary, typically short-lived, certificate. To create one from the
2931 previously created certificate, first create a temporary key and then
2932 generate a proxy certificate for it, using the commands:
2935 $ certtool --generate-privkey > proxy-key.pem
2936 $ certtool --generate-proxy --load-ca-privkey key.pem \
2937 --load-privkey proxy-key.pem --load-certificate cert.pem \
2938 --outfile proxy-cert.pem
2942 To create an empty Certificate Revocation List (CRL) do:
2945 $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem --load-ca-certificate x509-ca.pem
2948 To create a CRL that contains some revoked certificates, place the
2949 certificates in a file and use @code{--load-certificate} as follows:
2952 $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem --load-ca-certificate x509-ca.pem --load-certificate revoked-certs.pem
2956 To verify a Certificate Revocation List (CRL) do:
2959 $ certtool --verify-crl --load-ca-certificate x509-ca.pem < crl.pem
2964 Certtool's template file format:
2969 Firstly create a file named 'cert.cfg' that contains the information
2970 about the certificate. An example file is listed below.
2976 $ certtool --generate-certificate cert.pem --load-privkey key.pem \
2977 --template cert.cfg \
2978 --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem
2983 An example certtool template file:
2986 # X.509 Certificate options
2990 # The organization of the subject.
2991 organization = "Koko inc."
2993 # The organizational unit of the subject.
2994 unit = "sleeping dept."
2996 # The locality of the subject.
2999 # The state of the certificate owner.
3002 # The country of the subject. Two letter code.
3005 # The common name of the certificate owner.
3008 # A user id of the certificate owner.
3011 # If the supported DN OIDs are not adequate you can set
3013 # For example set the X.520 Title and the X.520 Pseudonym
3014 # by using OID and string pairs.
3015 #dn_oid = "2.5.4.12" "Dr." "2.5.4.65" "jackal"
3017 # This is deprecated and should not be used in new
3019 # pkcs9_email = "none@@none.org"
3021 # The serial number of the certificate
3024 # In how many days, counting from today, this certificate will expire.
3025 expiration_days = 700
3027 # X.509 v3 extensions
3029 # A dnsname in case of a WWW server.
3030 #dns_name = "www.none.org"
3031 #dns_name = "www.morethanone.org"
3033 # An IP address in case of a server.
3034 #ip_address = "192.168.1.1"
3036 # An email in case of a person
3037 email = "none@@none.org"
3039 # An URL that has CRLs (certificate revocation lists)
3040 # available. Needed in CA certificates.
3041 #crl_dist_points = "http://www.getcrl.crl/getcrl/"
3043 # Whether this is a CA certificate or not
3046 # Whether this certificate will be used for a TLS client
3049 # Whether this certificate will be used for a TLS server
3052 # Whether this certificate will be used to sign data (needed
3053 # in TLS DHE ciphersuites).
3056 # Whether this certificate will be used to encrypt data (needed
3057 # in TLS RSA ciphersuites). Note that it is prefered to use different
3058 # keys for encryption and signing.
3061 # Whether this key will be used to sign other certificates.
3064 # Whether this key will be used to sign CRLs.
3067 # Whether this key will be used to sign code.
3070 # Whether this key will be used to sign OCSP data.
3073 # Whether this key will be used for time stamping.
3077 @node Invoking gnutls-cli
3078 @section Invoking gnutls-cli
3081 Simple client program to set up a TLS connection to some other
3082 computer. It sets up a TLS connection and forwards data from the
3083 standard input to the secured socket and vice versa.
3087 Usage: gnutls-cli [options] hostname
3089 -d, --debug integer Enable debugging
3090 -r, --resume Connect, establish a session. Connect
3091 again and resume this session.
3092 -s, --starttls Connect, establish a plain session and
3093 start TLS when EOF or a SIGALRM is
3095 --crlf Send CR LF instead of LF.
3096 --x509fmtder Use DER format for certificates to read
3098 -f, --fingerprint Send the openpgp fingerprint, instead
3100 --disable-extensions Disable all the TLS extensions.
3101 --print-cert Print the certificate in PEM format.
3102 --recordsize integer The maximum record size to advertize.
3103 -V, --verbose More verbose output.
3104 --ciphers cipher1 cipher2...
3106 --protocols protocol1 protocol2...
3107 Protocols to enable.
3108 --comp comp1 comp2... Compression methods to enable.
3109 --macs mac1 mac2... MACs to enable.
3110 --kx kx1 kx2... Key exchange methods to enable.
3111 --ctypes certType1 certType2...
3112 Certificate types to enable.
3113 --priority PRIORITY STRING
3115 --x509cafile FILE Certificate file to use.
3116 --x509crlfile FILE CRL file to use.
3117 --pgpkeyfile FILE PGP Key file to use.
3118 --pgpkeyring FILE PGP Key ring file to use.
3119 --pgpcertfile FILE PGP Public Key (certificate) file to
3121 --pgpsubkey HEX|auto PGP subkey to use.
3122 --x509keyfile FILE X.509 key file to use.
3123 --x509certfile FILE X.509 Certificate file to use.
3124 --srpusername NAME SRP username to use.
3125 --srppasswd PASSWD SRP password to use.
3126 --pskusername NAME PSK username to use.
3127 --pskkey KEY PSK key (in hex) to use.
3128 --opaque-prf-input DATA
3129 Use Opaque PRF Input DATA.
3130 -p, --port PORT The port to connect to.
3131 --insecure Don't abort program if server
3132 certificate can't be validated.
3133 -l, --list Print a list of the supported
3134 algorithms and modes.
3135 -h, --help prints this help
3136 -v, --version prints the program's version number
3139 To connect to a server using PSK authentication, you may use something
3143 $ gnutls-cli -p 5556 test.gnutls.org --pskusername jas --pskkey 9e32cf7786321a828ef7668f09fb35db --priority NORMAL:+PSK:-RSA:-DHE-RSA -d 4711
3147 * Example client PSK connection::
3150 @node Example client PSK connection
3151 @subsection Example client PSK connection
3154 If your server only supports the PSK ciphersuite, connecting to it
3155 should be as simple as connecting to the server:
3158 $ ./gnutls-cli -p 5556 localhost
3159 Resolving 'localhost'...
3160 Connecting to '127.0.0.1:5556'...
3161 - PSK client callback. PSK hint 'psk_identity_hint'
3162 Enter PSK identity: psk_identity
3164 - PSK authentication. PSK hint 'psk_identity_hint'
3167 - Cipher: AES-128-CBC
3170 - Handshake was completed
3172 - Simple Client Mode:
3175 If the server supports several cipher suites, you may need to force it
3176 to chose PSK by using a cipher priority parameter such as
3177 @code{--priority NORMAL:+PSK:-RSA:-DHE-RSA:-DHE-PSK}.
3180 Instead of using the Netconf-way to derive the PSK key from a
3181 password, you can also give the PSK username and key directly on the
3185 $ ./gnutls-cli -p 5556 localhost --pskusername psk_identity --pskkey 88f3824b3e5659f52d00e959bacab954b6540344
3186 Resolving 'localhost'...
3187 Connecting to '127.0.0.1:5556'...
3188 - PSK authentication. PSK hint 'psk_identity_hint'
3191 - Cipher: AES-128-CBC
3194 - Handshake was completed
3196 - Simple Client Mode:
3199 By keeping the @code{--pskusername} parameter and removing the
3200 @code{--pskkey} parameter, it will query only for the password during
3203 @node Invoking gnutls-cli-debug
3204 @section Invoking gnutls-cli-debug
3205 @cindex gnutls-cli-debug
3207 This program was created to assist in debugging @acronym{GnuTLS}, but
3208 it might be useful to extract a @acronym{TLS} server's capabilities.
3209 It's purpose is to connect onto a @acronym{TLS} server, perform some
3210 tests and print the server's capabilities. If called with the `-v'
3211 parameter a more checks will be performed. An example output is:
3214 crystal:/cvs/gnutls/src$ ./gnutls-cli-debug localhost -p 5556
3215 Resolving 'localhost'...
3216 Connecting to '127.0.0.1:5556'...
3217 Checking for TLS 1.1 support... yes
3218 Checking fallback from TLS 1.1 to... N/A
3219 Checking for TLS 1.0 support... yes
3220 Checking for SSL 3.0 support... yes
3221 Checking for version rollback bug in RSA PMS... no
3222 Checking for version rollback bug in Client Hello... no
3223 Checking whether we need to disable TLS 1.0... N/A
3224 Checking whether the server ignores the RSA PMS version... no
3225 Checking whether the server can accept Hello Extensions... yes
3226 Checking whether the server can accept cipher suites not in SSL 3.0 spec... yes
3227 Checking whether the server can accept a bogus TLS record version in the client hello... yes
3228 Checking for certificate information... N/A
3229 Checking for trusted CAs... N/A
3230 Checking whether the server understands TLS closure alerts... yes
3231 Checking whether the server supports session resumption... yes
3232 Checking for export-grade ciphersuite support... no
3233 Checking RSA-export ciphersuite info... N/A
3234 Checking for anonymous authentication support... no
3235 Checking anonymous Diffie-Hellman group info... N/A
3236 Checking for ephemeral Diffie-Hellman support... no
3237 Checking ephemeral Diffie-Hellman group info... N/A
3238 Checking for AES cipher support (TLS extension)... yes
3239 Checking for 3DES cipher support... yes
3240 Checking for ARCFOUR 128 cipher support... yes
3241 Checking for ARCFOUR 40 cipher support... no
3242 Checking for MD5 MAC support... yes
3243 Checking for SHA1 MAC support... yes
3244 Checking for ZLIB compression support (TLS extension)... yes
3245 Checking for LZO compression support (GnuTLS extension)... yes
3246 Checking for max record size (TLS extension)... yes
3247 Checking for SRP authentication support (TLS extension)... yes
3248 Checking for OpenPGP authentication support (TLS extension)... no
3251 @node Invoking gnutls-serv
3252 @section Invoking gnutls-serv
3255 Simple server program that listens to incoming TLS connections.
3259 Usage: gnutls-serv [options]
3261 -d, --debug integer Enable debugging
3262 -g, --generate Generate Diffie-Hellman Parameters.
3263 -p, --port integer The port to connect to.
3264 -q, --quiet Suppress some messages.
3265 --nodb Does not use the resume database.
3266 --http Act as an HTTP Server.
3267 --echo Act as an Echo Server.
3268 --dhparams FILE DH params file to use.
3269 --x509fmtder Use DER format for certificates
3270 --x509cafile FILE Certificate file to use.
3271 --x509crlfile FILE CRL file to use.
3272 --pgpkeyring FILE PGP Key ring file to use.
3273 --pgpkeyfile FILE PGP Key file to use.
3274 --pgpcertfile FILE PGP Public Key (certificate) file to
3276 --pgpsubkey HEX|auto PGP subkey to use.
3277 --x509keyfile FILE X.509 key file to use.
3278 --x509certfile FILE X.509 Certificate file to use.
3279 --x509dsakeyfile FILE Alternative X.509 key file to use.
3280 --x509dsacertfile FILE Alternative X.509 certificate file to
3282 -r, --require-cert Require a valid certificate.
3283 -a, --disable-client-cert
3284 Disable request for a client
3286 --pskpasswd FILE PSK password file to use.
3287 --pskhint HINT PSK identity hint to use.
3288 --srppasswd FILE SRP password file to use.
3289 --srppasswdconf FILE SRP password conf file to use.
3290 --opaque-prf-input DATA
3291 Use Opaque PRF Input DATA.
3292 --ciphers cipher1 cipher2...
3294 --protocols protocol1 protocol2...
3295 Protocols to enable.
3296 --comp comp1 comp2... Compression methods to enable.
3297 --macs mac1 mac2... MACs to enable.
3298 --kx kx1 kx2... Key exchange methods to enable.
3299 --ctypes certType1 certType2...
3300 Certificate types to enable.
3301 --priority PRIORITY STRING
3303 -l, --list Print a list of the supported
3304 algorithms and modes.
3305 -h, --help prints this help
3306 -v, --version prints the program's version number
3309 @subsection Setting Up a Test HTTPS Server
3310 @cindex HTTPS server
3311 @cindex debug server
3313 Running your own TLS server based on GnuTLS can be useful when
3314 debugging clients and/or GnuTLS itself. This section describes how to
3315 use @code{gnutls-serv} as a simple HTTPS server.
3317 The most basic server can be started as:
3323 It will only support anonymous ciphersuites, which many TLS clients
3326 The next step is to add support for X.509. First we generate a CA:
3329 certtool --generate-privkey > x509-ca-key.pem
3330 echo 'cn = GnuTLS test CA' > ca.tmpl
3331 echo 'ca' >> ca.tmpl
3332 echo 'cert_signing_key' >> ca.tmpl
3333 certtool --generate-self-signed --load-privkey x509-ca-key.pem \
3334 --template ca.tmpl --outfile x509-ca.pem
3338 Then generate a server certificate. Remember to change the dns_name
3339 value to the name of your server host, or skip that command to avoid
3343 certtool --generate-privkey > x509-server-key.pem
3344 echo 'organization = GnuTLS test server' > server.tmpl
3345 echo 'cn = test.gnutls.org' >> server.tmpl
3346 echo 'tls_www_server' >> server.tmpl
3347 echo 'encryption_key' >> server.tmpl
3348 echo 'signing_key' >> server.tmpl
3349 echo 'dns_name = test.gnutls.org' >> server.tmpl
3350 certtool --generate-certificate --load-privkey x509-server-key.pem \
3351 --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
3352 --template server.tmpl --outfile x509-server.pem
3356 For use in the client, you may want to generate a client certificate
3360 certtool --generate-privkey > x509-client-key.pem
3361 echo 'cn = GnuTLS test client' > client.tmpl
3362 echo 'tls_www_client' >> client.tmpl
3363 echo 'encryption_key' >> client.tmpl
3364 echo 'signing_key' >> client.tmpl
3365 certtool --generate-certificate --load-privkey x509-client-key.pem \
3366 --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
3367 --template client.tmpl --outfile x509-client.pem
3371 To be able to import the client key/certificate into some
3372 applications, you will need to convert them into a PKCS#12 structure.
3373 This also encrypts the security sensitive key with a password.
3376 certtool --to-p12 --load-ca-certificate x509-ca.pem --load-privkey x509-client-key.pem --load-certificate x509-client.pem --outder --outfile x509-client.p12
3379 For icing, we'll create a proxy certificate for the client too.
3382 certtool --generate-privkey > x509-proxy-key.pem
3383 echo 'cn = GnuTLS test client proxy' > proxy.tmpl
3384 certtool --generate-proxy --load-privkey x509-proxy-key.pem \
3385 --load-ca-certificate x509-client.pem --load-ca-privkey x509-client-key.pem \
3386 --load-certificate x509-client.pem --template proxy.tmpl \
3387 --outfile x509-proxy.pem
3391 Then start the server again:
3394 gnutls-serv --http \
3395 --x509cafile x509-ca.pem \
3396 --x509keyfile x509-server-key.pem \
3397 --x509certfile x509-server.pem
3400 Try connecting to the server using your web browser. Note that the
3401 server listens to port 5556 by default.
3403 While you are at it, to allow connections using DSA, you can also
3404 create a DSA key and certificate for the server. These credentials
3405 will be used in the final example below.
3408 certtool --generate-privkey --dsa > x509-server-key-dsa.pem
3409 certtool --generate-certificate --load-privkey x509-server-key-dsa.pem \
3410 --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
3411 --template server.tmpl --outfile x509-server-dsa.pem
3415 The next step is to create OpenPGP credentials for the server.
3419 ...enter whatever details you want, use 'test.gnutls.org' as name...
3422 Make a note of the OpenPGP key identifier of the newly generated key,
3423 here it was @code{5D1D14D8}. You will need to export the key for
3424 GnuTLS to be able to use it.
3427 gpg -a --export 5D1D14D8 > openpgp-server.txt
3428 gpg --export 5D1D14D8 > openpgp-server.bin
3429 gpg --export-secret-keys 5D1D14D8 > openpgp-server-key.bin
3430 gpg -a --export-secret-keys 5D1D14D8 > openpgp-server-key.txt
3433 Let's start the server with support for OpenPGP credentials:
3436 gnutls-serv --http \
3437 --pgpkeyfile openpgp-server-key.txt \
3438 --pgpcertfile openpgp-server.txt
3441 The next step is to add support for SRP authentication.
3444 srptool --create-conf srp-tpasswd.conf
3445 srptool --passwd-conf srp-tpasswd.conf --username jas --passwd srp-passwd.txt
3446 Enter password: [TYPE "foo"]
3449 Start the server with SRP support:
3452 gnutls-serv --http \
3453 --srppasswdconf srp-tpasswd.conf \
3454 --srppasswd srp-passwd.txt
3457 Let's also add support for PSK.
3460 $ psktool --passwd psk-passwd.txt
3463 Start the server with PSK support:
3466 gnutls-serv --http \
3467 --pskpasswd psk-passwd.txt
3470 Finally, we start the server with all the earlier parameters and you
3474 gnutls-serv --http \
3475 --x509cafile x509-ca.pem \
3476 --x509keyfile x509-server-key.pem \
3477 --x509certfile x509-server.pem \
3478 --x509dsakeyfile x509-server-key-dsa.pem \
3479 --x509dsacertfile x509-server-dsa.pem \
3480 --pgpkeyfile openpgp-server-key.txt \
3481 --pgpcertfile openpgp-server.txt \
3482 --srppasswdconf srp-tpasswd.conf \
3483 --srppasswd srp-passwd.txt \
3484 --pskpasswd psk-passwd.txt
3488 * Example server PSK connection::
3491 @node Example server PSK connection
3492 @subsection Example server PSK connection
3495 To set up a PSK server with @code{gnutls-serv} you need to create PSK
3496 password file (@pxref{Invoking psktool}). In the example below, I
3497 type @code{password} at the prompt.
3500 $ ./psktool -u psk_identity -p psks.txt -n psk_identity_hint
3502 Key stored to psks.txt
3504 psk_identity:88f3824b3e5659f52d00e959bacab954b6540344
3508 After this, start the server pointing to the password file. We
3512 $ ./gnutls-serv --pskpasswd psks.txt --pskhint psk_identity_hint --priority NORMAL:-DHE-PSK
3513 Set static Diffie-Hellman parameters, consider --dhparams.
3514 Echo Server ready. Listening to port '5556'.
3517 You can now connect to the server using a PSK client (@pxref{Example
3518 client PSK connection}).
3520 @node Invoking psktool
3521 @section Invoking psktool
3524 This is a program to manage @acronym{PSK} username and keys.
3528 Usage : psktool [options]
3529 -u, --username username
3531 -p, --passwd FILE specify a password file.
3532 -n, --netconf-hint HINT
3533 derive key from Netconf password, using
3534 HINT as the psk_identity_hint.
3535 -s, --keysize SIZE specify the key size in bytes.
3536 -v, --version prints the program's version number
3537 -h, --help shows this help text
3540 Normally the file will generate random keys for the indicate username.
3541 You may also derive PSK keys from passwords, using the algorithm
3542 specified in @file{draft-ietf-netconf-tls-02.txt}. The algorithm
3543 needs a PSK identity hint, which you specify using
3544 @code{--netconf-hint}. To derive a PSK key from a password with an
3545 empty PSK identity hint, using @code{--netconf-hint ""}.
3547 @node Invoking srptool
3548 @section Invoking srptool
3552 The @file{srptool} is a very simple program that emulates the programs
3553 in the @emph{Stanford SRP libraries}, see
3554 @url{http://srp.stanford.edu/}. It is intended for use in places
3555 where you don't expect @acronym{SRP} authentication to be the used for
3558 Traditionally @emph{libsrp} used two files. One called @code{tpasswd}
3559 which holds usernames and verifiers, and @code{tpasswd.conf} which
3560 holds generators and primes.
3567 To create tpasswd.conf which holds the g and n values for
3568 @acronym{SRP} protocol (generator and a large prime), run:
3571 $ srptool --create-conf /etc/tpasswd.conf
3575 This command will create /etc/tpasswd and will add user 'test' (you
3576 will also be prompted for a password). Verifiers are stored by
3577 default in the way libsrp expects.
3580 $ srptool --passwd /etc/tpasswd \
3581 --passwd-conf /etc/tpasswd.conf -u test
3585 This command will check against a password. If the password matches
3586 the one in /etc/tpasswd you will get an ok.
3589 $ srptool --passwd /etc/tpasswd \
3590 --passwd-conf /etc/tpasswd.conf --verify -u test
3595 @node Function reference
3596 @chapter Function Reference
3597 @cindex Function reference
3601 * X.509 certificate functions::
3602 * GnuTLS-extra functions::
3603 * OpenPGP functions::
3604 * TLS Inner Application (TLS/IA) functions::
3605 * Error codes and descriptions::
3608 @node Core functions
3609 @section Core Functions
3611 The prototypes for the following functions lie in
3612 @file{gnutls/gnutls.h}.
3614 @include gnutls-api.texi
3616 @node X.509 certificate functions
3617 @section @acronym{X.509} Certificate Functions
3618 @anchor{sec:x509api}
3619 @cindex @acronym{X.509} Functions
3621 The following functions are to be used for @acronym{X.509} certificate handling.
3622 Their prototypes lie in @file{gnutls/x509.h}.
3624 @include x509-api.texi
3626 @node GnuTLS-extra functions
3627 @section @acronym{GnuTLS-extra} Functions
3628 @cindex @acronym{GnuTLS-extra} functions
3630 These functions are only available in the GPLv3+ version of the
3631 library called @code{gnutls-extra}. The prototypes for this library
3632 lie in @file{gnutls/extra.h}.
3634 @include extra-api.texi
3636 @node OpenPGP functions
3637 @section @acronym{OpenPGP} Functions
3638 @cindex @acronym{OpenPGP} functions
3639 @anchor{sec:openpgpapi}
3641 The following functions are to be used for @acronym{OpenPGP}
3642 certificate handling. Their prototypes lie in
3643 @file{gnutls/openpgp.h}.
3645 @include pgp-api.texi
3647 @node TLS Inner Application (TLS/IA) functions
3648 @section @acronym{TLS} Inner Application (@acronym{TLS/IA}) Functions
3649 @cindex @acronym{TLS} Inner Application (@acronym{TLS/IA}) functions
3650 @cindex Inner Application (@acronym{TLS/IA}) functions
3652 The following functions are used for @acronym{TLS} Inner Application
3653 (@acronym{TLS/IA}). Their prototypes lie in @file{gnutls/extra.h}.
3654 You need to link with @file{libgnutls-extra} to be able to use these
3655 functions (@pxref{GnuTLS-extra functions}).
3657 The typical control flow in an TLS/IA client (that would not require
3658 an Application Phase for resumed sessions) would be similar to the
3662 int client_avp (gnuls_session_t *session, void *ptr,
3663 const char *last, size_t lastlen,
3664 char **new, size_t *newlen)
3671 gnutls_ia_client_credentials_t iacred;
3673 gnutls_init (&session, GNUTLS_CLIENT);
3675 /* Enable TLS/IA. */
3676 gnutls_ia_allocate_client_credentials(&iacred);
3677 gnutls_ia_set_client_avp_function(iacred, client_avp);
3678 gnutls_credentials_set (session, GNUTLS_CRD_IA, iacred);
3680 ret = gnutls_handshake (session);
3681 // Error handling...
3683 if (gnutls_ia_handshake_p (session))
3685 ret = gnutls_ia_handshake (session);
3686 // Error handling...
3690 See below for detailed descriptions of all the functions used above.
3692 The function @code{client_avp} would have to be implemented by your
3693 application. The function is responsible for handling the AVP data.
3694 See @code{gnutls_ia_set_client_avp_function} below for more
3695 information on how that function should be implemented.
3697 The control flow in a typical server is similar to the above, use
3698 @code{gnutls_ia_server_credentials_t} instead of
3699 @code{gnutls_ia_client_credentials_t}, and replace the call to the
3700 client functions with the corresponding server functions.
3702 @include ia-api.texi
3704 @node Error codes and descriptions
3705 @section Error Codes and Descriptions
3706 @anchor{Error Codes}
3709 The error codes used throughout the library are described below. The
3710 return code @code{GNUTLS_E_SUCCESS} indicate successful operation, and
3711 is guaranteed to have the value 0, so you can use it in logical
3714 @include error_codes.texi
3716 @node All the supported ciphersuites in GnuTLS
3717 @chapter All the Supported Ciphersuites in @acronym{GnuTLS}
3718 @anchor{ciphersuites}
3719 @cindex Ciphersuites
3721 @include algorithms.texi
3723 Some additional information regarding some of the algorithms:
3727 RSA is public key cryptosystem designed by Ronald Rivest, Adi Shamir
3728 and Leonard Adleman. It can be used with any hash functions.
3731 DSA is the USA's Digital Signature Standard. It uses only the SHA-1
3735 MD2 is a cryptographic hash algorithm designed by Ron Rivest. It is
3736 optimized for 8-bit processors. Outputs 128 bits of data. There are
3737 no known weaknesses of this algorithm but since this algorithm is
3738 rarely used and not really studied it should not be used today.
3741 MD5 is a cryptographic hash algorithm designed by Ron Rivest. Outputs
3742 128 bits of data. It is considered to be broken.
3745 SHA is a cryptographic hash algorithm designed by NSA. Outputs 160
3746 bits of data. It is also considered to be broken, though no practical
3747 attacks have been found.
3750 RIPEMD is a cryptographic hash algorithm developed in the framework of
3751 the EU project RIPE. Outputs 160 bits of data.
3762 @node Internal architecture of GnuTLS
3763 @chapter Internal Architecture of GnuTLS
3764 @cindex Internal architecture
3766 This chapter is to give a brief description of the
3767 way @acronym{GnuTLS} works. The focus is to give an idea
3768 to potential developers and those who want to know what
3769 happens inside the black box.
3772 * The TLS Protocol::
3773 * TLS Handshake Protocol::
3774 * TLS Authentication Methods::
3775 * TLS Extension Handling::
3776 * Cryptographic Backend::
3779 @node The TLS Protocol
3780 @section The TLS Protocol
3781 The main needs for the TLS protocol to be used are
3782 shown in the image below.
3784 @image{gnutls-client-server-use-case,9cm}
3786 This is being accomplished by the following object diagram.
3787 Note that since @acronym{GnuTLS} is being developed in C
3788 object are just structures with attributes. The operations listed
3789 are functions that require the first parameter to be that object.
3790 @image{gnutls-objects,15cm}
3792 @node TLS Handshake Protocol
3793 @section TLS Handshake Protocol
3794 The @acronym{GnuTLS} handshake protocol is implemented as a state
3795 machine that waits for input or returns immediately when the non-blocking
3796 transport layer functions are used. The main idea is shown in the following
3799 @image{gnutls-handshake-state,9cm}
3801 Also the way the input is processed varies per ciphersuite. Several
3802 implementations of the internal handlers are available and
3803 @ref{gnutls_handshake} only multiplexes the input to the appropriate
3804 handler. For example a @acronym{PSK} ciphersuite has a different
3805 implementation of the @code{process_client_key_exchange} than a
3806 certificate ciphersuite.
3808 @image{gnutls-handshake-sequence,12cm}
3810 @node TLS Authentication Methods
3811 @section TLS Authentication Methods
3812 In @acronym{GnuTLS} authentication methods can be implemented quite
3813 easily. Since the required changes to add a new authentication method
3814 affect only the handshake protocol, a simple interface is used. An
3815 authentication method needs only to implement the functions as seen in
3818 @image{gnutls-mod_auth_st,12cm}
3820 The functions that need to be implemented are the ones responsible for
3821 interpreting the handshake protocol messages. It is common for such
3822 functions to read data from one or more @code{credentials_t}
3823 structures@footnote{such as the
3824 @code{gnutls_certificate_credentials_t} structures} and write data,
3825 such as certificates, usernames etc. to @code{auth_info_t} structures.
3827 Simple examples of existing authentication methods can be seen in
3828 @code{auth_psk.c} for PSK ciphersuites and @code{auth_srp.c} for SRP
3829 ciphersuites. After implementing these functions the structure holding
3830 its pointers has to be registered in @code{gnutls_algorithms.c} in the
3831 @code{_gnutls_kx_algorithms} structure.
3833 @node TLS Extension Handling
3834 @section TLS Extension Handling
3835 As with authentication methods, the TLS extensions handlers can be
3836 implemented using the following interface.
3838 @image{gnutls-extensions_st,12cm}
3840 Here there are two functions, one for receiving the extension data
3841 and one for sending. These functions have to check internally whether
3842 they operate in client or server side.
3844 A simple example of an extension handler can be seen in
3845 @code{ext_srp.c} After implementing these functions, together with the
3846 extension number they handle, they have to be registered in
3847 @code{gnutls_extensions.c} in the @code{_gnutls_extensions} structure.
3849 @subsection Adding a New TLS Extension
3851 Adding support for a new TLS extension is done from time to time, and
3852 the process to do so is not difficult. Here are the steps you need to
3853 follow if you wish to do this yourself. For sake of discussion, let's
3854 consider adding support for the hypothetical TLS extension
3859 @item Add @code{configure} option like @code{--enable-foobar} or @code{--disable-foobar}.
3861 Which to chose depends on whether you intend to make the extension be
3862 enabled by default. Look at existing checks (i.e., SRP, authz) for
3863 how to model the code. For example:
3866 AC_MSG_CHECKING([whether to disable foobar support])
3867 AC_ARG_ENABLE(foobar,
3868 AS_HELP_STRING([--disable-foobar],
3869 [disable foobar support]),
3870 ac_enable_foobar=no)
3871 if test x$ac_enable_foobar != xno; then
3873 AC_DEFINE(ENABLE_FOOBAR, 1, [enable foobar])
3878 AM_CONDITIONAL(ENABLE_FOOBAR, test "$ac_enable_foobar" != "no")
3881 These lines should go in @code{lib/m4/hooks.m4}.
3883 @item Add IANA extension value to @code{extensions_t} in @code{gnutls_int.h}.
3885 A good name for the value would be GNUTLS_EXTENSION_FOOBAR. Check
3886 with @url{http://www.iana.org/assignments/tls-extensiontype-values}
3887 for allocated values. For experiments, you could pick a number but
3888 remember that some consider it a bad idea to deploy such modified
3889 version since it will lead to interoperability problems in the future
3890 when the IANA allocates that number to someone else, or when the
3891 foobar protocol is allocated another number.
3893 @item Add an entry to @code{_gnutls_extensions} in @code{gnutls_extensions.c}.
3895 A typical entry would be:
3904 ret = gnutls_ext_register (GNUTLS_EXTENSION_FOOBAR,
3907 _gnutls_foobar_recv_params,
3908 _gnutls_foobar_send_params);
3909 if (ret != GNUTLS_E_SUCCESS)
3914 The GNUTLS_EXTENSION_FOOBAR is the integer value you added to
3915 @code{gnutls_int.h} earlier. The two functions are new functions that
3916 you will need to implement, most likely you'll need to add an
3917 @code{#include "ext_foobar.h"} as well.
3919 @item Add new files @code{ext_foobar.c} and @code{ext_foobar.h} that implements the extension.
3921 The functions you are responsible to add are those mentioned in the
3922 previous step. As a starter, you could add this:
3926 _gnutls_foobar_recv_params (gnutls_session_t session,
3927 const opaque * data,
3934 _gnutls_foobar_send_params (gnutls_session_t session,
3942 The @code{_gnutls_foobar_recv_params} function is responsible for
3943 parsing incoming extension data (both in the client and server).
3945 The @code{_gnutls_foobar_send_params} function is responsible for
3946 sending extension data (both in the client and server).
3948 If you receive length fields that doesn't match, return
3949 @code{GNUTLS_E_UNEXPECTED_PACKET_LENGTH}. If you receive invalid
3950 data, return @code{GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER}. You can use
3951 other error codes too. Return 0 on success.
3953 The function typically store some information in the @code{session}
3954 variable for later usage. If you need to add new fields there, check
3955 @code{tls_ext_st} in @code{gnutls_int.h} and compare with existing TLS
3956 extension specific variables.
3958 Recall that both the client and server both send and receives
3959 parameters, and your code most likely will need to do different things
3960 depending on which mode it is in. It may be useful to make this
3961 distinction explicit in the code. Thus, for example, a better
3962 template than above would be:
3966 _gnutls_foobar_recv_params (gnutls_session_t session,
3967 const opaque * data,
3970 if (session->security_parameters.entity == GNUTLS_CLIENT)
3971 return foobar_recv_client (session, data, data_size);
3973 return foobar_recv_server (session, data, data_size);
3977 _gnutls_foobar_send_params (gnutls_session_t session,
3981 if (session->security_parameters.entity == GNUTLS_CLIENT)
3982 return foobar_send_client (session, data, data_size);
3984 return foobar_send_server (session, data, data_size);
3988 The functions used would be declared as @code{static} functions, of
3989 the appropriate prototype, in the same file.
3991 When adding the files, you'll need to add them to @code{Makefile.am}
3992 as well, for example:
3996 COBJECTS += ext_foobar.c
3997 HFILES += ext_foobar.h
4001 @item Add API functions to enable/disable the extension.
4003 Normally the client will have one API to request use of the extension,
4004 and setting some extension specific data. The server will have one
4005 API to let the library know that it is willing to accept the
4006 extension, often this is implemented through a callback but it doesn't
4009 The APIs need to be added to @code{includes/gnutls/gnutls.h} or
4010 @code{includes/gnutls/extra.h} as appropriate. It is recommended that
4011 if you don't have a requirement to use the LGPLv2.1+ license for your
4012 extension, that you place your work under the GPLv3+ license and thus
4013 in the libgnutls-extra library.
4015 You can implement the API function in the @code{ext_foobar.c} file, or
4016 if that file ends up becoming rather larger, add a
4017 @code{gnutls_foobar.c} file.
4021 @section Certificate Handling
4022 What is provided by the certificate handling functions
4023 is summarized in the following diagram.
4025 @image{gnutls-certificate-user-use-case,12cm}
4027 @node Cryptographic Backend
4028 @section Cryptographic Backend
4029 Several new systems provide hardware assisted cryptographic algorithm
4030 implementations that offer implementations some orders of magnitude
4031 faster than the software. For this reason in current releases of
4032 GnuTLS it is possible to override parts of the crypto backend or the
4033 whole. It is possible to override them both at runtime and compile
4034 time, however here we will discuss the runtime possibility. The API
4035 available for this functionality is in @code{gnutls/crypto.h} header
4038 @subsection Override specific algorithms
4039 When an optimized implementation of a single algorithm is available,
4040 say a hardware assisted version of @acronym{AES-CBC} then the
4041 following functions can be used to register those algorithms.
4045 @item @ref{gnutls_crypto_single_cipher_register2}
4046 To register a cipher algorithm.
4048 @item @ref{gnutls_crypto_single_mac_register2}
4049 To register a MAC algorithm.
4051 @ref{gnutls_crypto_single_digest_register2}
4052 To register a digest (hash) algorithm.
4056 Those registration functions will only replace the specified algorithm
4057 and leave the rest of subsystem intact.
4059 @subsection Override parts of the backend
4060 In some systems, such as embedded ones, it might be desirable to
4061 override big parts of the cryptographic backend, or even all of
4062 them. For this reason the following functions are provided.
4066 @item @ref{gnutls_crypto_cipher_register2}
4067 To override the cryptographic algorithms backend.
4069 @item @ref{gnutls_crypto_mac_register2}
4070 To override the MAC algorithms backend.
4072 @item @ref{gnutls_crypto_digest_register2}
4073 To override the digest algorithms backend.
4075 @item @ref{gnutls_crypto_rnd_register2}
4076 To override the random number generator backend.
4078 @item @ref{gnutls_crypto_bigint_register2}
4079 To override the big number number operations backend.
4081 @item @ref{gnutls_crypto_pk_register2}
4082 To override the public key encryption backend. This is tight to the
4083 big number operations so either both of them should be updated or care
4084 must be taken to use the same format.
4088 If all of them are used then GnuTLS will no longer use libgcrypt.
4090 @node Copying Information
4091 @appendix Copying Information
4094 * GNU Free Documentation License:: License for copying this manual.
4095 * GNU LGPL:: License for copying the core GnuTLS library.
4096 * GNU GPL:: License for copying GNUTLS extra and tools.
4099 @node GNU Free Documentation License
4100 @appendixsec GNU Free Documentation License
4102 @cindex FDL, GNU Free Documentation License
4104 @include fdl-1.3.texi
4107 @appendixsec GNU Lesser General Public License
4108 @cindex LGPL, GNU Lesser General Public License
4109 @cindex License, GNU LGPL
4111 @include lgpl-2.1.texi
4114 @appendixsec GNU General Public License
4115 @cindex GPL, GNU General Public License
4116 @cindex License, GNU GPL
4118 @include gpl-3.0.texi
4121 @unnumbered Bibliography
4125 @item @anchor{CBCATT}[CBCATT]
4126 Bodo Moeller, "Security of CBC Ciphersuites in SSL/TLS: Problems and
4127 Countermeasures", 2002, available from
4128 @url{http://www.openssl.org/~bodo/tls-cbc.txt}.
4130 @item @anchor{GPGH}[GPGH]
4131 Mike Ashley, "The GNU Privacy Handbook", 2002, available from
4132 @url{http://www.gnupg.org/gph/en/manual.pdf}.
4134 @item @anchor{GUTPKI}[GUTPKI]
4135 Peter Gutmann, "Everything you never wanted to know about PKI but were
4136 forced to find out", Available from
4137 @url{http://www.cs.auckland.ac.nz/~pgut001/}.
4139 @item @anchor{NISTSP80057}[NISTSP80057]
4140 NIST Special Publication 800-57, "Recommendation for Key Management -
4141 Part 1: General (Revised)", March 2007, available from
4142 @url{http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57-Part1-revised2_Mar08-2007.pdf}.
4144 @item @anchor{RFC2246}[RFC2246]
4145 Tim Dierks and Christopher Allen, "The TLS Protocol Version 1.0",
4146 January 1999, Available from
4147 @url{http://www.ietf.org/rfc/rfc2246.txt}.
4149 @item @anchor{RFC4346}[RFC4346]
4150 Tim Dierks and Eric Rescorla, "The TLS Protocol Version 1.1", Match
4151 2006, Available from @url{http://www.ietf.org/rfc/rfc4346.txt}.
4153 @item @anchor{RFC2440}[RFC2440]
4154 Jon Callas, Lutz Donnerhacke, Hal Finney and Rodney Thayer, "OpenPGP
4155 Message Format", November 1998, Available from
4156 @url{http://www.ietf.org/rfc/rfc2440.txt}.
4158 @item @anchor{RFC4880}[RFC4880]
4159 Jon Callas, Lutz Donnerhacke, Hal Finney, David Shaw and Rodney
4160 Thayer, "OpenPGP Message Format", November 2007, Available from
4161 @url{http://www.ietf.org/rfc/rfc4880.txt}.
4163 @item @anchor{RFC4211}[RFC4211]
4164 J. Schaad, "Internet X.509 Public Key Infrastructure Certificate
4165 Request Message Format (CRMF)", September 2005, Available from
4166 @url{http://www.ietf.org/rfc/rfc4211.txt}.
4168 @item @anchor{RFC2817}[RFC2817]
4169 Rohit Khare and Scott Lawrence, "Upgrading to TLS Within HTTP/1.1",
4170 May 2000, Available from @url{http://www.ietf.org/rfc/rfc2817.txt}
4172 @item @anchor{RFC2818}[RFC2818]
4173 Eric Rescorla, "HTTP Over TLS", May 2000, Available from
4174 @url{http://www.ietf/rfc/rfc2818.txt}.
4176 @item @anchor{RFC2945}[RFC2945]
4177 Tom Wu, "The SRP Authentication and Key Exchange System", September
4178 2000, Available from @url{http://www.ietf.org/rfc/rfc2945.txt}.
4180 @item @anchor{RFC2986}[RFC2986]
4181 Magnus Nystrom and Burt Kaliski, "PKCS 10 v1.7: Certification Request
4182 Syntax Specification", November 2000, Available from
4183 @url{http://www.ietf.org/rfc/rfc2986.txt}.
4185 @item @anchor{PKIX}[PKIX]
4186 D. Cooper, S. Santesson, S. Farrel, S. Boeyen, R. Housley, W. Polk,
4187 "Internet X.509 Public Key Infrastructure Certificate and Certificate
4188 Revocation List (CRL) Profile", May 2008, available from
4189 @url{http://www.ietf.org/rfc/rfc5280.txt}.
4191 @item @anchor{RFC3749}[RFC3749]
4192 Scott Hollenbeck, "Transport Layer Security Protocol Compression
4193 Methods", May 2004, available from
4194 @url{http://www.ietf.org/rfc/rfc3749.txt}.
4196 @item @anchor{RFC3820}[RFC3820]
4197 Steven Tuecke, Von Welch, Doug Engert, Laura Pearlman, and Mary
4198 Thompson, "Internet X.509 Public Key Infrastructure (PKI) Proxy
4199 Certificate Profile", June 2004, available from
4200 @url{http://www.ietf.org/rfc/rfc3820}.
4202 @item @anchor{TLSTKT}[TLSTKT]
4203 Joseph Salowey, Hao Zhou, Pasi Eronen, Hannes Tschofenig, "Transport
4204 Layer Security (TLS) Session Resumption without Server-Side State",
4205 January 2008, available from @url{http://www.ietf.org/rfc/rfc5077}.
4207 @item @anchor{PKCS12}[PKCS12]
4208 RSA Laboratories, "PKCS 12 v1.0: Personal Information Exchange
4209 Syntax", June 1999, Available from @url{http://www.rsa.com}.
4211 @item @anchor{RESCORLA}[RESCORLA]
4212 Eric Rescorla, "SSL and TLS: Designing and Building Secure Systems",
4215 @item @anchor{SELKEY}[SELKEY]
4216 Arjen Lenstra and Eric Verheul, "Selecting Cryptographic Key Sizes",
4217 2003, available from @url{http://www.win.tue.nl/~klenstra/key.pdf}.
4219 @item @anchor{SSL3}[SSL3]
4220 Alan Freier, Philip Karlton and Paul Kocher, "The SSL Protocol Version
4221 3.0", November 1996, Available from
4222 @url{http://wp.netscape.com/eng/ssl3/draft302.txt}.
4224 @item @anchor{STEVENS}[STEVENS]
4225 Richard Stevens, "UNIX Network Programming, Volume 1", Prentice Hall
4228 @item @anchor{TLSEXT}[TLSEXT]
4229 Simon Blake-Wilson, Magnus Nystrom, David Hopwood, Jan Mikkelsen and
4230 Tim Wright, "Transport Layer Security (TLS) Extensions", June 2003,
4231 Available from @url{http://www.ietf.org/rfc/rfc3546.txt}.
4233 @item @anchor{TLSPGP}[TLSPGP]
4234 Nikos Mavrogiannopoulos, "Using OpenPGP keys for TLS authentication",
4235 April 2004, November 2007. Available from
4236 @url{http://www.ietf.org/rfc/rfc5081.txt}.
4238 @item @anchor{TLSSRP}[TLSSRP]
4239 David Taylor, Trevor Perrin, Tom Wu and Nikos Mavrogiannopoulos,
4240 "Using SRP for TLS Authentication", November 2007. Available from
4241 @url{http://www.ietf.org/rfc/rfc5054.txt}.
4243 @item @anchor{TLSPSK}[TLSPSK]
4244 Pasi Eronen and Hannes Tschofenig, "Pre-shared key Ciphersuites for
4245 TLS", December 2005, Available from
4246 @url{http://www.ietf.org/rfc/rfc4279.txt}.
4248 @item @anchor{TOMSRP}[TOMSRP]
4249 Tom Wu, "The Stanford SRP Authentication Project", Available at
4250 @url{http://srp.stanford.edu/}.
4252 @item @anchor{WEGER}[WEGER]
4253 Arjen Lenstra and Xiaoyun Wang and Benne de Weger, "Colliding X.509
4254 Certificates", Cryptology ePrint Archive, Report 2005/067, Available
4255 at @url{http://eprint.iacr.org/}.
4259 @node Function and Data Index
4260 @unnumbered Function and Data Index
4265 @unnumbered Concept Index