Drop experimental stuff.
[gnutls.git] / doc / gnutls.texi
blobd8ec68e2352349db464d61a11161d87ae81a390b
1 \input texinfo   @c -*-texinfo-*-
2 @comment $Id$
3 @comment %**start of header
4 @setfilename gnutls.info
5 @include version.texi
6 @settitle GNU TLS @value{VERSION}
8 @c don't indent the paragraphs.
9 @paragraphindent 0
11 @c Unify some of the indices.
12 @syncodeindex tp fn
13 @syncodeindex pg cp
15 @comment %**end of header
16 @finalout
17 @copying
18 This manual is last updated @value{UPDATED} for version
19 @value{VERSION} of GNU TLS.
21 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
23 @quotation
24 Permission is granted to copy, distribute and/or modify this document
25 under the terms of the GNU Free Documentation License, Version 1.2 or
26 any later version published by the Free Software Foundation; with no
27 Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.  A
28 copy of the license is included in the section entitled ``GNU Free
29 Documentation License''.
30 @end quotation
31 @end copying
33 @dircategory GNU Libraries
34 @direntry
35 * libgnutls: (gnutls).          A Transport Layer Security Library.
36 @end direntry
38 @dircategory Network Applications
39 @direntry
40 * GnuTLS: (gnutls).                     Package for Transport Layer Security.
41 * certtool: (gnutls)Invoking certtool.  Manipulate certificates and keys.
42 * srptool: (gnutls)Invoking srptool.    Simple SRP password tool.
43 * gnutls-serv: (gnutls)Invoking gnutls-serv.    GNU TLS test server.
44 * gnutls-cli: (gnutls)Invoking gnutls-cli.      GNU TLS test client.
45 * gnutls-cli-debug: (gnutls)Invoking gnutls-cli-debug.  GNU TLS debug client.
46 @end direntry
48 @titlepage
49 @title GNU TLS
50 @subtitle Transport Layer Security Library for the GNU system
51 @subtitle for version @value{VERSION}, @value{UPDATED}
52 @sp 7
53 @image{gnutls-logo,6cm,6cm}
54 @author Nikos Mavrogiannopoulos
55 @author Simon Josefsson (@email{bug-gnutls@@gnu.org})
56 @page
57 @vskip 0pt plus 1filll
58 @insertcopying
59 @end titlepage
61 @macro xcite{ref}
62 [\ref\] (@pxref{Bibliography})
63 @end macro
65 @contents
67 @ifnottex
68 @node Top
69 @top GNU TLS
71 @insertcopying
72 @end ifnottex
74 @menu
75 * Preface::
76 * The Library::
77 * Introduction to TLS::
78 * Authentication methods::
79 * More on certificate authentication::
80 * How to use TLS in application protocols::
81 * How to use GnuTLS in applications::
82 * Included programs::
83 * Function reference::
84 * All the supported ciphersuites in GnuTLS::
85 * Guile Bindings::
86 * Internal architecture of GnuTLS::
87 * Copying Information::
88 * Concept Index::
89 * Function and Data Index::
90 @c * @mybibnode{}::
91 * Bibliography::
92 @end menu
95 @node Preface
96 @chapter Preface
98 This document tries to demonstrate and explain the @acronym{GnuTLS}
99 library API.  A brief introduction to the protocols and the technology
100 involved, is also included so that an application programmer can
101 better understand the @acronym{GnuTLS} purpose and actual offerings.
102 Even if @acronym{GnuTLS} is a typical library software, it operates
103 over several security and cryptographic protocols, which require the
104 programmer to make careful and correct usage of them, otherwise he
105 risks to offer just a false sense of security. Security and the
106 network security terms are very general terms even for computer
107 software thus cannot be easily restricted to a single cryptographic
108 library.  For that reason, do not consider a program secure just
109 because it uses @acronym{GnuTLS}; there are several ways to compromise
110 a program or a communication line and @acronym{GnuTLS} only helps with
111 some of them.
113 Although this document tries to be self contained, basic network
114 programming and PKI knowlegde is assumed in most of it. A good
115 introduction to networking can be found in @xcite{STEVENS} and for
116 Public Key Infrastructure in @xcite{GUTPKI}.
118 @anchor{Availability}
120 Updated versions of the @acronym{GnuTLS} software and this document
121 will be available from @url{http://www.gnutls.org/} and
122 @url{http://www.gnu.org/software/gnutls/}.
124 @menu
125 * Getting help::
126 * Commercial Support::
127 * Downloading and Installing::
128 * Bug Reports::
129 * Contributing::
130 @end menu
132 @node Getting help
133 @section Getting Help
135 A mailing list where users may help each other exists, and you can
136 reach it by sending e-mail to @email{help-gnutls@@gnu.org}.  Archives
137 of the mailing list discussions, and an interface to manage
138 subscriptions, is available through the World Wide Web at
139 @url{http://lists.gnu.org/mailman/listinfo/help-gnutls}.
141 A mailing list for developers are also available, see
142 @url{http://www.gnu.org/software/gnutls/lists.html}.
144 Bug reports should be sent to @email{bug-gnutls@@gnu.org}, see
145 @xref{Bug Reports}.
147 @node Commercial Support
148 @section Commercial Support
150 Commercial support is available for users of GnuTLS.  The kind of
151 support that can be purchased may include:
153 @itemize
155 @item Implement new features.
156 Such as a new TLS extension.
158 @item Port GnuTLS to new platforms.
159 This could include porting to an embedded platforms that may need
160 memory or size optimization.
162 @item Integrating TLS as a security environment in your existing project.
164 @item System design of components related to TLS.
166 @end itemize
168 If you are interested, please write to:
170 @verbatim
171 Simon Josefsson Datakonsult
172 Hagagatan 24
173 113 47 Stockholm
174 Sweden
176 E-mail: simon@josefsson.org
177 @end verbatim
179 If your company provide support related to GnuTLS and would like to be
180 mentioned here, contact the author (@pxref{Bug Reports}).
182 @node Downloading and Installing
183 @section Downloading and Installing
184 @cindex Installation
185 @cindex Download
187 GnuTLS is available for download from the following URL:
189 @url{http://www.gnutls.org/download.html}
191 The latest version is stored in a file, e.g.,
192 @samp{gnutls-@value{VERSION}.tar.gz} where the @samp{@value{VERSION}}
193 value is the highest version number in the directory.
195 GnuTLS uses a Linux-like development cycle: even minor version numbers
196 indicate a stable release and a odd minor version number indicates a
197 development release.  For example, GnuTLS 1.6.3 denote a stable
198 release since 6 is even, and GnuTLS 1.7.11 denote a development
199 release since 7 is odd.
201 GnuTLS depends on Libgcrypt, 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
238 table.
240 @table @code
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.
250 @end table
252 For the complete list, refer to the output from @code{configure
253 --help}.
255 @node Bug Reports
256 @section Bug Reports
257 @cindex Reporting Bugs
259 If you think you have found a bug in GnuTLS, please investigate it and
260 report it.
262 @itemize @bullet
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
266 version.
268 @item You have to send us a test case that makes it possible for us to
269 reproduce the bug.
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.
276 @end itemize
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
281 development effort.
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
286 reports).
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
290 note.
292 Send your bug report to:
294 @center @samp{bug-gnutls@@gnu.org}
296 @node Contributing
297 @section Contributing
298 @cindex Contributing
299 @cindex Hacking
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:
318 @itemize @bullet
320 @item Coding Style.
321 Follow the GNU Standards document (@pxref{top, GNU Coding Standards,,
322 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}.
330 @item Return errors.
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.
350 @end itemize
351 @node The Library
352 @chapter The Library
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.  The library is available under the GNU Lesser GPL
364 license@footnote{A copy of the license is included in the
365 distribution}.  Important features of the @acronym{GnuTLS} library
366 include:
368 @itemize
370 @item Support for TLS 1.0, TLS 1.1, and SSL 3.0 protocols.
372 @item Support for both @acronym{X.509} and @acronym{OpenPGP} certificates.
374 @item Support for handling and verification of certificates.
376 @item Support for @acronym{SRP} for TLS authentication.
378 @item Support for @acronym{PSK} for TLS authentication.
380 @item Support for TLS Extension mechanism.
382 @item Support for TLS Compression Methods.
384 @end itemize
386 Additionally @acronym{GnuTLS} provides a limited emulation API for the
387 widely used OpenSSL@footnote{@url{http://www.openssl.org/}} library,
388 to ease integration with existing applications.
390 @acronym{GnuTLS} consists of three independent parts, namely the ``TLS
391 protocol part'', the ``Certificate part'', and the ``Crypto backend''
392 part.  The `TLS protocol part' is the actual protocol implementation,
393 and is entirely implemented within the @acronym{GnuTLS} library.  The
394 `Certificate part' consists of the certificate parsing, and
395 verification functions which is partially implemented in the
396 @acronym{GnuTLS} library.  The
397 @acronym{Libtasn1}@footnote{@url{ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/libtasn1/}},
398 a library which offers @acronym{ASN.1} parsing capabilities, is used
399 for the @acronym{X.509} certificate parsing functions.  A smaller
400 version of
401 @acronym{OpenCDK}@footnote{@url{ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/opencdk/}}
402 is used for the @acronym{OpenPGP} key support in @acronym{GnuTLS}.
403 The ``Crypto backend'' is provided by the
404 @acronym{Libgcrypt}@footnote{@url{ftp://ftp.gnupg.org/gcrypt/alpha/libgcrypt/}}
405 library.
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.
411 @menu
412 * General Idea::
413 * Error handling::
414 * Memory handling::
415 * Callback functions::
416 @end menu
418 @node General Idea
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 structure
431 is never modified by any @acronym{GnuTLS} function, except for the
432 deinitialization function which frees all memory allocated in the
433 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.
465 @node Error handling
466 @section Error Handling
468 In @acronym{GnuTLS} most functions return an integer type as a result.  In
469 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
498 defaults.
500 The @acronym{Libgcrypt} library on which @acronym{GnuTLS} depends, has such
501 secure memory allocation functions available. These should be used in
502 cases where even the system's swap memory is not considered
503 secure. See the documentation of @acronym{Libgcrypt} for more
504 information.
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.
518 @itemize
520 @item @ref{gnutls_transport_set_push_function}
522 @item @ref{gnutls_transport_set_pull_function}
524 @end itemize
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.
531 @itemize
533 @item @ref{gnutls_malloc}
535 @item @ref{gnutls_free}
537 @end itemize
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}.
559 @menu
560 * TLS layers::
561 * The transport layer::
562 * The TLS record protocol::
563 * The TLS Alert Protocol::
564 * The TLS Handshake Protocol::
565 * TLS Extensions::
566 * Selecting cryptographic key sizes::
567 * On SSL 2 and older protocols::
568 * On Record Padding::
569 @end menu
571 @node TLS layers
572 @section TLS Layers
573 @cindex TLS Layers
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.
602 @itemize
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}
608 @end itemize
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
637 TCP/IP servers.
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:
647 @table @asis
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.
657 @end table
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.
668 @menu
669 * Encryption algorithms used in the record layer::
670 * Compression algorithms used in the record layer::
671 * Weaknesses and countermeasures::
672 @end menu
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
689 data size.
691 Supported cipher algorithms:
693 @table @code
694 @item 3DES_CBC
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.
698 @item ARCFOUR_128
699 ARCFOUR is a fast stream cipher.
701 @item ARCFOUR_40
702 This is the ARCFOUR cipher that is fed with a 40 bit key,
703 which is considered weak.
705 @item AES_CBC
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.
709 @end table
711 Supported MAC algorithms:
713 @table @code
714 @item MAC_MD5
715 MD5 is a cryptographic hash algorithm designed by Ron Rivest. Outputs
716 128 bits of data.
718 @item MAC_SHA
719 SHA is a cryptographic hash algorithm designed by NSA. Outputs 160
720 bits of data.
722 @end table
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:
748 @table @code
749 @item DEFLATE
750 Zlib compression, using the deflate algorithm.
752 @item LZO
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
756 LZO support.
758 @end table
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
767 @enumerate
769 @item
770 @acronym{TLS} has separate alerts for ``decryption_failed'' and
771 ``bad_record_mac''
773 @item
774 The decryption failure reason can be detected by timing the response
775 time.
777 @item
778 The IV for CBC encrypted packets is the last block of the previous
779 encrypted packet.
781 @end enumerate
783 Those weaknesses were solved in @acronym{TLS} 1.1 @xcite{RFC4346} which is implemented
784 in @acronym{GnuTLS}. For a detailed discussion see the archives of the
785 TLS Working Group mailing list and the paper @xcite{CBCATT}.
787 @node The TLS Alert Protocol
788 @section The TLS Alert Protocol
789 @anchor{The Alert Protocol}
790 @cindex Alert protocol
792 The Alert protocol is there to allow signals to be sent between peers.
793 These signals are mostly used to inform the peer about the cause of a
794 protocol failure. Some of these signals are used internally by the
795 protocol and the application protocol does not have to cope with them
796 (see @code{GNUTLS_A_CLOSE_NOTIFY}), and others refer to the
797 application protocol solely (see @code{GNUTLS_A_USER_CANCELLED}).  An
798 alert signal includes a level indication which may be either fatal or
799 warning. Fatal alerts always terminate the current connection, and
800 prevent future renegotiations using the current session ID.
802 The alert messages are protected by the record protocol, thus the
803 information that is included does not leak. You must take extreme care
804 for the alert information not to leak to a possible attacker, via
805 public log files etc.
807 @table @asis
808 @item @ref{gnutls_alert_send}:
809 To send an alert signal.
811 @item @ref{gnutls_error_to_alert}:
812 To map a gnutls error number to an alert signal.
814 @item @ref{gnutls_alert_get}:
815 Returns the last received alert.
817 @item @ref{gnutls_alert_get_name}:
818 Returns the name, in a character array, of the given alert.
820 @end table
822 @node The TLS Handshake Protocol
823 @section The TLS Handshake Protocol
824 @anchor{The Handshake Protocol}
825 @cindex Handshake protocol
827 The Handshake protocol is responsible for the ciphersuite negotiation,
828 the initial key exchange, and the authentication of the two peers.
829 This is fully controlled by the application layer, thus your program
830 has to set up the required parameters. Available functions to control
831 the handshake protocol include:
833 @table @asis
834 @item @ref{gnutls_priority_init}:
835 To initialize a priority set of ciphers.
837 @item @ref{gnutls_priority_deinit}:
838 To deinitialize a priority set of ciphers.
840 @item @ref{gnutls_priority_set}:
841 To associate a priority set with a @acronym{TLS} session.
843 @item @ref{gnutls_priority_set_direct}:
844 To directly associate a session with a given priority string.
846 @item @ref{gnutls_credentials_set}:
847 To set the appropriate credentials structures.
849 @item @ref{gnutls_certificate_server_set_request}:
850 To set whether client certificate is required or not.
852 @item @ref{gnutls_handshake}:
853 To initiate the handshake.
854 @end table
856 @subsection TLS Cipher Suites
858 The Handshake Protocol of @acronym{TLS} negotiates cipher suites of
859 the form @code{TLS_DHE_RSA_WITH_3DES_CBC_SHA}.  The usual cipher
860 suites contain these parameters:
862 @itemize
864 @item The key exchange algorithm.
865 @code{DHE_RSA} in the example.
867 @item The Symmetric encryption algorithm and mode
868 @code{3DES_CBC} in this example.
870 @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.
871 @code{MAC_SHA} is used in the above example.
873 @end itemize
875 The cipher suite negotiated in the handshake protocol will affect the
876 Record Protocol, by enabling encryption and data authentication.  Note
877 that you should not over rely on @acronym{TLS} to negotiate the
878 strongest available cipher suite. Do not enable ciphers and algorithms
879 that you consider weak.
881 The priority functions, dicussed above, allow the application layer to
882 enable and set priorities on the individual ciphers. It may imply that
883 all combinations of ciphersuites are allowed, but this is not
884 true. For several reasons, not discussed here, some combinations were
885 not defined in the @acronym{TLS} protocol.  The supported ciphersuites
886 are shown in @ref{ciphersuites}.
888 @subsection Client Authentication
889 @cindex Client Certificate authentication
891 In the case of ciphersuites that use certificate authentication, the
892 authentication of the client is optional in @acronym{TLS}.  A server
893 may request a certificate from the client --- using the
894 @ref{gnutls_certificate_server_set_request} function. If a
895 certificate is to be requested from the client during the handshake,
896 the server will send a certificate request message that contains a
897 list of acceptable certificate signers. In @acronym{GnuTLS} the certificate
898 signers list is constructed using the trusted Certificate Authorities by the 
899 server. That is the ones set using
900 @itemize
901 @item @ref{gnutls_certificate_set_x509_trust_file}
902 @item @ref{gnutls_certificate_set_x509_trust_mem}
903 @end itemize
905 Sending of the names of the CAs can be controlled using 
906 @ref{gnutls_certificate_send_x509_rdn_sequence}. The client, then, 
907 may send a certificate, signed by one of the server's acceptable 
908 signers. 
910 @subsection Resuming Sessions
911 @anchor{resume}
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 necessary
935 parameters. See the functions:
937 @itemize
939 @item @ref{gnutls_session_get_data}
941 @item @ref{gnutls_session_get_id}
943 @item @ref{gnutls_session_set_data}
945 @end itemize
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
949 registered with:
951 @itemize
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}
961 @end itemize
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.
967 @node TLS Extensions
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:
975 @itemize
976 @item Maximum fragment length negotiation
977 @item Server name indication
978 @end itemize
980 and they will be discussed in the subsections that follow.
982 @subsection Maximum Fragment Length Negotiation
983 @cindex TLS Extensions
984 @cindex Maximum fragment length
986 This extension allows a @acronym{TLS} implementation to negotiate a
987 smaller value for record packet maximum length. This extension may be
988 useful to clients with constrained capabilities. See the
989 @ref{gnutls_record_set_max_size} and the
990 @ref{gnutls_record_get_max_size} functions.
992 @subsection Server Name Indication
993 @anchor{serverind}
994 @cindex TLS Extensions
995 @cindex Server name indication
997 A common problem in @acronym{HTTPS} servers is the fact that the
998 @acronym{TLS} protocol is not aware of the hostname that a client
999 connects to, when the handshake procedure begins. For that reason the
1000 @acronym{TLS} server has no way to know which certificate to send.
1002 This extension solves that problem within the @acronym{TLS} protocol,
1003 and allows a client to send the HTTP hostname before the handshake
1004 begins within the first handshake packet.  The functions
1005 @ref{gnutls_server_name_set} and @ref{gnutls_server_name_get} can be
1006 used to enable this extension, or to retrieve the name sent by a
1007 client.
1009 @node Selecting cryptographic key sizes
1010 @section Selecting Cryptographic Key Sizes
1011 @cindex key sizes
1013 In TLS, since a lot of algorithms are involved, it is not easy to set a consistent security level.
1014 For this reason this section will present some correspondance between key sizes of symmetric algorithms
1015 and public key algorithms based on the most conservative values of @xcite{SELKEY}. 
1016 Those can be used to generate certificates with appropriate key sizes as well
1017 as parameters for Diffie Hellman and SRP authentication.
1019 @multitable @columnfractions .15 .20 .20 .20
1021 @item Year
1022 @tab Symmetric key size
1023 @tab RSA key size, DH and SRP prime size
1024 @tab ECC key size
1026 @item 1982
1027 @tab 56
1028 @tab 417
1029 @tab 105
1031 @item 1988
1032 @tab 61
1033 @tab 566
1034 @tab 114
1036 @item 2002
1037 @tab 72
1038 @tab 1028
1039 @tab 139
1041 @item 2015
1042 @tab 82
1043 @tab 1613
1044 @tab 173
1046 @item 2028
1047 @tab 92
1048 @tab 2362
1049 @tab 210
1051 @item 2040
1052 @tab 101
1053 @tab 3214
1054 @tab 244
1056 @item 2050 
1057 @tab 109
1058 @tab 4047
1059 @tab 272
1061 @end multitable
1063 The first column provides an estimation of the year until these parameters
1064 are considered safe and the rest of the columns list the parameters for the
1065 various algorithms.
1067 Note however that the values suggested here are nothing more than an educated
1068 guess that is valid today. There are no guarrantees that an algorithm will remain unbreakable or that these values will remain constant in time. There could be scientific breakthroughs that cannot be predicted or total failure of the current public key systems by quantum computers. On the other hand though the cryptosystems
1069 used in TLS are selected in a conservative way and such catastrophic breakthroughs or failures are believed to be unlikely.
1071 @node On SSL 2 and older protocols
1072 @section On SSL 2 and Older Protocols
1073 @cindex SSL 2
1075 One of the initial decisions in the @acronym{GnuTLS} development was
1076 to implement the known security protocols for the transport layer.
1077 Initially @acronym{TLS} 1.0 was implemented since it was the latest at
1078 that time, and was considered to be the most advanced in security
1079 properties.  Later the @acronym{SSL} 3.0 protocol was implemented
1080 since it is still the only protocol supported by several servers and
1081 there are no serious security vulnerabilities known.
1083 One question that may arise is why we didn't implement @acronym{SSL}
1084 2.0 in the library.  There are several reasons, most important being
1085 that it has serious security flaws, unacceptable for a modern security
1086 library.  Other than that, this protocol is barely used by anyone
1087 these days since it has been deprecated since 1996.  The security
1088 problems in @acronym{SSL} 2.0 include:
1090 @itemize
1092 @item Message integrity compromised.
1093 The @acronym{SSLv2} message authentication uses the MD5 function, and
1094 is insecure.
1096 @item Man-in-the-middle attack.
1097 There is no protection of the handshake in @acronym{SSLv2}, which
1098 permits a man-in-the-middle attack.
1100 @item Truncation attack.
1101 @acronym{SSLv2} relies on TCP FIN to close the session, so the
1102 attacker can forge a TCP FIN, and the peer cannot tell if it was a
1103 legitimate end of data or not.
1105 @item Weak message integrity for export ciphers.
1106 The cryptographic keys in @acronym{SSLv2} are used for both message
1107 authentication and encryption, so if weak encryption schemes are
1108 negotiated (say 40-bit keys) the message authentication code use the
1109 same weak key, which isn't necessary.
1111 @end itemize
1113 @cindex PCT
1114 Other protocols such as Microsoft's @acronym{PCT} 1 and @acronym{PCT}
1115 2 were not implemented because they were also abandoned and deprecated
1116 by @acronym{SSL} 3.0 and later @acronym{TLS} 1.0.
1118 @node On Record Padding
1119 @section On Record Padding
1120 @cindex Record padding
1121 @cindex Bad record MAC
1123 The TLS protocol allows for random padding of records, to make it more
1124 difficult to perform analysis on the length of exchanged messages.
1125 (In RFC 4346 this is specified in section 6.2.3.2.)  GnuTLS appears to
1126 be one of few implementation that take advantage of this text, and pad
1127 records by a random length.
1129 The TLS implementation in the Symbian operating system, frequently
1130 used by Nokia and Sony-Ericsson mobile phones, cannot handle
1131 non-minimal record padding.  What happens when one of these clients
1132 handshake with a GnuTLS server is that the client will fail to compute
1133 the correct MAC for the record.  The client sends a TLS alert
1134 (@code{bad_record_mac}) and disconnects.  Typically this will result
1135 in error messages such as 'A TLS fatal alert has been received', 'Bad
1136 record MAC', or both, on the GnuTLS server side.
1138 GnuTLS implements a work around for this problem.  However, it has to
1139 be enabled specifically.  It can be enabled by using
1140 @ref{gnutls_record_disable_padding}, or @ref{gnutls_priority_set} with
1141 the @code{%COMPAT} priority string.
1143 If you implement an application that have a configuration file, we
1144 recommend that you make it possible for users or administrators to
1145 specify a GnuTLS protocol priority string, which is used by your
1146 application via @ref{gnutls_priority_set}.  To allow the best
1147 flexibility, make it possible to have a different priority string for
1148 different incoming IP addresses.
1150 To enable the workaround in the @code{gnutls-cli} client or the
1151 @code{gnutls-serv} server, for testing of other implementations, use
1152 the following parameter: @code{--priority "%COMPAT"}.
1154 This problem has been discussed on mailing lists and in bug reports.
1155 This section tries to collect all pieces of information that we know
1156 about the problem.  If you wish to go back to the old discussions,
1157 here are some links:
1159 @url{http://bugs.debian.org/390712}
1161 @url{http://bugs.debian.org/402861}
1163 @url{http://bugs.debian.org/438137}
1165 @url{http://thread.gmane.org/gmane.ietf.tls/3079}
1167 @node Authentication methods
1168 @chapter Authentication Methods
1170 The @acronym{TLS} protocol provides confidentiality and encryption,
1171 but also offers authentication, which is a prerequisite for a secure
1172 connection. The available authentication methods in @acronym{GnuTLS}
1173 are:
1175 @itemize
1177 @item Certificate authentication
1179 @item Anonymous authentication
1181 @item @acronym{SRP} authentication
1183 @item @acronym{PSK} authentication
1185 @end itemize
1187 @menu
1188 * Certificate authentication::
1189 * Anonymous authentication::
1190 * Authentication using SRP::
1191 * Authentication using PSK::
1192 * Authentication and credentials::
1193 * Parameters stored in credentials::
1194 @end menu
1196 @node Certificate authentication
1197 @section Certificate Authentication
1199 @subsection Authentication Using @acronym{X.509} Certificates
1200 @cindex @acronym{X.509} certificates
1202 @acronym{X.509} certificates contain the public parameters, of a
1203 public key algorithm, and an authority's signature, which proves the
1204 authenticity of the parameters.  @xref{The X.509 trust model}, for
1205 more information on @acronym{X.509} protocols.
1207 @subsection Authentication Using @acronym{OpenPGP} Keys
1208 @cindex @acronym{OpenPGP} Keys
1210 @acronym{OpenPGP} keys also contain public parameters of a public key
1211 algorithm, and signatures from several other parties. Depending on
1212 whether a signer is trusted the key is considered trusted or not.
1213 @acronym{GnuTLS}'s @acronym{OpenPGP} authentication implementation is
1214 based on the @xcite{TLSPGP} proposal.
1216 @xref{The OpenPGP trust model}, for more information about the
1217 @acronym{OpenPGP} trust model.  For a more detailed introduction to
1218 @acronym{OpenPGP} and @acronym{GnuPG} see @xcite{GPGH}.
1220 @subsection Using Certificate Authentication
1222 In @acronym{GnuTLS} both the @acronym{OpenPGP} and @acronym{X.509}
1223 certificates are part of the certificate authentication and thus are
1224 handled using a common API.
1226 When using certificates the server is required to have at least one
1227 certificate and private key pair. A client may or may not have such a
1228 pair. The certificate and key pair should be loaded, before any
1229 @acronym{TLS} session is initialized, in a certificate credentials
1230 structure. This should be done by using
1231 @ref{gnutls_certificate_set_x509_key_file} or
1232 @ref{gnutls_certificate_set_openpgp_key_file} depending on the
1233 certificate type.  In the @acronym{X.509} case, the functions will
1234 also accept and use a certificate list that leads to a trusted
1235 authority. The certificate list must be ordered in such way that every
1236 certificate certifies the one before it. The trusted authority's
1237 certificate need not to be included, since the peer should possess it
1238 already.
1240 As an alternative, a callback may be used so the server or the client
1241 specify the certificate and the key at the handshake time.  That
1242 callback can be set using the functions:
1244 @itemize
1246 @item @ref{gnutls_certificate_server_set_retrieve_function}
1248 @item @ref{gnutls_certificate_client_set_retrieve_function}
1250 @end itemize
1252 Certificate verification is possible by loading the trusted
1253 authorities into the credentials structure by using
1254 @ref{gnutls_certificate_set_x509_trust_file} or
1255 @ref{gnutls_certificate_set_openpgp_keyring_file} for openpgp
1256 keys. Note however that the peer's certificate is not automatically
1257 verified, you should call @ref{gnutls_certificate_verify_peers2},
1258 after a successful handshake, to verify the signatures of the
1259 certificate.  An alternative way, which reports a more detailed
1260 verification output, is to use @ref{gnutls_certificate_get_peers} to
1261 obtain the raw certificate of the peer and verify it using the
1262 functions discussed in @ref{The X.509 trust model}.
1264 In a handshake, the negotiated cipher suite depends on the
1265 certificate's parameters, so not all key exchange methods will be
1266 available with some certificates. @acronym{GnuTLS} will disable
1267 ciphersuites that are not compatible with the key, or the enabled
1268 authentication methods.  For example keys marked as sign-only, will
1269 not be able to access the plain RSA ciphersuites, but only the
1270 @code{DHE_RSA} ones. It is recommended not to use RSA keys for both
1271 signing and encryption. If possible use the same key for the
1272 @code{DHE_RSA} and @code{RSA_EXPORT} ciphersuites, which use signing,
1273 and a different key for the plain RSA ciphersuites, which use
1274 encryption.  All the key exchange methods shown below are available in
1275 certificate authentication.
1277 Note that the DHE key exchange methods are generally
1278 slower@footnote{It really depends on the group used.  Primes with
1279 lesser bits are always faster, but also easier to break.  Values less
1280 than 768 should not be used today} than plain RSA and require Diffie
1281 Hellman parameters to be generated and associated with a credentials
1282 structure, by the server.  The @code{RSA-EXPORT} method also requires 512 bit RSA
1283 parameters, that should also be generated and associated with the
1284 credentials structure.  See the functions:
1286 @itemize
1288 @item @ref{gnutls_dh_params_generate2}
1290 @item @ref{gnutls_certificate_set_dh_params}
1292 @item @ref{gnutls_rsa_params_generate2}
1294 @item @ref{gnutls_certificate_set_rsa_export_params}
1296 @end itemize
1298 Sometimes in order to avoid bottlenecks in programs it is usefull to store
1299 and read parameters from formats that can be generated by external programs such
1300 as @code{certtool}. This is possible with @acronym{GnuTLS} by using the following
1301 functions:
1303 @itemize
1305 @item @ref{gnutls_dh_params_import_pkcs3}
1307 @item @ref{gnutls_rsa_params_import_pkcs1}
1309 @item @ref{gnutls_dh_params_export_pkcs3}
1311 @item @ref{gnutls_rsa_params_export_pkcs1}
1313 @end itemize
1315 Key exchange algorithms for @acronym{OpenPGP} and @acronym{X.509}
1316 certificates:
1318 @table @code
1320 @item RSA:
1321 The RSA algorithm is used to encrypt a key and send it to the peer.
1322 The certificate must allow the key to be used for encryption.
1324 @item RSA_EXPORT:
1325 The RSA algorithm is used to encrypt a key and send it to the peer.
1326 In the EXPORT algorithm, the server signs temporary RSA parameters of
1327 512 bits --- which are considered weak --- and sends them to the client.
1329 @item DHE_RSA:
1330 The RSA algorithm is used to sign Ephemeral Diffie Hellman parameters
1331 which are sent to the peer. The key in the certificate must allow the
1332 key to be used for signing. Note that key exchange algorithms which
1333 use Ephemeral Diffie Hellman parameters, offer perfect forward
1334 secrecy. That means that even if the private key used for signing is
1335 compromised, it cannot be used to reveal past session data.
1337 @item DHE_DSS:
1338 The DSS algorithm is used to sign Ephemeral Diffie Hellman parameters
1339 which are sent to the peer. The certificate must contain DSA
1340 parameters to use this key exchange algorithm. DSS stands for Digital
1341 Signature Standard.
1343 @end table
1345 @node Anonymous authentication
1346 @section Anonymous Authentication
1347 @cindex Anonymous authentication
1349 The anonymous key exchange performs encryption but there is no
1350 indication of the identity of the peer.  This kind of authentication
1351 is vulnerable to a man in the middle attack, but this protocol can be
1352 used even if there is no prior communication and trusted parties with
1353 the peer, or when full anonymity is required.  Unless really required,
1354 do not use anonymous authentication.  Available key exchange methods
1355 are shown below.
1357 Note that the key exchange methods for anonymous authentication
1358 require Diffie Hellman parameters to be generated by the server and associated with
1359 an anonymous credentials structure.
1361 Supported anonymous key exchange algorithms:
1363 @table @code
1365 @item ANON_DH:
1366 This algorithm exchanges Diffie Hellman parameters.
1368 @end table
1370 @node Authentication using SRP
1371 @section Authentication using @acronym{SRP}
1372 @cindex @acronym{SRP} authentication
1374 Authentication via the Secure Remote Password protocol,
1375 @acronym{SRP}@footnote{@acronym{SRP} is described in @xcite{RFC2945}},
1376 is supported.  The @acronym{SRP} key exchange is an extension to the
1377 @acronym{TLS} protocol, and it is a password based authentication
1378 (unlike @acronym{X.509} or @acronym{OpenPGP} that use certificates).
1379 The two peers can be identified using a single password, or there can
1380 be combinations where the client is authenticated using @acronym{SRP}
1381 and the server using a certificate.
1383 The advantage of @acronym{SRP} authentication, over other proposed
1384 secure password authentication schemes, is that @acronym{SRP} does not
1385 require the server to hold the user's password.  This kind of
1386 protection is similar to the one used traditionally in the @emph{UNIX}
1387 @file{/etc/passwd} file, where the contents of this file did not cause
1388 harm to the system security if they were revealed.  The @acronym{SRP}
1389 needs instead of the plain password something called a verifier, which
1390 is calculated using the user's password, and if stolen cannot be used
1391 to impersonate the user. Check @xcite{TOMSRP} for a detailed description
1392 of the @acronym{SRP} protocol and the Stanford @acronym{SRP}
1393 libraries, which includes a PAM module that synchronizes the system's
1394 users passwords with the @acronym{SRP} password files. That way
1395 @acronym{SRP} authentication could be used for all the system's users.
1397 The implementation in @acronym{GnuTLS} is based on paper
1398 @xcite{TLSSRP}.  The supported @acronym{SRP} key exchange methods are:
1400 @table @code
1402 @item SRP:
1403 Authentication using the @acronym{SRP} protocol.
1405 @item SRP_DSS:
1406 Client authentication using the @acronym{SRP} protocol. Server is
1407 authenticated using a certificate with DSA parameters.
1409 @item SRP_RSA:
1410 Client authentication using the @acronym{SRP} protocol. Server is
1411 authenticated using a certificate with RSA parameters.
1413 @end table
1415 If clients supporting @acronym{SRP} know the username and password
1416 before the connection, should initialize the client credentials and
1417 call the function @ref{gnutls_srp_set_client_credentials}.
1418 Alternatively they could specify a callback function by using the
1419 function @ref{gnutls_srp_set_client_credentials_function}.  This has
1420 the advantage that allows probing the server for @acronym{SRP}
1421 support.  In that case the callback function will be called twice per
1422 handshake.  The first time is before the ciphersuite is negotiated,
1423 and if the callback returns a negative error code, the callback will
1424 be called again if @acronym{SRP} has been negotiated.  This uses a
1425 special @acronym{TLS}-@acronym{SRP} handshake idiom in order to avoid,
1426 in interactive applications, to ask the user for @acronym{SRP}
1427 password and username if the server does not negotiate an
1428 @acronym{SRP} ciphersuite.
1430 In server side the default behaviour of @acronym{GnuTLS} is to read
1431 the usernames and @acronym{SRP} verifiers from password files. These
1432 password files are the ones used by the @emph{Stanford srp libraries}
1433 and can be specified using the
1434 @ref{gnutls_srp_set_server_credentials_file}.  If a different
1435 password file format is to be used, then the function
1436 @ref{gnutls_srp_set_server_credentials_function}, should be called,
1437 in order to set an appropriate callback.
1439 Some helper functions such as
1441 @itemize
1443 @item @ref{gnutls_srp_verifier}
1445 @item @ref{gnutls_srp_base64_encode}
1447 @item @ref{gnutls_srp_base64_decode}
1449 @end itemize
1451 are included in @acronym{GnuTLS}, and can be used to generate and
1452 maintain @acronym{SRP} verifiers and password files.  A program to
1453 manipulate the required parameters for @acronym{SRP} authentication is
1454 also included.  @xref{srptool}, for more information.
1457 @node Authentication using PSK
1458 @section Authentication using @acronym{PSK}
1459 @cindex @acronym{PSK} authentication
1461 Authentication using Pre-shared keys is a method to authenticate using
1462 usernames and binary keys. This protocol avoids making use of public key infrastructure
1463 and expensive calculations, thus it is suitable for constraint clients.
1465 The implementation in @acronym{GnuTLS} is based on paper
1466 @xcite{TLSPSK}.  The supported @acronym{PSK} key exchange methods are:
1468 @table @code
1470 @item PSK:
1471 Authentication using the @acronym{PSK} protocol.
1473 @item DHE-PSK:
1474 Authentication using the @acronym{PSK} protocol and Diffie Hellman key exchange.
1475 This method offers perfect forward secrecy.
1477 @end table
1479 Clients supporting @acronym{PSK} should supply the username and key
1480 before the connection to the client credentials by calling
1481 the function @ref{gnutls_psk_set_client_credentials}.
1482 Alternatively they could specify a callback function by using the
1483 function @ref{gnutls_psk_set_client_credentials_function}.
1484 This has the advantage that the callback will be called only if @acronym{PSK}
1485 has been negotiated.
1487 In server side the default behaviour of @acronym{GnuTLS} is to read
1488 the usernames and @acronym{PSK} keys from a password file. The password file
1489 should contain usernames and keys in hexadecimal format. The name of the password
1490 file can be stored to the credentials structure by calling
1491 @ref{gnutls_psk_set_server_credentials_file}.  If a different
1492 password file format is to be used, then the function
1493 @ref{gnutls_psk_set_server_credentials_function}, should be used instead.
1495 The server can help the client chose a suitable username and password,
1496 by sending a hint.  In the server, specify the hint by calling
1497 @ref{gnutls_psk_set_server_credentials_hint}.  The client can retrieve
1498 the hint, for example in the callback function, using
1499 @ref{gnutls_psk_client_get_hint}.
1501 There is no standard mechanism to derive a PSK key from a password
1502 specified by the TLS PSK document.  However, GnuTLS provides
1503 @ref{gnutls_psk_netconf_derive_key} which follows the algorithm
1504 specified in @file{draft-ietf-netconf-tls-02.txt}.
1506 Some helper functions such as:
1508 @itemize
1510 @item @ref{gnutls_hex_encode}
1512 @item @ref{gnutls_hex_decode}
1514 @end itemize
1516 are included in @acronym{GnuTLS}, and may be used to generate and
1517 maintain @acronym{PSK} keys.
1520 @node Authentication and credentials
1521 @section Authentication and Credentials
1523 In @acronym{GnuTLS} every key exchange method is associated with a
1524 credentials type. So in order to enable to enable a specific method,
1525 the corresponding credentials type should be initialized and set using
1526 @ref{gnutls_credentials_set}.  A mapping is shown below.
1528 Key exchange algorithms and the corresponding credential types:
1530 @multitable @columnfractions .3 .3 .3
1532 @headitem Key exchange @tab Client credentials @tab Server credentials
1534 @item @code{KX_RSA}
1535 @item @code{KX_DHE_RSA}
1536 @item @code{KX_DHE_DSS}
1537 @item @code{KX_RSA_EXPORT}
1538 @tab @code{CRD_CERTIFICATE}
1539 @tab @code{CRD_CERTIFICATE}
1541 @item @code{KX_SRP_RSA}
1542 @tab @code{CRD_SRP}
1543 @tab @code{CRD_SRP}
1544 @item @code{KX_SRP_DSS}
1545 @tab
1546 @tab @code{CRD_CERTIFICATE}
1548 @item @code{KX_SRP}
1549 @tab @code{CRD_SRP}
1550 @tab @code{CRD_SRP}
1552 @item @code{KX_ANON_DH}
1553 @tab @code{CRD_ANON}
1554 @tab @code{CRD_ANON}
1556 @item @code{KX_PSK}
1557 @tab @code{CRD_PSK}
1558 @tab @code{CRD_PSK}
1560 @end multitable
1562 @node Parameters stored in credentials
1563 @section Parameters Stored in Credentials
1565 Several parameters such as the ones used for Diffie-Hellman
1566 authentication are stored within the credentials structures, so all
1567 sessions can access them. Those parameters are stored in structures
1568 such as @code{gnutls_dh_params_t} and @code{gnutls_rsa_params_t}, and
1569 functions like @ref{gnutls_certificate_set_dh_params} and
1570 @ref{gnutls_certificate_set_rsa_export_params} can be used to
1571 associate those parameters with the given credentials structure.
1573 Since those parameters need to be renewed from time to time and a
1574 global structure such as the credentials, may not be easy to modify
1575 since it is accessible by all sessions, an alternative interface is
1576 available using a callback function.  This can be set using the
1577 @ref{gnutls_certificate_set_params_function}.  An example is shown
1578 below.
1580 @example
1581 #include <gnutls.h>
1583 gnutls_rsa_params_t rsa_params;
1584 gnutls_dh_params_t dh_params;
1586 /* This function will be called once a session requests DH
1587  * or RSA parameters. The parameters returned (if any) will
1588  * be used for the first handshake only.
1589  */
1590 static int get_params( gnutls_session_t session,
1591         gnutls_params_type_t type,
1592         gnutls_params_st *st)
1594    if (type == GNUTLS_PARAMS_RSA_EXPORT)
1595       st->params.rsa_export = rsa_params;
1596    else if (type == GNUTLS_PARAMS_DH)
1597       st->params.dh = dh_params;
1598    else return -1;
1600    st->type = type;
1601    /* do not deinitialize those parameters.
1602     */
1603    st->deinit = 0;
1605    return 0;
1608 int main()
1610    gnutls_certificate_credentials_t cert_cred;
1612    initialize_params();
1614    /* ...
1615     */
1617    gnutls_certificate_set_params_function( cert_cred, get_params);
1619 @end example
1621 @node More on certificate authentication
1622 @chapter More on Certificate Authentication
1623 @anchor{Certificate Authentication}
1624 @cindex Certificate authentication
1626 @menu
1627 * The X.509 trust model::
1628 * The OpenPGP trust model::
1629 * Digital signatures::
1630 @end menu
1632 @node The X.509 trust model
1633 @section The @acronym{X.509} Trust Model
1634 @cindex @acronym{X.509} certificates
1636 The @acronym{X.509} protocols rely on a hierarchical trust model. In
1637 this trust model Certification Authorities (CAs) are used to certify
1638 entities.  Usually more than one certification authorities exist, and
1639 certification authorities may certify other authorities to issue
1640 certificates as well, following a hierarchical model.
1642 @image{gnutls-x509,7cm,9.5cm}
1644 One needs to trust one or more CAs for his secure communications. In
1645 that case only the certificates issued by the trusted authorities are
1646 acceptable.  See the figure above for a typical example.  The API for
1647 handling @acronym{X.509} certificates is described at section
1648 @ref{sec:x509api}.  Some examples are listed below.
1650 @menu
1651 * X.509 certificates::
1652 * Verifying X.509 certificate paths::
1653 * PKCS #10 certificate requests::
1654 * PKCS #12 structures::
1655 @end menu
1657 @node X.509 certificates
1658 @subsection @acronym{X.509} Certificates
1660 An @acronym{X.509} certificate usually contains information about the
1661 certificate holder, the signer, a unique serial number, expiration
1662 dates and some other fields @xcite{RFC3280} as shown in the table
1663 below.
1665 @table @code
1667 @item version:
1668 The field that indicates the version of the certificate.
1670 @item serialNumber:
1671 This field holds a unique serial number per certificate.
1673 @item issuer:
1674 Holds the issuer's distinguished name.
1676 @item validity:
1677 The activation and expiration dates.
1679 @item subject:
1680 The subject's distinguished name of the certificate.
1682 @item extensions:
1683 The extensions are fields only present in version 3 certificates.
1685 @end table
1687 The certificate's @emph{subject or issuer name} is not just a single
1688 string.  It is a Distinguished name and in the @acronym{ASN.1}
1689 notation is a sequence of several object IDs with their corresponding
1690 values. Some of available OIDs to be used in an @acronym{X.509}
1691 distinguished name are defined in @file{gnutls/x509.h}.
1693 The @emph{Version} field in a certificate has values either 1 or 3 for
1694 version 3 certificates.  Version 1 certificates do not support the
1695 extensions field so it is not possible to distinguish a CA from a
1696 person, thus their usage should be avoided.
1698 The @emph{validity} dates are there to indicate the date that the
1699 specific certificate was activated and the date the certificate's key
1700 would be considered invalid.
1702 Certificate @emph{extensions} are there to include information about
1703 the certificate's subject that did not fit in the typical certificate
1704 fields. Those may be e-mail addresses, flags that indicate whether the
1705 belongs to a CA etc.  All the supported @acronym{X.509} version 3
1706 extensions are shown in the table below.
1708 @table @code
1710 @item subject key id (2.5.29.14):
1711 An identifier of the key of the subject.
1713 @item authority key id (2.5.29.35):
1714 An identifier of the authority's key used to sign the certificate.
1716 @item subject alternative name (2.5.29.17):
1717 Alternative names to subject's distinguished name.
1719 @item key usage (2.5.29.15):
1720 Constraints the key's usage of the certificate.
1722 @item extended key usage (2.5.29.37):
1723 Constraints the purpose of the certificate.
1725 @item basic constraints (2.5.29.19):
1726 Indicates whether this is a CA certificate or not, and specify the
1727 maximum path lengths of certificate chains.
1729 @item CRL distribution points (2.5.29.31):
1730 This extension is set by the CA, in order to inform about the issued CRLs.
1732 @item Proxy Certification Information (1.3.6.1.5.5.7.1.14):
1733 Proxy Certificates includes this extension that contains the OID of
1734 the proxy policy language used, and can specify limits on the maximum
1735 lengths of proxy chains.  Proxy Certificates are specified in
1736 @xcite{RFC3820}.
1738 @end table
1740 In @acronym{GnuTLS} the @acronym{X.509} certificate structures are handled using
1741 the @code{gnutls_x509_crt_t} type and the corresponding private keys
1742 with the @code{gnutls_x509_privkey_t} type.  All the available
1743 functions for @acronym{X.509} certificate handling have their prototypes in
1744 @file{gnutls/x509.h}. An example program to demonstrate the @acronym{X.509}
1745 parsing capabilities can be found at section @ref{ex:x509-info}.
1747 @node Verifying X.509 certificate paths
1748 @subsection Verifying @acronym{X.509} Certificate Paths
1749 @cindex Verifying certificate paths
1751 Verifying certificate paths is important in @acronym{X.509} authentication. For
1752 this purpose the function @ref{gnutls_x509_crt_verify} is
1753 provided. The output of this function is the bitwise OR of the
1754 elements of the @code{gnutls_certificate_status_t} enumeration.  A
1755 detailed description of these elements can be found in figure below.
1756 The function @ref{gnutls_certificate_verify_peers2} is equivalent to
1757 the previous one, and will verify the peer's certificate in a TLS
1758 session.
1760 @table @code
1762 @item CERT_INVALID:
1763 The certificate is not signed by one of the known authorities, or
1764 the signature is invalid.
1766 @item CERT_REVOKED:
1767 The certificate has been revoked by its CA.
1769 @item CERT_SIGNER_NOT_FOUND:
1770 The certificate's issuer is not known. This is the case when the
1771 issuer is not in the trusted certificates list.
1773 @item GNUTLS_CERT_SIGNER_NOT_CA:
1774 The certificate's signer was not a CA. This may happen if
1775 this was a version 1 certificate, which is common with some CAs, or
1776 a version 3 certificate without the basic constrains extension.
1778 @anchor{GNUTLS_CERT_INSECURE_ALGORITHM}
1779 @item GNUTLS_CERT_INSECURE_ALGORITHM:
1780 The certificate was signed using an insecure algorithm such as MD2 or
1781 MD5.  These algorithms have been broken and should not be trusted.
1783 @end table
1785 There is also to possibility to pass some input to the verification
1786 functions in the form of flags. For @ref{gnutls_x509_crt_verify} the
1787 flags are passed straightforward, but
1788 @ref{gnutls_certificate_verify_peers2} depends on the flags set by
1789 calling @ref{gnutls_certificate_set_verify_flags}.  All the available
1790 flags are part of the enumeration
1791 @ref{gnutls_certificate_verify_flags} and are explained in the table
1792 below.
1794 @anchor{gnutls_certificate_verify_flags}
1795 @tindex gnutls_certificate_verify_flags
1796 @table @code
1797 @item GNUTLS_VERIFY_DISABLE_CA_SIGN:
1798 If set a signer does not have to be a certificate authority. This
1799 flag should normaly be disabled, unless you know what this means.
1801 @item GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT:
1802 Allow only trusted CA certificates that have version 1.  This is
1803 safer than GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT, and should be
1804 used instead. That way only signers in your trusted list will be
1805 allowed to have certificates of version 1.
1807 @item GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT:
1808 Allow CA certificates that have version 1 (both root and
1809 intermediate). This is dangerous since those haven't the
1810 basicConstraints extension. Must be used in combination with
1811 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT.
1813 @item GNUTLS_VERIFY_DO_NOT_ALLOW_SAME:
1814 If a certificate is not signed by anyone trusted but exists in
1815 the trusted CA list do not treat it as trusted.
1817 @item GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2:
1818 Allow certificates to be signed using the old MD2 algorithm.
1820 @item GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5:
1821 Allow certificates to be signed using the broken MD5 algorithm.
1822 @end table
1824 Although the verification of a certificate path indicates that the
1825 certificate is signed by trusted authority, does not reveal anything
1826 about the peer's identity. It is required to verify if the
1827 certificate's owner is the one you expect. For more information consult @xcite{RFC2818} 
1828 and section @ref{ex:verify} for an example.
1830 @node PKCS #10 certificate requests
1831 @subsection @acronym{PKCS} #10 Certificate Requests
1832 @cindex Certificate requests
1833 @cindex @acronym{PKCS} #10
1835 A certificate request is a structure, which contain information about
1836 an applicant of a certificate service.  It usually contains a private
1837 key, a distinguished name and secondary data such as a challenge
1838 password. @acronym{GnuTLS} supports the requests defined in
1839 @acronym{PKCS} #10 @xcite{RFC2986}. Other certificate request's format
1840 such as PKIX's @xcite{RFC4211} are not currently supported.
1842 In @acronym{GnuTLS} the @acronym{PKCS} #10 structures are handled
1843 using the @code{gnutls_x509_crq_t} type.  An example of a certificate
1844 request generation can be found at section @ref{ex:crq}.
1846 @node PKCS #12 structures
1847 @subsection @acronym{PKCS} #12 Structures
1848 @cindex @acronym{PKCS} #12
1850 A @acronym{PKCS} #12 structure @xcite{PKCS12} usually contains a user's
1851 private keys and certificates. It is commonly used in browsers to
1852 export and import the user's identities.
1854 In @acronym{GnuTLS} the @acronym{PKCS} #12 structures are handled
1855 using the @code{gnutls_pkcs12_t} type. This is an abstract type that
1856 may hold several @code{gnutls_pkcs12_bag_t} types.  The Bag types are
1857 the holders of the actual data, which may be certificates, private
1858 keys or encrypted data.  An Bag of type encrypted should be decrypted
1859 in order for its data to be accessed.
1861 An example of a @acronym{PKCS} #12 structure generation can be found
1862 at section @ref{ex:pkcs12}.
1864 @node The OpenPGP trust model
1865 @section The @acronym{OpenPGP} Trust Model
1866 @cindex @acronym{OpenPGP} Keys
1868 The @acronym{OpenPGP} key authentication relies on a distributed trust
1869 model, called the ``web of trust''. The ``web of trust'' uses a
1870 decentralized system of trusted introducers, which are the same as a
1871 CA. @acronym{OpenPGP} allows anyone to sign anyone's else public
1872 key. When Alice signs Bob's key, she is introducing Bob's key to
1873 anyone who trusts Alice. If someone trusts Alice to introduce keys,
1874 then Alice is a trusted introducer in the mind of that observer.
1876 @image{gnutls-pgp,11cm,9cm}
1878 For example: If David trusts Alice to be an introducer, and Alice
1879 signed Bob's key, Dave also trusts Bob's key to be the real one.
1881 There are some key points that are important in that model. In the
1882 example Alice has to sign Bob's key, only if she is sure that the key
1883 belongs to Bob. Otherwise she may also make Dave falsely believe that
1884 this is Bob's key. Dave has also the responsibility to know who to
1885 trust.  This model is similar to real life relations.
1887 Just see how Charlie behaves in the previous example. Although he has
1888 signed Bob's key - because he knows, somehow, that it belongs to Bob -
1889 he does not trust Bob to be an introducer. Charlie decided to trust
1890 only Kevin, for some reason. A reason could be that Bob is lazy
1891 enough, and signs other people's keys without being sure that they
1892 belong to the actual owner.
1894 @subsection @acronym{OpenPGP} Keys
1896 In @acronym{GnuTLS} the @acronym{OpenPGP} key structures
1897 @xcite{RFC2440} are handled using the @code{gnutls_openpgp_crt_t} type
1898 and the corresponding private keys with the
1899 @code{gnutls_openpgp_privkey_t} type. All the prototypes for the key
1900 handling functions can be found at @file{gnutls/openpgp.h}.
1902 @subsection Verifying an @acronym{OpenPGP} Key
1904 The verification functions of @acronym{OpenPGP} keys, included in
1905 @acronym{GnuTLS}, are simple ones, and do not use the features of the
1906 ``web of trust''.  For that reason, if the verification needs are
1907 complex, the assistance of external tools like @acronym{GnuPG} and
1908 GPGME (@url{http://www.gnupg.org/related_software/gpgme/}) is
1909 recommended.
1911 There is one verification function in @acronym{GnuTLS}, the
1912 @ref{gnutls_openpgp_crt_verify_ring}.
1913 This checks an @acronym{OpenPGP} key against a given set of public keys (keyring) and
1914 returns the key status. The key verification status is the same as in
1915 @acronym{X.509} certificates, although the meaning and interpretation are
1916 different. For example an @acronym{OpenPGP} key may be valid, if the
1917 self signature is ok, even if no signers were found.  The meaning of
1918 verification status is shown in the figure below.  
1920 @table @code
1922 @item CERT_INVALID:
1923 A signature on the key is invalid. That means that the key was
1924 modified by somebody, or corrupted during transport.
1926 @item CERT_REVOKED:
1927 The key has been revoked by its owner.
1929 @item CERT_SIGNER_NOT_FOUND:
1930 The key was not signed by a known signer.
1932 @item GNUTLS_CERT_INSECURE_ALGORITHM:
1933 The certificate was signed using an insecure algorithm such as MD2 or MD5.
1934 These algorithms have been broken and should not be trusted.
1936 @end table
1938 @node Digital signatures
1939 @section Digital Signatures
1940 @cindex Digital signatures
1941 @include signatures.texi
1944 @node How to use TLS in application protocols
1945 @chapter How To Use @acronym{TLS} in Application Protocols
1947 This chapter is intended to provide some hints on how to use the
1948 @acronym{TLS} over simple custom made application protocols.  The
1949 discussion below mainly refers to the @emph{TCP/IP} transport layer
1950 but may be extended to other ones too.
1952 @menu
1953 * Separate ports::
1954 * Upward negotiation::
1955 @end menu
1957 @node Separate ports
1958 @section Separate Ports
1960 Traditionally @acronym{SSL} was used in application protocols by
1961 assigning a new port number for the secure services. That way two
1962 separate ports were assigned, one for the non secure sessions, and one
1963 for the secured ones. This has the benefit that if a user requests a
1964 secure session then the client will try to connect to the secure port
1965 and fail otherwise. The only possible attack with this method is a
1966 denial of service one. The most famous example of this method is the
1967 famous ``HTTP over TLS'' or @acronym{HTTPS} protocol @xcite{RFC2818}.
1969 Despite its wide use, this method is not as good as it seems.  This
1970 approach starts the @acronym{TLS} Handshake procedure just after the
1971 client connects on the ---so called--- secure port.  That way the
1972 @acronym{TLS} protocol does not know anything about the client, and
1973 popular methods like the host advertising in HTTP do not
1974 work@footnote{See also the Server Name Indication extension on
1975 @ref{serverind}.}.  There is no way for the client to say ``I
1976 connected to YYY server'' before the Handshake starts, so the server
1977 cannot possibly know which certificate to use.
1979 Other than that it requires two separate ports to run a single
1980 service, which is unnecessary complication. Due to the fact that there
1981 is a limitation on the available privileged ports, this approach was
1982 soon obsoleted.
1984 @node Upward negotiation
1985 @section Upward Negotiation
1987 Other application protocols@footnote{See LDAP, IMAP etc.}  use a
1988 different approach to enable the secure layer.  They use something
1989 called the ``TLS upgrade'' method. This method is quite tricky but it
1990 is more flexible. The idea is to extend the application protocol to
1991 have a ``STARTTLS'' request, whose purpose it to start the TLS
1992 protocols just after the client requests it.  This is a really neat
1993 idea and does not require an extra port.
1995 This method is used by almost all modern protocols and there is even
1996 the @xcite{RFC2817} paper which proposes extensions to HTTP to support
1999 The tricky part, in this method, is that the ``STARTTLS'' request is
2000 sent in the clear, thus is vulnerable to modifications.  A typical
2001 attack is to modify the messages in a way that the client is fooled
2002 and thinks that the server does not have the ``STARTTLS'' capability.
2003 See a typical conversation of a hypothetical protocol:
2005 @quotation
2006 (client connects to the server)
2008 CLIENT: HELLO I'M MR. XXX
2010 SERVER: NICE TO MEET YOU XXX
2012 CLIENT: PLEASE START TLS
2014 SERVER: OK
2016 *** TLS STARTS
2018 CLIENT: HERE ARE SOME CONFIDENTIAL DATA
2019 @end quotation
2021 And see an example of a conversation where someone is acting
2022 in between:
2024 @quotation
2025 (client connects to the server)
2027 CLIENT: HELLO I'M MR. XXX
2029 SERVER: NICE TO MEET YOU XXX
2031 CLIENT: PLEASE START TLS
2033 (here someone inserts this message)
2035 SERVER: SORRY I DON'T HAVE THIS CAPABILITY
2037 CLIENT: HERE ARE SOME CONFIDENTIAL DATA
2038 @end quotation
2040 As you can see above the client was fooled, and was dummy enough to
2041 send the confidential data in the clear.
2043 How to avoid the above attack? As you may have already thought this
2044 one is easy to avoid. The client has to ask the user before it
2045 connects whether the user requests @acronym{TLS} or not. If the user
2046 answered that he certainly wants the secure layer the last
2047 conversation should be:
2049 @quotation
2050 (client connects to the server)
2052 CLIENT: HELLO I'M MR. XXX
2054 SERVER: NICE TO MEET YOU XXX
2056 CLIENT: PLEASE START TLS
2058 (here someone inserts this message)
2060 SERVER: SORRY I DON'T HAVE THIS CAPABILITY
2062 CLIENT: BYE
2064 (the client notifies the user that the secure connection was not possible)
2065 @end quotation
2067 This method, if implemented properly, is far better than the
2068 traditional method, and the security properties remain the same, since
2069 only denial of service is possible. The benefit is that the server may
2070 request additional data before the @acronym{TLS} Handshake protocol
2071 starts, in order to send the correct certificate, use the correct
2072 password file@footnote{in @acronym{SRP} authentication}, or anything
2073 else!
2075 @node How to use GnuTLS in applications
2076 @chapter How To Use @acronym{GnuTLS} in Applications
2077 @anchor{examples}
2078 @cindex Example programs
2080 @menu
2081 * Preparation::
2082 * Multi-threaded applications::
2083 * Client examples::
2084 * Server examples::
2085 * Miscellaneous examples::
2086 * Compatibility with the OpenSSL library::
2087 * Opaque PRF Input TLS Extension::
2088 @end menu
2090 @node Preparation
2091 @section Preparation
2093 To use @acronym{GnuTLS}, you have to perform some changes to your
2094 sources and your build system. The necessary changes are explained in
2095 the following subsections.
2097 @menu
2098 * Headers::
2099 * Version check::
2100 * Debugging::
2101 * Building the source::
2102 @end menu
2104 @node Headers
2105 @subsection Headers
2107 All the data types and functions of the @acronym{GnuTLS} library are
2108 defined in the header file @file{gnutls/gnutls.h}.  This must be
2109 included in all programs that make use of the @acronym{GnuTLS}
2110 library.
2112 The extra functionality of the @acronym{GnuTLS-extra} library is
2113 available by including the header file @file{gnutls/extra.h} in your
2114 programs.
2116 @node Version check
2117 @subsection Version Check
2119 It is often desirable to check that the version of `gnutls' used is
2120 indeed one which fits all requirements.  Even with binary
2121 compatibility new features may have been introduced but due to problem
2122 with the dynamic linker an old version is actually used.  So you may
2123 want to check that the version is okay right after program startup.
2124 See the function @ref{gnutls_check_version}.
2126 @node Debugging
2127 @subsection Debugging
2129 In many cases things may not go as expected and further information,
2130 to assist debugging, from @acronym{GnuTLS} is desired. Those are the
2131 case where the @ref{gnutls_global_set_log_level} and
2132 @ref{gnutls_global_set_log_function} are to be used. Those will print
2133 verbose information on the @acronym{GnuTLS} functions internal flow.
2135 @node Building the source
2136 @subsection Building the Source
2138 If you want to compile a source file including the `gnutls/gnutls.h'
2139 header file, you must make sure that the compiler can find it in the
2140 directory hierarchy.  This is accomplished by adding the path to the
2141 directory in which the header file is located to the compilers include
2142 file search path (via the -I option).
2144 However, the path to the include file is determined at the time the
2145 source is configured.  To solve this problem, @acronym{GnuTLS} ships
2146 with two small helper programs @command{libgnutls-config} and
2147 @command{libgnutls-extra-config} that knows about the path to the
2148 include file and other configuration options.  The options that need
2149 to be added to the compiler invocation at compile time are output by
2150 the @code{--cflags} option to @command{libgnutls-config}.  The
2151 following example shows how it can be used at the command line:
2153 @example
2154 gcc -c foo.c `libgnutls-config --cflags`
2155 @end example
2157 Adding the output of @command{libgnutls-config --cflags} to the
2158 compilers command line will ensure that the compiler can find the
2159 @acronym{GnuTLS} header file.
2161 A similar problem occurs when linking the program with the library.
2162 Again, the compiler has to find the library files.  For this to work,
2163 the path to the library files has to be added to the library search
2164 path (via the -L option).  For this, the option @code{--libs} to
2165 @command{libgnutls-config} can be used.  For convenience, this option
2166 also outputs all other options that are required to link the program
2167 with the @acronym{GnuTLS} libararies.  The example shows how to link
2168 `foo.o' with the @acronym{GnuTLS} libraries to a program @emph{foo}.
2170 @example
2171 gcc -o foo foo.o `libgnutls-config --libs`
2172 @end example
2174 Of course you can also combine both examples to a single command by
2175 specifying both options to `libgnutls-config':
2177 @example
2178 gcc -o foo foo.c `libgnutls-config --cflags --libs`
2179 @end example
2181 @node Multi-threaded applications
2182 @section Multi-Threaded Applications
2184 Although the @acronym{GnuTLS} library is thread safe by design, some
2185 parts of the crypto backend, such as the random generator, are
2186 not. Since @emph{libgcrypt 1.1.92} there was an automatic detection of
2187 the thread library used by the application, so most applications
2188 wouldn't need to do any changes to ensure thread-safety. Due to the
2189 unportability of the automatic thread detection, this was removed from
2190 later releases of @emph{libgcrypt}, so applications have now to
2191 register callback functions to ensure proper locking in sensitive
2192 parts of @emph{libgcrypt}.
2194 There are helper macros to help you properly initialize the libraries.
2195 Examples are shown below.
2197 @itemize
2199 @item POSIX threads
2200 @example
2201 #include <gnutls.h>
2202 #include <gcrypt.h>
2203 #include <errno.h>
2204 #include <pthread.h>
2205 GCRY_THREAD_OPTION_PTHREAD_IMPL;
2207 int main() 
2209    /* The order matters.
2210     */
2211    gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
2212    gnutls_global_init();
2214 @end example
2216 @item GNU PTH threads
2217 @example
2218 #include <gnutls.h>
2219 #include <gcrypt.h>
2220 #include <errno.h>
2221 #include <pth.h>
2222 GCRY_THREAD_OPTION_PTH_IMPL;
2224 int main() 
2226    gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
2227    gnutls_global_init();
2229 @end example
2231 @item Other thread packages
2232 @example
2233 /* The gcry_thread_cbs structure must have been
2234  * initialized.
2235  */
2236 static struct gcry_thread_cbs gcry_threads_other = @{ ... @};
2238 int main()
2240    gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_other);
2242 @end example
2243 @end itemize
2245 @node Client examples
2246 @section Client Examples
2248 This section contains examples of @acronym{TLS} and @acronym{SSL}
2249 clients, using @acronym{GnuTLS}.  Note that these examples contain
2250 little or no error checking.  Some of the examples require functions
2251 implemented by another example.
2253 @menu
2254 * Simple client example with anonymous authentication::
2255 * Simple client example with X.509 certificate support::
2256 * Obtaining session information::
2257 * Verifying peer's certificate::
2258 * Using a callback to select the certificate to use::
2259 * Client with Resume capability example::
2260 * Simple client example with SRP authentication::
2261 * Simple client example with TLS/IA support::
2262 * Simple client example in @acronym{C++}::
2263 * Helper function for TCP connections::
2264 @end menu
2266 @node Simple client example with anonymous authentication
2267 @subsection Simple Client Example with Anonymous Authentication
2269 The simplest client using TLS is the one that doesn't do any
2270 authentication.  This means no external certificates or passwords are
2271 needed to set up the connection.  As could be expected, the connection
2272 is vulnerable to man-in-the-middle (active or redirection) attacks.
2273 However, the data is integrity and privacy protected.
2275 @verbatiminclude examples/ex-client1.c
2277 @node Simple client example with X.509 certificate support
2278 @subsection Simple Client Example with @acronym{X.509} Certificate Support
2280 Let's assume now that we want to create a TCP client which
2281 communicates with servers that use @acronym{X.509} or
2282 @acronym{OpenPGP} certificate authentication. The following client is
2283 a very simple @acronym{TLS} client, it does not support session
2284 resuming, not even certificate verification. The TCP functions defined
2285 in this example are used in most of the other examples below, without
2286 redefining them.
2288 @verbatiminclude examples/ex-client2.c
2290 @node Obtaining session information
2291 @subsection Obtaining Session Information
2293 Most of the times it is desirable to know the security properties of
2294 the current established session.  This includes the underlying ciphers
2295 and the protocols involved.  That is the purpose of the following
2296 function.  Note that this function will print meaningful values only
2297 if called after a successful @ref{gnutls_handshake}.
2299 @verbatiminclude examples/ex-session-info.c
2301 @node Verifying peer's certificate
2302 @subsection Verifying Peer's Certificate
2303 @anchor{ex:verify}
2305 A @acronym{TLS} session is not secure just after the handshake
2306 procedure has finished.  It must be considered secure, only after the
2307 peer's certificate and identity have been verified. That is, you have
2308 to verify the signature in peer's certificate, the hostname in the
2309 certificate, and expiration dates.  Just after this step you should
2310 treat the connection as being a secure one.
2312 @verbatiminclude examples/ex-rfc2818.c
2314 An other example is listed below which provides a more detailed
2315 verification output.
2317 @verbatiminclude examples/ex-verify.c
2319 @node Using a callback to select the certificate to use
2320 @subsection Using a Callback to Select the Certificate to Use
2322 There are cases where a client holds several certificate and key
2323 pairs, and may not want to load all of them in the credentials
2324 structure.  The following example demonstrates the use of the
2325 certificate selection callback.
2327 @verbatiminclude examples/ex-cert-select.c
2329 @node Client with Resume capability example
2330 @subsection Client with Resume Capability Example
2331 @anchor{ex:resume-client}
2333 This is a modification of the simple client example. Here we
2334 demonstrate the use of session resumption. The client tries to connect
2335 once using @acronym{TLS}, close the connection and then try to
2336 establish a new connection using the previously negotiated data.
2338 @verbatiminclude examples/ex-client-resume.c
2340 @node Simple client example with SRP authentication
2341 @subsection Simple Client Example with @acronym{SRP} Authentication
2343 The following client is a very simple @acronym{SRP} @acronym{TLS}
2344 client which connects to a server and authenticates using a
2345 @emph{username} and a @emph{password}. The server may authenticate
2346 itself using a certificate, and in that case it has to be verified.
2348 @verbatiminclude examples/ex-client-srp.c
2350 @node Simple client example with TLS/IA support
2351 @subsection Simple Client Example with @acronym{TLS/IA} Support
2353 The following client is a simple client which uses the
2354 @acronym{TLS/IA} extension to authenticate with the server.
2356 @verbatiminclude examples/ex-client-tlsia.c
2358 @node Simple client example in @acronym{C++}
2359 @subsection Simple Client Example using the @acronym{C++} API
2361 The following client is a simple example of a client
2362 client utilizing the GnuTLS @acronym{C++} API. 
2364 @verbatiminclude examples/ex-cxx.cpp
2366 @node Helper function for TCP connections
2367 @subsection Helper Function for TCP Connections
2369 This helper function abstracts away TCP connection handling from the
2370 other examples.  It is required to build some examples.
2372 @verbatiminclude examples/tcp.c
2374 @node Server examples
2375 @section Server Examples
2377 This section contains examples of @acronym{TLS} and @acronym{SSL}
2378 servers, using @acronym{GnuTLS}.
2380 @menu
2381 * Echo Server with X.509 authentication::
2382 * Echo Server with X.509 authentication II::
2383 * Echo Server with OpenPGP authentication::
2384 * Echo Server with SRP authentication::
2385 * Echo Server with anonymous authentication::
2386 @end menu
2388 @node Echo Server with X.509 authentication
2389 @subsection Echo Server with @acronym{X.509} Authentication
2391 This example is a very simple echo server which supports
2392 @acronym{X.509} authentication, using the RSA ciphersuites.
2394 @verbatiminclude examples/ex-serv1.c
2396 @node Echo Server with X.509 authentication II
2397 @subsection Echo Server with @acronym{X.509} Authentication II
2399 The following example is a server which supports @acronym{X.509}
2400 authentication.  This server supports the export-grade cipher suites,
2401 the DHE ciphersuites and session resuming.
2403 @verbatiminclude examples/ex-serv-export.c
2405 @node Echo Server with OpenPGP authentication
2406 @subsection Echo Server with @acronym{OpenPGP} Authentication
2407 @cindex @acronym{OpenPGP} Server
2409 The following example is an echo server which supports
2410 @acronym{@acronym{OpenPGP}} key authentication. You can easily combine
2411 this functionality ---that is have a server that supports both
2412 @acronym{X.509} and @acronym{OpenPGP} certificates--- but we separated
2413 them to keep these examples as simple as possible.
2415 @verbatiminclude examples/ex-serv-pgp.c
2417 @node Echo Server with SRP authentication
2418 @subsection Echo Server with @acronym{SRP} Authentication
2420 This is a server which supports @acronym{SRP} authentication. It is
2421 also possible to combine this functionality with a certificate
2422 server. Here it is separate for simplicity.
2424 @verbatiminclude examples/ex-serv-srp.c
2426 @node Echo Server with anonymous authentication
2427 @subsection Echo Server with Anonymous Authentication
2429 This example server support anonymous authentication, and could be
2430 used to serve the example client for anonymous authentication.
2432 @verbatiminclude examples/ex-serv-anon.c
2434 @node Miscellaneous examples
2435 @section Miscellaneous Examples
2437 @menu
2438 * Checking for an alert::
2439 * X.509 certificate parsing example::
2440 * Certificate request generation::
2441 * PKCS #12 structure generation::
2442 @end menu
2444 @node Checking for an alert
2445 @subsection Checking for an Alert
2447 This is a function that checks if an alert has been received in the
2448 current session.
2450 @verbatiminclude examples/ex-alert.c
2452 @node X.509 certificate parsing example
2453 @subsection @acronym{X.509} Certificate Parsing Example
2454 @anchor{ex:x509-info}
2456 To demonstrate the @acronym{X.509} parsing capabilities an example program is
2457 listed below.  That program reads the peer's certificate, and prints
2458 information about it.
2460 @verbatiminclude examples/ex-x509-info.c
2462 @node Certificate request generation
2463 @subsection Certificate Request Generation
2464 @anchor{ex:crq}
2466 The following example is about generating a certificate request, and a
2467 private key. A certificate request can be later be processed by a CA,
2468 which should return a signed certificate.
2470 @verbatiminclude examples/ex-crq.c
2472 @node PKCS #12 structure generation
2473 @subsection @acronym{PKCS} #12 Structure Generation
2474 @anchor{ex:pkcs12}
2476 The following example is about generating a @acronym{PKCS} #12
2477 structure.
2479 @verbatiminclude examples/ex-pkcs12.c
2481 @node Compatibility with the OpenSSL library
2482 @section Compatibility with the OpenSSL Library
2483 @cindex OpenSSL
2485 To ease @acronym{GnuTLS}' integration with existing applications, a
2486 compatibility layer with the widely used OpenSSL library is included
2487 in the @code{gnutls-openssl} library. This compatibility layer is not
2488 complete and it is not intended to completely reimplement the OpenSSL
2489 API with @acronym{GnuTLS}.  It only provides source-level
2490 compatibility. There is currently no attempt to make it
2491 binary-compatible with OpenSSL.
2493 The prototypes for the compatibility functions are in the
2494 @file{gnutls/openssl.h} header file.
2496 Current limitations imposed by the compatibility layer include:
2498 @itemize
2500 @item Error handling is not thread safe.
2502 @end itemize
2504 @node Opaque PRF Input TLS Extension
2505 @section Opaque PRF Input TLS Extension
2506 @cindex Opaque PRF Input
2508 GnuTLS supports the Opaque PRF Input TLS extension
2509 (@code{draft-rescorla-tls-opaque-prf-input-00.txt}).  The API consists
2510 of one API for use in the client, @ref{gnutls_oprfi_enable_client},
2511 and one API for use in the server, @ref{gnutls_oprfi_enable_server}.
2512 You must invoke both functions before calling @ref{gnutls_handshake}.
2513 The server utilizes a callback function into the application.  The
2514 callback can look at the random string provided by the client, and
2515 also set the server string.  The string lengths must be equal
2516 according to the protocol.
2518 @node Included programs
2519 @chapter Included Programs
2521 Included with @acronym{GnuTLS} are also a few command line tools that
2522 let you use the library for common tasks without writing an
2523 application.  The applications are discussed in this chapter.
2525 @menu
2526 * Invoking srptool::
2527 * Invoking gnutls-cli::
2528 * Invoking gnutls-cli-debug::
2529 * Invoking gnutls-serv::
2530 * Invoking certtool::
2531 * Invoking psktool::
2532 @end menu
2534 @node Invoking srptool
2535 @section Invoking srptool
2536 @anchor{srptool}
2537 @cindex srptool
2539 The @file{srptool} is a very simple program that emulates the programs
2540 in the @emph{Stanford SRP libraries}.  It is intended for use in
2541 places where you don't expect @acronym{SRP} authentication to be the
2542 used for system users.  Traditionally @emph{libsrp} used two
2543 files. One called 'tpasswd' which holds usernames and verifiers, and
2544 'tpasswd.conf' which holds generators and primes.
2546 How to use srptool:
2548 @itemize
2550 @item
2551 To create tpasswd.conf which holds the g and n values for
2552 @acronym{SRP} protocol (generator and a large prime), run:
2554 @example
2555 $ srptool --create-conf /etc/tpasswd.conf
2556 @end example
2558 @item
2559 This command will create /etc/tpasswd and will add user 'test' (you
2560 will also be prompted for a password). Verifiers are stored by default
2561 in the way libsrp expects.
2563 @example
2564 $ srptool --passwd /etc/tpasswd \
2565     --passwd-conf /etc/tpasswd.conf -u test
2566 @end example
2568 @item
2569 This command will check against a password. If the password matches
2570 the one in /etc/tpasswd you will get an ok.
2572 @example
2573 $ srptool --passwd /etc/tpasswd \
2574     --passwd-conf /etc/tpasswd.conf --verify -u test
2575 @end example
2577 @end itemize
2579 @node Invoking gnutls-cli
2580 @section Invoking gnutls-cli
2581 @cindex gnutls-cli
2583 Simple client program to set up a TLS connection to some other
2584 computer.  It sets up a TLS connection and forwards data from the
2585 standard input to the secured socket and vice versa.
2587 @verbatim
2588 GNU TLS test client
2589 Usage:  gnutls-cli [options] hostname
2591      -d, --debug integer      Enable debugging
2592      -r, --resume             Connect, establish a session. Connect
2593                               again and resume this session.
2594      -s, --starttls           Connect, establish a plain session and
2595                               start TLS when EOF or a SIGALRM is
2596                               received.
2597      --crlf                   Send CR LF instead of LF.
2598      --x509fmtder             Use DER format for certificates to read
2599                               from.
2600      -f, --fingerprint        Send the openpgp fingerprint, instead
2601                               of the key.
2602      --disable-extensions     Disable all the TLS extensions.
2603      --print-cert             Print the certificate in PEM format.
2604      -p, --port integer       The port to connect to.
2605      --recordsize integer     The maximum record size to advertize.
2606      -V, --verbose            More verbose output.
2607      --ciphers cipher1 cipher2...
2608                               Ciphers to enable.
2609      --protocols protocol1 protocol2...
2610                               Protocols to enable.
2611      --comp comp1 comp2...    Compression methods to enable.
2612      --macs mac1 mac2...      MACs to enable.
2613      --kx kx1 kx2...          Key exchange methods to enable.
2614      --ctypes certType1 certType2...
2615                               Certificate types to enable.
2616      --x509cafile FILE        Certificate file to use.
2617      --x509crlfile FILE       CRL file to use.
2618      --pgpkeyfile FILE        PGP Key file to use.
2619      --pgpkeyring FILE        PGP Key ring file to use.
2620      --pgptrustdb FILE        PGP trustdb file to use.
2621      --pgpcertfile FILE       PGP Public Key (certificate) file to
2622                               use.
2623      --x509keyfile FILE       X.509 key file to use.
2624      --x509certfile FILE      X.509 Certificate file to use.
2625      --srpusername NAME       SRP username to use.
2626      --srppasswd PASSWD       SRP password to use.
2627      --insecure               Don't abort program if server
2628                               certificate can't be validated.
2629      -l, --list               Print a list of the supported
2630                               algorithms  and modes.
2631      -h, --help               prints this help
2632      -v, --version            prints the program's version number
2633      --copyright              prints the program's license
2634 @end verbatim
2636 To connect to a server using PSK authentication, you may use something
2637 like:
2639 @smallexample
2640 $ gnutls-cli -p 5556 test.gnutls.org --pskusername jas --pskkey 9e32cf7786321a828ef7668f09fb35db --priority NORMAL:+PSK:-RSA:-DHE-RSA -d 4711
2641 @end smallexample
2643 @menu
2644 * Example client PSK connection::
2645 @end menu
2647 @node Example client PSK connection
2648 @subsection Example client PSK connection
2649 @cindex PSK client
2651 If your server only supports the PSK ciphersuite, connecting to it
2652 should be as simple as connecting to the server:
2654 @smallexample
2655 $ ./gnutls-cli -p 5556 localhost
2656 Resolving 'localhost'...
2657 Connecting to '127.0.0.1:5556'...
2658 - PSK client callback. PSK hint 'psk_identity_hint'
2659 Enter PSK identity: psk_identity
2660 Enter password: 
2661 - PSK authentication. PSK hint 'psk_identity_hint'
2662 - Version: TLS1.1
2663 - Key Exchange: PSK
2664 - Cipher: AES-128-CBC
2665 - MAC: SHA1
2666 - Compression: NULL
2667 - Handshake was completed
2669 - Simple Client Mode:
2670 @end smallexample
2672 If the server supports several cipher suites, you may need to force it
2673 to chose PSK by using a cipher priority parameter such as
2674 @code{--priority NORMAL:+PSK:-RSA:-DHE-RSA:-DHE-PSK}.
2676 @cindex Netconf
2677 Instead of using the Netconf-way to derive the PSK key from a
2678 password, you can also give the PSK username and key directly on the
2679 command line:
2681 @smallexample
2682 $ ./gnutls-cli -p 5556 localhost --pskusername psk_identity --pskkey 88f3824b3e5659f52d00e959bacab954b6540344 
2683 Resolving 'localhost'...
2684 Connecting to '127.0.0.1:5556'...
2685 - PSK authentication. PSK hint 'psk_identity_hint'
2686 - Version: TLS1.1
2687 - Key Exchange: PSK
2688 - Cipher: AES-128-CBC
2689 - MAC: SHA1
2690 - Compression: NULL
2691 - Handshake was completed
2693 - Simple Client Mode:
2694 @end smallexample
2696 By keeping the @code{--pskusername} parameter and removing the
2697 @code{--pskkey} parameter, it will query only for the password during
2698 the handshake.
2700 @node Invoking gnutls-cli-debug
2701 @section Invoking gnutls-cli-debug
2702 @cindex gnutls-cli-debug
2704 This program was created to assist in debugging @acronym{GnuTLS}, but
2705 it might be useful to extract a @acronym{TLS} server's capabilities.
2706 It's purpose is to connect onto a @acronym{TLS} server, perform some
2707 tests and print the server's capabilities. If called with the `-v'
2708 parameter a more checks will be performed. An example output is:
2710 @smallexample
2711 crystal:/cvs/gnutls/src$ ./gnutls-cli-debug localhost -p 5556
2712 Resolving 'localhost'...
2713 Connecting to '127.0.0.1:5556'...
2714 Checking for TLS 1.1 support... yes
2715 Checking fallback from TLS 1.1 to... N/A
2716 Checking for TLS 1.0 support... yes
2717 Checking for SSL 3.0 support... yes
2718 Checking for version rollback bug in RSA PMS... no
2719 Checking for version rollback bug in Client Hello... no
2720 Checking whether we need to disable TLS 1.0... N/A
2721 Checking whether the server ignores the RSA PMS version... no
2722 Checking whether the server can accept Hello Extensions... yes
2723 Checking whether the server can accept cipher suites not in SSL 3.0 spec... yes
2724 Checking whether the server can accept a bogus TLS record version in the client hello... yes
2725 Checking for certificate information... N/A
2726 Checking for trusted CAs... N/A
2727 Checking whether the server understands TLS closure alerts... yes
2728 Checking whether the server supports session resumption... yes
2729 Checking for export-grade ciphersuite support... no
2730 Checking RSA-export ciphersuite info... N/A
2731 Checking for anonymous authentication support... no
2732 Checking anonymous Diffie Hellman group info... N/A
2733 Checking for ephemeral Diffie Hellman support... no
2734 Checking ephemeral Diffie Hellman group info... N/A
2735 Checking for AES cipher support (TLS extension)... yes
2736 Checking for 3DES cipher support... yes
2737 Checking for ARCFOUR 128 cipher support... yes
2738 Checking for ARCFOUR 40 cipher support... no
2739 Checking for MD5 MAC support... yes
2740 Checking for SHA1 MAC support... yes
2741 Checking for ZLIB compression support (TLS extension)... yes
2742 Checking for LZO compression support (GnuTLS extension)... yes
2743 Checking for max record size (TLS extension)... yes
2744 Checking for SRP authentication support (TLS extension)... yes
2745 Checking for OpenPGP authentication support (TLS extension)... no
2746 @end smallexample
2748 @node Invoking gnutls-serv
2749 @section Invoking gnutls-serv
2750 @cindex gnutls-serv
2752 Simple server program that listens to incoming TLS connections.
2754 @verbatim
2755 GNU TLS test server
2756 Usage: gnutls-serv [options]
2758      -d, --debug integer      Enable debugging
2759      -g, --generate           Generate Diffie Hellman Parameters.
2760      -p, --port integer       The port to connect to.
2761      -q, --quiet              Suppress some messages.
2762      --nodb                   Does not use the resume database.
2763      --http                   Act as an HTTP Server.
2764      --echo                   Act as an Echo Server.
2765      --dhparams FILE          DH params file to use.
2766      --x509fmtder             Use DER format for certificates
2767      --x509cafile FILE        Certificate file to use.
2768      --x509crlfile FILE       CRL file to use.
2769      --pgpkeyring FILE        PGP Key ring file to use.
2770      --pgptrustdb FILE        PGP trustdb file to use.
2771      --pgpkeyfile FILE        PGP Key file to use.
2772      --pgpcertfile FILE       PGP Public Key (certificate) file to
2773                               use.
2774      --x509keyfile FILE       X.509 key file to use.
2775      --x509certfile FILE      X.509 Certificate file to use.
2776      --x509dsakeyfile FILE    Alternative X.509 key file to use.
2777      --x509dsacertfile FILE   Alternative X.509 certificate file to
2778                               use.
2779      --srppasswd FILE         SRP password file to use.
2780      --srppasswdconf FILE     SRP password conf file to use.
2781      --ciphers cipher1 cipher2...
2782                               Ciphers to enable.
2783      --protocols protocol1 protocol2...
2784                               Protocols to enable.
2785      --comp comp1 comp2...    Compression methods to enable.
2786      --macs mac1 mac2...      MACs to enable.
2787      --kx kx1 kx2...          Key exchange methods to enable.
2788      --ctypes certType1 certType2...
2789                               Certificate types to enable.
2790      -l, --list               Print a list of the supported
2791                               algorithms  and modes.
2792      -h, --help               prints this help
2793      -v, --version            prints the program's version number
2794      --copyright              prints the program's license
2795 @end verbatim
2797 @subsection Setting Up a Test HTTPS Server
2798 @cindex HTTPS server
2799 @cindex debug server
2801 Running your own TLS server based on GnuTLS can be useful when
2802 debugging clients and/or GnuTLS itself.  This section describes how to
2803 use @code{gnutls-serv} as a simple HTTPS server.
2805 The most basic server can be started as:
2807 @example
2808 gnutls-serv --http
2809 @end example
2811 It will only support anonymous ciphersuites, which many TLS clients
2812 refuse to use.
2814 The next step is to add support for X.509.  First we generate a CA:
2816 @example
2817 certtool --generate-privkey > x509-ca-key.pem
2818 echo 'cn = GnuTLS test CA' > ca.tmpl
2819 echo 'ca' >> ca.tmpl
2820 echo 'cert_signing_key' >> ca.tmpl
2821 certtool --generate-self-signed --load-privkey x509-ca-key.pem \
2822   --template ca.tmpl --outfile x509-ca.pem
2824 @end example
2826 Then generate a server certificate.  Remember to change the dns_name
2827 value to the name of your server host, or skip that command to avoid
2828 the field.
2830 @example
2831 certtool --generate-privkey > x509-server-key.pem
2832 echo 'organization = GnuTLS test server' > server.tmpl
2833 echo 'cn = test.gnutls.org' >> server.tmpl
2834 echo 'tls_www_server' >> server.tmpl
2835 echo 'encryption_key' >> server.tmpl
2836 echo 'signing_key' >> server.tmpl
2837 echo 'dns_name = test.gnutls.org' >> server.tmpl
2838 certtool --generate-certificate --load-privkey x509-server-key.pem \
2839   --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
2840   --template server.tmpl --outfile x509-server.pem
2842 @end example
2844 For use in the client, you may want to generate a client certificate
2845 as well.
2847 @example
2848 certtool --generate-privkey > x509-client-key.pem
2849 echo 'cn = GnuTLS test client' > client.tmpl
2850 echo 'tls_www_client' >> client.tmpl
2851 echo 'encryption_key' >> client.tmpl
2852 echo 'signing_key' >> client.tmpl
2853 certtool --generate-certificate --load-privkey x509-client-key.pem \
2854   --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
2855   --template client.tmpl --outfile x509-client.pem
2857 @end example
2859 To be able to import the client key/certificate into some
2860 applications, you will need to convert them into a PKCS#12 structure.
2861 This also encrypts the security sensitive key with a password.
2863 @example
2864 certtool --to-p12 --load-privkey x509-client-key.pem --load-certificate x509-client.pem --outder --outfile x509-client.p12
2865 @end example
2867 For icing, we'll create a proxy certificate for the client too.
2869 @example
2870 certtool --generate-privkey > x509-proxy-key.pem
2871 echo 'cn = GnuTLS test client proxy' > proxy.tmpl
2872 certtool --generate-proxy --load-privkey x509-proxy-key.pem \
2873   --load-ca-certificate x509-client.pem --load-ca-privkey x509-client-key.pem \
2874   --load-certificate x509-client.pem --template proxy.tmpl \
2875   --outfile x509-proxy.pem
2877 @end example
2879 Then start the server again:
2881 @example
2882 gnutls-serv --http \
2883             --x509cafile x509-ca.pem \
2884             --x509keyfile x509-server-key.pem \
2885             --x509certfile x509-server.pem
2886 @end example
2888 Try connecting to the server using your web browser.  Note that the
2889 server listens to port 5556 by default.
2891 While you are at it, to allow connections using DSA, you can also
2892 create a DSA key and certificate for the server.  These credentials
2893 will be used in the final example below.
2895 @example
2896 certtool --generate-privkey --dsa > x509-server-key-dsa.pem
2897 certtool --generate-certificate --load-privkey x509-server-key-dsa.pem \
2898   --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
2899   --template server.tmpl --outfile x509-server-dsa.pem
2901 @end example
2903 The next step is to create OpenPGP credentials for the server.
2905 @example
2906 gpg --gen-key
2907 ...enter whatever details you want, use 'test.gnutls.org' as name...
2908 @end example
2910 Make a note of the OpenPGP key identifier of the newly generated key,
2911 here it was @code{5D1D14D8}.  You will need to export the key for
2912 GnuTLS to be able to use it.
2914 @example
2915 gpg -a --export 5D1D14D8 > openpgp-server.txt
2916 gpg --export 5D1D14D8 > openpgp-server.bin
2917 gpg --export-secret-keys 5D1D14D8 > openpgp-server-key.bin
2918 gpg -a --export-secret-keys 5D1D14D8 > openpgp-server-key.txt
2919 @end example
2921 Let's start the server with support for OpenPGP credentials:
2923 @example
2924 gnutls-serv --http \
2925             --pgpkeyfile openpgp-server-key.txt \
2926             --pgpcertfile openpgp-server.txt
2927 @end example
2929 The next step is to add support for SRP authentication.
2931 @example
2932 srptool --create-conf srp-tpasswd.conf
2933 srptool --passwd-conf srp-tpasswd.conf --username jas --passwd srp-passwd.txt
2934 Enter password: [TYPE "foo"]
2935 @end example
2937 Start the server with SRP support:
2939 @example
2940 gnutls-serv --http \
2941             --srppasswdconf srp-tpasswd.conf \
2942             --srppasswd srp-passwd.txt
2943 @end example
2945 Let's also add support for PSK.
2947 @example
2948 $ psktool --passwd psk-passwd.txt
2949 @end example
2951 Start the server with PSK support:
2953 @example
2954 gnutls-serv --http \
2955             --pskpasswd psk-passwd.txt
2956 @end example
2958 Finally, we start the server with all the earlier parameters and you
2959 get this command:
2961 @example
2962 gnutls-serv --http \
2963             --x509cafile x509-ca.pem \
2964             --x509keyfile x509-server-key.pem \
2965             --x509certfile x509-server.pem \
2966             --x509dsakeyfile x509-server-key-dsa.pem \
2967             --x509dsacertfile x509-server-dsa.pem \
2968             --pgpkeyfile openpgp-server-key.txt \
2969             --pgpcertfile openpgp-server.txt \
2970             --srppasswdconf srp-tpasswd.conf \
2971             --srppasswd srp-passwd.txt \
2972             --pskpasswd psk-passwd.txt
2973 @end example
2975 @menu
2976 * Example server PSK connection::
2977 @end menu
2979 @node Example server PSK connection
2980 @subsection Example server PSK connection
2981 @cindex PSK server
2983 To set up a PSK server with @code{gnutls-serv} you need to create PSK
2984 password file (@pxref{Invoking psktool}).  In the example below, I
2985 type @code{password} at the prompt.
2987 @smallexample
2988 $ ./psktool -u psk_identity -p psks.txt -n psk_identity_hint
2989 Enter password:
2990 Key stored to psks.txt
2991 $ cat psks.txt
2992 psk_identity:88f3824b3e5659f52d00e959bacab954b6540344
2994 @end smallexample
2996 After this, start the server pointing to the password file.  We
2997 disable DHE-PSK.
2999 @smallexample
3000 $ ./gnutls-serv --pskpasswd psks.txt  --pskhint psk_identity_hint --priority NORMAL:-DHE-PSK
3001 Set static Diffie Hellman parameters, consider --dhparams.
3002 Echo Server ready. Listening to port '5556'.
3003 @end smallexample
3005 You can now connect to the server using a PSK client (@pxref{Example
3006 client PSK connection}).
3008 @node Invoking certtool
3009 @section Invoking certtool
3010 @cindex certtool
3012 This is a program to generate @acronym{X.509} certificates, certificate
3013 requests, CRLs and private keys.
3015 @verbatim
3016 Certtool help
3017 Usage: certtool [options]
3018      -s, --generate-self-signed
3019                               Generate a self-signed certificate.
3020      -c, --generate-certificate
3021                               Generate a signed certificate.
3022      --generate-proxy         Generate a proxy certificate.
3023      --generate-crl           Generate a CRL.
3024      -u, --update-certificate
3025                               Update a signed certificate.
3026      -p, --generate-privkey   Generate a private key.
3027      -q, --generate-request   Generate a PKCS #10 certificate
3028                               request.
3029      -e, --verify-chain       Verify a PEM encoded certificate chain.
3030                               The last certificate in the chain must
3031                               be a self signed one.
3032      --verify-crl             Verify a CRL.
3033      --generate-dh-params     Generate PKCS #3 encoded Diffie Hellman
3034                               parameters.
3035      --get-dh-params          Get the included PKCS #3 encoded Diffie
3036                               Hellman parameters.
3037      --load-privkey FILE      Private key file to use.
3038      --load-request FILE      Certificate request file to use.
3039      --load-certificate FILE
3040                               Certificate file to use.
3041      --load-ca-privkey FILE   Certificate authority's private key
3042                               file to use.
3043      --load-ca-certificate FILE
3044                               Certificate authority's certificate
3045                               file to use.
3046      --password PASSWORD      Password to use.
3047      -i, --certificate-info   Print information on a certificate.
3048      -l, --crl-info           Print information on a CRL.
3049      --p12-info               Print information on a PKCS #12
3050                               structure.
3051      --p7-info                Print information on a PKCS #7
3052                               structure.
3053      --smime-to-p7            Convert S/MIME to PKCS #7 structure.
3054      -k, --key-info           Print information on a private key.
3055      --fix-key                Regenerate the parameters in a private
3056                               key.
3057      --to-p12                 Generate a PKCS #12 structure.
3058      -8, --pkcs8              Use PKCS #8 format for private keys.
3059      --dsa                    Use DSA keys.
3060      --hash STR               Hash algorithm to use for signing
3061                               (MD5,SHA1,RMD160).
3062      --export-ciphers         Use weak encryption algorithms.
3063      --inder                  Use DER format for input certificates
3064                               and private keys.
3065      --outder                 Use DER format for output certificates
3066                               and private keys.
3067      --bits BITS              specify the number of bits for key
3068                               generation.
3069      --outfile FILE           Output file.
3070      --infile FILE            Input file.
3071      --template FILE          Template file to use for non
3072                               interactive operation.
3073      -d, --debug LEVEL        specify the debug level. Default is 1.
3074      -h, --help               shows this help text
3075      -v, --version            shows the program's version
3076      --copyright              shows the program's license
3077 @end verbatim
3079 The program can be used interactively or non interactively by
3080 specifying the @code{--template} command line option. See below for an
3081 example of a template file.
3083 How to use certtool interactively:
3085 @itemize
3086 @item
3087 To generate parameters for Diffie Hellman key exchange, use the command:
3088 @example
3089 $ certtool --generate-dh-params --outfile dh.pem
3090 @end example
3092 @item
3093 To generate parameters for the RSA-EXPORT key exchange, use the command:
3094 @example
3095 $ certtool --generate-privkey --bits 512 --outfile rsa.pem
3096 @end example
3098 @end itemize
3100 @itemize
3102 @item
3103 To create a self signed certificate, use the command:
3104 @example
3105 $ certtool --generate-privkey --outfile ca-key.pem
3106 $ certtool --generate-self-signed --load-privkey ca-key.pem \
3107    --outfile ca-cert.pem
3108 @end example
3110 Note that a self-signed certificate usually belongs to a certificate
3111 authority, that signs other certificates.
3113 @item
3114 To create a private key, run:
3116 @example
3117 $ certtool --generate-privkey --outfile key.pem
3118 @end example
3120 @item
3121 To generate a certificate using the private key, use the command:
3123 @example
3124 $ certtool --generate-certificate --load-privkey key.pem \
3125    --outfile cert.pem --load-ca-certificate ca-cert.pem \
3126    --load-ca-privkey ca-key.pem
3127 @end example
3129 @item
3130 To create a certificate request (needed when the certificate is issued by
3131 another party), run:
3133 @example
3134 $ certtool --generate-request --load-privkey key.pem \
3135   --outfile request.pem
3136 @end example
3138 @item
3139 To generate a certificate using the previous request, use the command:
3141 @example
3142 $ certtool --generate-certificate --load-request request.pem \
3143    --outfile cert.pem \
3144    --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem
3145 @end example
3147 @item
3148 To view the certificate information, use:
3150 @example
3151 $ certtool --certificate-info --infile cert.pem
3152 @end example
3154 @item
3155 To generate a @acronym{PKCS} #12 structure using the previous key and
3156 certificate, use the command:
3158 @example
3159 $ certtool --load-certificate cert.pem --load-privkey key.pem \
3160   --to-p12 --outder --outfile key.p12
3161 @end example
3163 @item
3164 Proxy certificate can be used to delegate your credential to a
3165 temporary, typically short-lived, certificate.  To create one from the
3166 previously created certificate, first create a temporary key and then
3167 generate a proxy certificate for it, using the commands:
3169 @example
3170 $ certtool --generate-privkey > proxy-key.pem
3171 $ certtool --generate-proxy --load-ca-privkey key.pem \
3172   --load-privkey proxy-key.pem --load-certificate cert.pem \
3173   --outfile proxy-cert.pem
3174 @end example
3176 @item
3177 To create an empty Certificate Revocation List (CRL) do:
3179 @example
3180 $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem --load-ca-certificate x509-ca.pem
3181 @end example
3183 To create a CRL that contains some revoked certificates, place the
3184 certificates in a file and use @code{--load-certificate} as follows:
3186 @example
3187 $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem --load-ca-certificate x509-ca.pem --load-certificate revoked-certs.pem
3188 @end example
3190 @item
3191 To verify a Certificate Revocation List (CRL) do:
3193 @example
3194 $ certtool --verify-crl --load-ca-certificate x509-ca.pem < crl.pem
3195 @end example
3197 @end itemize
3199 Certtool's template file format:
3201 @itemize
3203 @item
3204 Firstly create a file named 'cert.cfg' that contains the information
3205 about the certificate. An example file is listed below.
3207 @item
3208 Then execute:
3210 @example
3211 $ certtool --generate-certificate cert.pem --load-privkey key.pem  \
3212    --template cert.cfg \
3213    --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem
3214 @end example
3216 @end itemize
3218 An example certtool template file:
3220 @example
3221 # X.509 Certificate options
3223 # DN options
3225 # The organization of the subject.
3226 organization = "Koko inc."
3228 # The organizational unit of the subject.
3229 unit = "sleeping dept."
3231 # The locality of the subject.
3232 # locality =
3234 # The state of the certificate owner.
3235 state = "Attiki"
3237 # The country of the subject. Two letter code.
3238 country = GR
3240 # The common name of the certificate owner.
3241 cn = "Cindy Lauper"
3243 # A user id of the certificate owner.
3244 #uid = "clauper"
3246 # If the supported DN OIDs are not adequate you can set
3247 # any OID here.
3248 # For example set the X.520 Title and the X.520 Pseudonym
3249 # by using OID and string pairs.
3250 #dn_oid = "2.5.4.12" "Dr." "2.5.4.65" "jackal"
3252 # This is deprecated and should not be used in new
3253 # certificates.
3254 # pkcs9_email = "none@@none.org"
3256 # The serial number of the certificate
3257 serial = 007
3259 # In how many days, counting from today, this certificate will expire.
3260 expiration_days = 700
3262 # X.509 v3 extensions
3264 # A dnsname in case of a WWW server.
3265 #dns_name = "www.none.org"
3267 # An IP address in case of a server.
3268 #ip_address = "192.168.1.1"
3270 # An email in case of a person
3271 email = "none@@none.org"
3273 # An URL that has CRLs (certificate revocation lists)
3274 # available. Needed in CA certificates.
3275 #crl_dist_points = "http://www.getcrl.crl/getcrl/"
3277 # Whether this is a CA certificate or not
3280 # Whether this certificate will be used for a TLS client
3281 #tls_www_client
3283 # Whether this certificate will be used for a TLS server
3284 #tls_www_server
3286 # Whether this certificate will be used to sign data (needed
3287 # in TLS DHE ciphersuites).
3288 signing_key
3290 # Whether this certificate will be used to encrypt data (needed
3291 # in TLS RSA ciphersuites). Note that it is prefered to use different
3292 # keys for encryption and signing.
3293 #encryption_key
3295 # Whether this key will be used to sign other certificates.
3296 #cert_signing_key
3298 # Whether this key will be used to sign CRLs.
3299 #crl_signing_key
3301 # Whether this key will be used to sign code.
3302 #code_signing_key
3304 # Whether this key will be used to sign OCSP data.
3305 #ocsp_signing_key
3307 # Whether this key will be used for time stamping.
3308 #time_stamping_key
3309 @end example
3311 @node Invoking psktool
3312 @section Invoking psktool
3313 @cindex psktool
3315 This is a program to manage @acronym{PSK} username and keys.
3317 @verbatim
3318 PSKtool help
3319 Usage : psktool [options]
3320      -u, --username username
3321                               specify username.
3322      -p, --passwd FILE        specify a password file.
3323      -n, --netconf-hint HINT
3324                               derive key from Netconf password, using 
3325                               HINT as the psk_identity_hint.
3326      -s, --keysize SIZE       specify the key size in bytes.
3327      -v, --version            prints the program's version number
3328      -h, --help               shows this help text
3329 @end verbatim
3331 Normally the file will generate random keys for the indicate username.
3332 You may also derive PSK keys from passwords, using the algorithm
3333 specified in @file{draft-ietf-netconf-tls-02.txt}.  The algorithm
3334 needs a PSK identity hint, which you specify using
3335 @code{--netconf-hint}.  To derive a PSK key from a password with an
3336 empty PSK identity hint, using @code{--netconf-hint ""}.
3338 @node Function reference
3339 @chapter Function Reference
3340 @cindex Function reference
3342 @menu
3343 * Core functions::
3344 * X.509 certificate functions::
3345 * GnuTLS-extra functions::
3346 * OpenPGP functions::
3347 * TLS Inner Application (TLS/IA) functions::
3348 * Error codes and descriptions::
3349 @end menu
3351 @node Core functions
3352 @section Core Functions
3354 The prototypes for the following functions lie in
3355 @file{gnutls/gnutls.h}.
3357 @include gnutls-api.texi
3359 @node X.509 certificate functions
3360 @section @acronym{X.509} Certificate Functions
3361 @anchor{sec:x509api}
3362 @cindex @acronym{X.509} Functions
3364 The following functions are to be used for @acronym{X.509} certificate handling.
3365 Their prototypes lie in @file{gnutls/x509.h}.
3367 @include x509-api.texi
3369 @node GnuTLS-extra functions
3370 @section @acronym{GnuTLS-extra} Functions
3371 @cindex @acronym{GnuTLS-extra} functions
3373 These functions are only available in the GPL version of the library
3374 called @code{gnutls-extra}. The prototypes for this library lie in
3375 @file{gnutls/extra.h}.
3377 @include gnutls-extra-api.texi
3379 @node OpenPGP functions
3380 @section @acronym{OpenPGP} Functions
3381 @cindex @acronym{OpenPGP} functions
3382 @anchor{sec:openpgpapi}
3384 The following functions are to be used for @acronym{OpenPGP}
3385 certificate handling.  Their prototypes lie in
3386 @file{gnutls/openpgp.h}.  You need to link with @file{libgnutls-extra}
3387 to be able to use these functions (@pxref{GnuTLS-extra functions}).
3389 @include pgp-api.texi
3391 @node TLS Inner Application (TLS/IA) functions
3392 @section @acronym{TLS} Inner Application (@acronym{TLS/IA}) Functions
3393 @cindex @acronym{TLS} Inner Application (@acronym{TLS/IA}) functions
3394 @cindex Inner Application (@acronym{TLS/IA}) functions
3396 The following functions are used for @acronym{TLS} Inner Application
3397 (@acronym{TLS/IA}).  Their prototypes lie in @file{gnutls/extra.h}.
3398 You need to link with @file{libgnutls-extra} to be able to use these
3399 functions (@pxref{GnuTLS-extra functions}).
3401 The typical control flow in an TLS/IA client (that would not require
3402 an Application Phase for resumed sessions) would be similar to the
3403 following:
3405 @example
3406 int client_avp (gnuls_session_t *session, void *ptr,
3407                 const char *last, size_t lastlen,
3408                 char **new, size_t *newlen)
3413 int main ()
3415   gnutls_ia_client_credentials_t iacred;
3417   gnutls_init (&session, GNUTLS_CLIENT);
3419   /* Enable TLS/IA. */
3420   gnutls_ia_allocate_client_credentials(&iacred);
3421   gnutls_ia_set_client_avp_function(iacred, client_avp);
3422   gnutls_credentials_set (session, GNUTLS_CRD_IA, iacred);
3424   ret = gnutls_handshake (session);
3425   // Error handling...
3427   if (gnutls_ia_handshake_p (session))
3428     @{
3429       ret = gnutls_ia_handshake (session);
3430       // Error handling...
3432 @end example
3434 See below for detailed descriptions of all the functions used above.
3436 The function @code{client_avp} would have to be implemented by your
3437 application.  The function is responsible for handling the AVP data.
3438 See @code{gnutls_ia_set_client_avp_function} below for more
3439 information on how that function should be implemented.
3441 The control flow in a typical server is similar to the above, use
3442 @code{gnutls_ia_server_credentials_t} instead of
3443 @code{gnutls_ia_client_credentials_t}, and replace the call to the
3444 client functions with the corresponding server functions.
3446 @include ia-api.texi
3448 @node Error codes and descriptions
3449 @section Error Codes and Descriptions
3450 @anchor{Error Codes}
3451 @cindex Error codes
3453 The error codes used throughout the library are described below.  The
3454 return code @code{GNUTLS_E_SUCCESS} indicate successful operation, and
3455 is guaranteed to have the value 0, so you can use it in logical
3456 expressions.
3458 @include error_codes.texi
3460 @node All the supported ciphersuites in GnuTLS
3461 @chapter All the Supported Ciphersuites in @acronym{GnuTLS}
3462 @anchor{ciphersuites}
3463 @cindex Ciphersuites
3465 @multitable @columnfractions .45 .20 .35
3467 @item @code{TLS_RSA_NULL_MD5} 
3468 @tab 0x00 0x01
3469 @tab RFC 2246
3471 @item @code{TLS_ANON_DH_3DES_EDE_CBC_SHA} 
3472 @tab 0x00 0x1B
3473 @tab RFC 2246
3475 @item @code{TLS_ANON_DH_ARCFOUR_MD5}
3476 @tab 0x00 0x18
3477 @tab RFC 2246
3479 @item @code{TLS_ANON_DH_AES_128_CBC_SHA}
3480 @tab 0x00 0x34
3481 @tab RFC 2246
3483 @item @code{TLS_ANON_DH_AES_256_CBC_SHA}
3484 @tab 0x00 0x3A
3485 @tab RFC 2246
3487 @item @code{TLS_RSA_ARCFOUR_SHA}
3488 @tab 0x00 0x05
3489 @tab  RFC 2246
3491 @item @code{TLS_RSA_ARCFOUR_MD5}
3492 @tab 0x00 0x04
3493 @tab RFC 2246
3495 @item @code{TLS_RSA_3DES_EDE_CBC_SHA}
3496 @tab 0x00 0x0A
3497 @tab RFC 2246
3499 @item @code{TLS_RSA_EXPORT_ARCFOUR_40_MD5}
3500 @tab 0x00 0x03
3501 @tab RFC 2246
3503 @item @code{TLS_DHE_DSS_3DES_EDE_CBC_SHA}
3504 @tab 0x00 0x13
3505 @tab RFC 2246
3507 @item @code{TLS_DHE_RSA_3DES_EDE_CBC_SHA}
3508 @tab 0x00 0x16
3509 @tab RFC 2246
3511 @item @code{TLS_RSA_AES_128_CBC_SHA}
3512 @tab 0x00 0x2F
3513 @tab RFC 3268
3515 @item @code{TLS_RSA_AES_256_CBC_SHA}
3516 @tab 0x00 0x35
3517 @tab RFC 3268
3519 @item @code{TLS_DHE_DSS_AES_256_CBC_SHA}
3520 @tab 0x00 0x38
3521 @tab RFC 3268
3523 @item @code{TLS_DHE_DSS_AES_128_CBC_SHA}
3524 @tab 0x00 0x32
3525 @tab RFC 3268
3527 @item @code{TLS_DHE_RSA_AES_256_CBC_SHA}
3528 @tab 0x00 0x39
3529 @tab RFC 3268
3531 @item @code{TLS_DHE_RSA_AES_128_CBC_SHA}
3532 @tab 0x00 0x33
3533 @tab RFC 3268
3535 @item @code{TLS_SRP_SHA_3DES_EDE_CBC_SHA}
3536 @tab 0x00 0x50
3537 @tab RFC 5054
3539 @item @code{TLS_SRP_SHA_AES_128_CBC_SHA}
3540 @tab 0x00 0x53
3541 @tab RFC 5054
3543 @item @code{TLS_SRP_SHA_AES_256_CBC_SHA}
3544 @tab 0x00 0x56
3545 @tab RFC 5054
3547 @item @code{TLS_SRP_SHA_RSA_3DES_EDE_CBC_SHA}
3548 @tab 0x00 0x51
3549 @tab RFC 5054
3551 @item @code{TLS_SRP_SHA_DSS_3DES_EDE_CBC_SHA}
3552 @tab 0x00 0x52
3553 @tab RFC 5054
3555 @item @code{TLS_SRP_SHA_RSA_AES_128_CBC_SHA}
3556 @tab 0x00 0x54
3557 @tab RFC 5054
3559 @item @code{TLS_SRP_SHA_DSS_AES_128_CBC_SHA}
3560 @tab 0x00 0x55
3561 @tab RFC 5054
3563 @item @code{TLS_SRP_SHA_RSA_AES_256_CBC_SHA}
3564 @tab 0x00 0x57
3565 @tab RFC 5054
3567 @item @code{TLS_SRP_SHA_DSS_AES_256_CBC_SHA}
3568 @tab 0x00 0x58
3569 @tab RFC 5054
3571 @item @code{TLS_DHE_DSS_ARCFOUR_SHA}
3572 @tab 0x00 0x66
3573 @tab draft-ietf-tls-56-bit-ciphersuites
3575 @item @code{TLS_PSK_ARCFOUR_SHA}
3576 @tab 0x00 0x8A
3577 @tab draft-ietf-tls-psk
3579 @item @code{TLS_PSK_3DES_EDE_CBC_SHA}
3580 @tab 0x00 0x8B
3581 @tab draft-ietf-tls-psk
3583 @item @code{TLS_PSK_AES_128_CBC_SHA}
3584 @tab 0x00 0x8C
3585 @tab draft-ietf-tls-psk
3587 @item @code{TLS_PSK_AES_256_CBC_SHA}
3588 @tab 0x00 0x8D
3589 @tab draft-ietf-tls-psk
3591 @end multitable
3594 @c Guile Bindings
3597 @include guile.texi
3599 @node Internal architecture of GnuTLS
3600 @chapter Internal Architecture of GnuTLS
3601 @cindex Internal architecture
3603 This chapter is to give a brief description of the
3604 way @acronym{GnuTLS} works. The focus is to give an idea
3605 to potential developers and those who want to know what
3606 happens inside the black box.
3608 @section The TLS Protocol
3609 The main needs for the TLS protocol to be used are
3610 shown in the image below.
3612 @image{gnutls-client-server-use-case,9cm}
3614 This is being accomplished by the following object diagram.
3615 Note that since @acronym{GnuTLS} is being developed in C
3616 object are just structures with attributes. The operations listed
3617 are functions that require the first parameter to be that object.
3618 @image{gnutls-objects,15cm}
3620 @section TLS Handshake Protocol
3621 The @acronym{GnuTLS} handshake protocol is implemented as a state
3622 machine that waits for input or returns immediately when the non-blocking
3623 transport layer functions are used. The main idea is shown in the following
3624 figure.
3626 @image{gnutls-handshake-state,9cm}
3628 Also the way the input is processed varies per ciphersuite. Several 
3629 implementations of the internal handlers are available and 
3630 @ref{gnutls_handshake} only multiplexes the input to the appropriate 
3631 handler. For example a @acronym{PSK} ciphersuite has a different 
3632 implementation of the @code{process_client_key_exchange} than a
3633 certificate ciphersuite.
3635 @image{gnutls-handshake-sequence,12cm}
3637 @section TLS Authentication Methods
3638 In @acronym{GnuTLS} authentication methods can be implemented quite easily.
3639 Since the required changes to add a new authentication method affect only the
3640 handshake protocol, a simple interface is used. An authentication method needs
3641 only to implement the functions as seen in the figure below.
3643 @image{gnutls-mod_auth_st,12cm}
3645 The functions that need to be implemented are the ones responsible for interpreting
3646 the handshake protocol messages. It is common for such functions to read data from
3647 one or more @code{credentials_t} structures@footnote{such as the @code{gnutls_certificate_credentials_t} structures} and write data, such as certificates, usernames etc. to @code{auth_info_t} structures.
3649 Simple examples of existing authentication methods can be seen in @code{auth_psk.c}
3650 for PSK ciphersuites and @code{auth_srp.c} for SRP ciphersuites. After implementing these functions
3651 the structure holding its pointers has to be registered in @code{gnutls_algorithms.c}
3652 in the @code{_gnutls_kx_algorithms} structure.
3654 @section TLS Extension Handling
3655 As with authentication methods, the TLS extensions handlers can be implemented
3656 using the following interface.
3658 @image{gnutls-extensions_st,12cm}
3660 Here there are two functions, one for receiving the extension data
3661 and one for sending. These functions have to check internally whether
3662 they operate in client or server side. 
3664 A simple example of an extension handler can be seen in @code{ext_srp.c}
3665 After implementing these functions, together with the extension number they
3666 handle, they have to be registered in @code{gnutls_extensions.c} in the 
3667 @code{_gnutls_extensions} structure.
3669 @subsection Adding a New TLS Extension
3671 Adding support for a new TLS extension is done from time to time, and
3672 the process to do so is not difficult.  Here are the steps you need to
3673 follow if you wish to do this yourself.  For sake of discussion, let's
3674 consider adding support for the hypothetical TLS extension
3675 @code{foobar}.
3677 @enumerate
3679 @item Modify @code{configure.in} to add @code{--enable-foobar} or @code{--disable-foobar}.
3681 Which to chose depends on whether you intend to make the extension be
3682 enabled by default.  Look at existing checks (i.e., SRP, authz) for
3683 how to model the code.  For example:
3685 @example
3686 AC_MSG_CHECKING([whether to disable foobar support])
3687 AC_ARG_ENABLE(foobar,
3688         AS_HELP_STRING([--disable-foobar],
3689                 [disable foobar support]),
3690         ac_enable_foobar=no)
3691 if test x$ac_enable_foobar != xno; then
3692  AC_MSG_RESULT(no)
3693  AC_DEFINE(ENABLE_FOOBAR, 1, [enable foobar])
3694 else
3695  ac_full=0
3696  AC_MSG_RESULT(yes)
3698 AM_CONDITIONAL(ENABLE_FOOBAR, test "$ac_enable_foobar" != "no")
3699 @end example
3701 @item Add IANA extension value to @code{extensions_t} in @code{gnutls_int.h}.
3703 A good name for the value would be GNUTLS_EXTENSION_FOOBAR.  Check
3704 with @url{http://www.iana.org/assignments/tls-extensiontype-values}
3705 for allocated values.  For experiments, you could pick a number but
3706 remember that some consider it a bad idea to deploy such modified
3707 version since it will lead to interoperability problems in the future
3708 when the IANA allocates that number to someone else, or when the
3709 foobar protocol is allocated another number.
3711 @item Add an entry to @code{_gnutls_extensions} in @code{gnutls_extensions.c}.
3713 A typical entry would be:
3715 @example
3716 #if ENABLE_FOOBAR
3717   GNUTLS_EXTENSION_ENTRY (GNUTLS_EXTENSION_FOOBAR,
3718                           _gnutls_foobar_recv_params,
3719                           _gnutls_foobar_send_params),
3720 #endif
3721 @end example
3723 The GNUTLS_EXTENSION_FOOBAR is the integer value you added to
3724 @code{gnutls_int.h} earlier.  The two functions are new functions that
3725 you will need to implement, most likely you'll need to add an
3726 @code{#include "ext_foobar.h"} as well.
3728 @item Add new files @code{ext_foobar.c} and @code{ext_foobar.h} that implements the extension.
3730 The functions you are responsible to add are those mentioned in the
3731 previous step.  As a starter, you could add this:
3733 @example
3735 _gnutls_foobar_recv_params (gnutls_session_t session,
3736                             const opaque * data,
3737                             size_t data_size)
3739   return 0;
3743 _gnutls_foobar_send_params (gnutls_session_t session,
3744                             opaque * data,
3745                             size_t _data_size)
3747   return 0;
3749 @end example
3751 The @code{_gnutls_foobar_recv_params} function is responsible for
3752 parsing incoming extension data (both in the client and server).
3754 The @code{_gnutls_foobar_send_params} function is responsible for
3755 sending extension data (both in the client and server).
3757 If you receive length fields that doesn't match, return
3758 @code{GNUTLS_E_UNEXPECTED_PACKET_LENGTH}.  If you receive invalid
3759 data, return @code{GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER}.  You can use
3760 other error codes too.  Return 0 on success.
3762 The function typically store some information in the @code{session}
3763 variable for later usage.  If you need to add new fields there, check
3764 @code{tls_ext_st} in @code{gnutls_int.h} and compare with existing TLS
3765 extension specific variables.
3767 Recall that both the client and server both send and receives
3768 parameters, and your code most likely will need to do different things
3769 depending on which mode it is in.  It may be useful to make this
3770 distinction explicit in the code.  Thus, for example, a better
3771 template than above would be:
3773 @example
3775 _gnutls_foobar_recv_params (gnutls_session_t session,
3776                             const opaque * data,
3777                             size_t data_size)
3779   if (session->security_parameters.entity == GNUTLS_CLIENT)
3780     return foobar_recv_client (session, data, data_size);
3781   else
3782     return foobar_recv_server (session, data, data_size);
3786 _gnutls_foobar_send_params (gnutls_session_t session,
3787                             opaque * data,
3788                             size_t data_size)
3790   if (session->security_parameters.entity == GNUTLS_CLIENT)
3791     return foobar_send_client (session, data, data_size);
3792   else
3793     return foobar_send_server (session, data, data_size);
3795 @end example
3797 The functions used would be declared as @code{static} functions, of
3798 the appropriate prototype, in the same file.
3800 When adding the files, you'll need to add them to @code{Makefile.am}
3801 as well, for example:
3803 @example
3804 if ENABLE_FOOBAR
3805 COBJECTS += ext_foobar.c
3806 HFILES += ext_foobar.h
3807 endif
3808 @end example
3810 @item Add API functions to enable/disable the extension.
3812 Normally the client will have one API to request use of the extension,
3813 and setting some extension specific data.  The server will have one
3814 API to let the library know that it is willing to accept the
3815 extension, often this is implemented through a callback but it doesn't
3816 have to.
3818 The APIs need to be added to @code{includes/gnutls/gnutls.h} or
3819 @code{includes/gnutls/extra.h} as appropriate.  It is recommended that
3820 if you don't have a requirement to use the LGPL license for your
3821 extension, that you place your work under the GPL license and thus in
3822 the libgnutls-extra library.
3824 You can implement the API function in the @code{ext_foobar.c} file, or
3825 if that file ends up becoming rather larger, add a
3826 @code{gnutls_foobar.c} file.
3828 @end enumerate
3830 @section Certificate Handling
3831 What is provided by the certificate handling functions
3832 is summarized in the following diagram.
3834 @image{gnutls-certificate-user-use-case,12cm}
3837 @node Copying Information
3838 @appendix Copying Information
3840 @menu
3841 * GNU Free Documentation License::   License for copying this manual.
3842 * GNU LGPL::                     License for copying the core GnuTLS library.
3843 * GNU GPL::                      License for copying GNUTLS extra and tools.
3844 @end menu
3846 @node GNU Free Documentation License
3847 @appendixsec GNU Free Documentation License
3849 @cindex FDL, GNU Free Documentation License
3851 @include fdl.texi
3853 @node GNU LGPL
3854 @appendixsec GNU Lesser General Public License
3855 @cindex LGPL, GNU Lesser General Public License
3856 @cindex License, GNU LGPL
3858 @include lgpl-2.1.texi
3860 @node GNU GPL
3861 @appendixsec GNU General Public License
3862 @cindex GPL, GNU General Public License
3863 @cindex License, GNU GPL
3865 @include gpl-3.0.texi
3867 @node Bibliography
3868 @unnumbered Bibliography
3870 @table @asis
3872 @item @anchor{CBCATT}[CBCATT]
3873 Bodo Moeller, "Security of CBC Ciphersuites in SSL/TLS: Problems and
3874 Countermeasures", 2002, available from
3875 @url{http://www.openssl.org/~bodo/tls-cbc.txt}.
3877 @item @anchor{GPGH}[GPGH]
3878 Mike Ashley, "The GNU Privacy Handbook", 2002, available from
3879 @url{http://www.gnupg.org/gph/en/manual.pdf}.
3881 @item @anchor{GUTPKI}[GUTPKI]
3882 Peter Gutmann, "Everything you never wanted to know about PKI but were
3883 forced to find out", Available from
3884 @url{http://www.cs.auckland.ac.nz/~pgut001/}.
3886 @item @anchor{RFC2246}[RFC2246]
3887 Tim Dierks and Christopher Allen, "The TLS Protocol Version 1.0",
3888 January 1999, Available from
3889 @url{http://www.ietf.org/rfc/rfc2246.txt}.
3891 @item @anchor{RFC4346}[RFC4346]
3892 Tim Dierks and Eric Rescorla, "The TLS Protocol Version 1.1", Match
3893 2006, Available from @url{http://www.ietf.org/rfc/rfc4346.txt}.
3895 @item @anchor{RFC2440}[RFC2440]
3896 Jon Callas, Lutz Donnerhacke, Hal Finney and Rodney Thayer, "OpenPGP
3897 Message Format", November 1998, Available from
3898 @url{http://www.ietf.org/rfc/rfc2440.txt}.
3900 @item @anchor{RFC4880}[RFC4880]
3901 Jon Callas, Lutz Donnerhacke, Hal Finney, David Shaw and Rodney
3902 Thayer, "OpenPGP Message Format", November 2007, Available from
3903 @url{http://www.ietf.org/rfc/rfc4880.txt}.
3905 @item @anchor{RFC4211}[RFC4211]
3906 J. Schaad, "Internet X.509 Public Key Infrastructure Certificate
3907 Request Message Format (CRMF)", September 2005, Available from
3908 @url{http://www.ietf.org/rfc/rfc4211.txt}.
3910 @item @anchor{RFC2817}[RFC2817]
3911 Rohit Khare and Scott Lawrence, "Upgrading to TLS Within HTTP/1.1",
3912 May 2000, Available from @url{http://www.ietf.org/rfc/rfc2817.txt}
3914 @item @anchor{RFC2818}[RFC2818]
3915 Eric Rescorla, "HTTP Over TLS", May 2000, Available from
3916 @url{http://www.ietf/rfc/rfc2818.txt}.
3918 @item @anchor{RFC2945}[RFC2945]
3919 Tom Wu, "The SRP Authentication and Key Exchange System", September
3920 2000, Available from @url{http://www.ietf.org/rfc/rfc2945.txt}.
3922 @item @anchor{RFC2986}[RFC2986]
3923 Magnus Nystrom and Burt Kaliski, "PKCS 10 v1.7: Certification Request
3924 Syntax Specification", November 2000, Available from
3925 @url{http://www.ietf.org/rfc/rfc2986.txt}.
3927 @item @anchor{RFC3280}[RFC3280]
3928 Russell Housley, Tim Polk, Warwick Ford and David Solo, "Internet
3929 X.509 Public Key Infrastructure Certificate and Certificate Revocation
3930 List (CRL) Profile", April 2002, Available from
3931 @url{http://www.ietf.org/rfc/rfc3280.txt}.
3933 @item @anchor{RFC3749}[RFC3749]
3934 Scott Hollenbeck, "Transport Layer Security Protocol Compression
3935 Methods", May 2004, Available from
3936 @url{http://www.ietf.org/rfc/rfc3749.txt}.
3938 @item @anchor{RFC3820}[RFC3820]
3939 Steven Tuecke, Von Welch, Doug Engert, Laura Pearlman, and Mary
3940 Thompson, "Internet X.509 Public Key Infrastructure (PKI) Proxy
3941 Certificate Profile", June 2004, available from
3942 @url{http://www.ietf.org/rfc3820}.
3944 @item @anchor{PKCS12}[PKCS12]
3945 RSA Laboratories, "PKCS 12 v1.0: Personal Information Exchange
3946 Syntax", June 1999, Available from @url{http://www.rsa.com}.
3948 @item @anchor{RESCORLA}[RESCORLA]
3949 Eric Rescorla, "SSL and TLS: Designing and Building Secure Systems",
3950 2001
3952 @item @anchor{SELKEY}[SELKEY]
3953 Arjen Lenstra and Eric Verheul, "Selecting Cryptographic Key Sizes",
3954 2003, available from @url{http://www.win.tue.nl/~klenstra/key.pdf}.
3956 @item @anchor{SSL3}[SSL3]
3957 Alan Freier, Philip Karlton and Paul Kocher, "The SSL Protocol Version
3958 3.0", November 1996, Available from
3959 @url{http://wp.netscape.com/eng/ssl3/draft302.txt}.
3961 @item @anchor{STEVENS}[STEVENS]
3962 Richard Stevens, "UNIX Network Programming, Volume 1", Prentice Hall
3963 PTR, January 1998
3965 @item @anchor{TLSEXT}[TLSEXT]
3966 Simon Blake-Wilson, Magnus Nystrom, David Hopwood, Jan Mikkelsen and
3967 Tim Wright, "Transport Layer Security (TLS) Extensions", June 2003,
3968 Available from @url{http://www.ietf.org/rfc/rfc3546.txt}.
3970 @item @anchor{TLSPGP}[TLSPGP]
3971 Nikos Mavrogiannopoulos, "Using OpenPGP keys for TLS authentication",
3972 April 2004, November 2007. Available from
3973 @url{http://www.ietf.org/rfc/rfc5081.txt}.
3975 @item @anchor{TLSSRP}[TLSSRP]
3976 David Taylor, Trevor Perrin, Tom Wu and Nikos Mavrogiannopoulos,
3977 "Using SRP for TLS Authentication", November 2007. Available from
3978 @url{http://www.ietf.org/rfc/rfc5054.txt}.
3980 @item @anchor{TLSPSK}[TLSPSK]
3981 Pasi Eronen and Hannes Tschofenig, "Pre-shared key Ciphersuites for
3982 TLS", December 2005, Available from
3983 @url{http://www.ietf.org/rfc/rfc4279.txt}.
3985 @item @anchor{TOMSRP}[TOMSRP]
3986 Tom Wu, "The Stanford SRP Authentication Project", Available at
3987 @url{http://srp.stanford.edu/}.
3989 @item @anchor{WEGER}[WEGER]
3990 Arjen Lenstra and Xiaoyun Wang and Benne de Weger, "Colliding X.509
3991 Certificates", Cryptology ePrint Archive, Report 2005/067, Available
3992 at @url{http://eprint.iacr.org/}.
3994 @end table
3996 @node Function and Data Index
3997 @unnumbered Function and Data Index
3999 @printindex fn
4001 @node Concept Index
4002 @unnumbered Concept Index
4004 @printindex cp
4006 @bye