Table of Contents ***************** GNU TLS 1 Preface 1.1 Getting Help 1.2 Commercial Support 1.3 Downloading and Installing 1.4 Bug Reports 1.5 Contributing 2 The Library 2.1 General Idea 2.2 Error Handling 2.3 Memory Handling 2.4 Callback Functions 3 Introduction to TLS 3.1 TLS Layers 3.2 The Transport Layer 3.3 The TLS Record Protocol 3.3.1 Encryption Algorithms Used in the Record Layer 3.3.2 Compression Algorithms Used in the Record Layer 3.3.3 Weaknesses and Countermeasures 3.4 The TLS Alert Protocol 3.5 The TLS Handshake Protocol 3.5.1 TLS Cipher Suites 3.5.2 Client Authentication 3.5.3 Resuming Sessions 3.5.4 Resuming Internals 3.6 TLS Extensions 3.6.1 Maximum Fragment Length Negotiation 3.6.2 Server Name Indication 3.7 Selecting Cryptographic Key Sizes 3.8 On SSL 2 and Older Protocols 4 Authentication Methods 4.1 Certificate Authentication 4.1.1 Authentication Using X.509 Certificates 4.1.2 Authentication Using OpenPGP Keys 4.1.3 Using Certificate Authentication 4.2 Anonymous Authentication 4.3 Authentication using SRP 4.4 Authentication using PSK 4.5 Authentication and Credentials 4.6 Parameters Stored in Credentials 5 More on Certificate Authentication 5.1 The X.509 Trust Model 5.1.1 X.509 Certificates 5.1.2 Verifying X.509 Certificate Paths 5.1.3 PKCS #10 Certificate Requests 5.1.4 PKCS #12 Structures 5.2 The OpenPGP Trust Model 5.2.1 OpenPGP Keys 5.2.2 Verifying an OpenPGP Key 5.3 Digital Signatures 5.3.1 Supported Algorithms 5.3.2 Trading Security for Interoperability 6 How To Use TLS in Application Protocols 6.1 Separate Ports 6.2 Upward Negotiation 7 How To Use GnuTLS in Applications 7.1 Preparation 7.1.1 Headers 7.1.2 Version Check 7.1.3 Debugging 7.1.4 Building the Source 7.2 Multi-Threaded Applications 7.3 Client Examples 7.3.1 Simple Client Example with Anonymous Authentication 7.3.2 Simple Client Example with X.509 Certificate Support 7.3.3 Obtaining Session Information 7.3.4 Verifying Peer's Certificate 7.3.5 Using a Callback to Select the Certificate to Use 7.3.6 Client with Resume Capability Example 7.3.7 Simple Client Example with SRP Authentication 7.3.8 Simple Client Example with TLS/IA Support 7.3.9 Helper Function for TCP Connections 7.4 Server Examples 7.4.1 Echo Server with X.509 Authentication 7.4.2 Echo Server with X.509 Authentication II 7.4.3 Echo Server with OpenPGP Authentication 7.4.4 Echo Server with SRP Authentication 7.4.5 Echo Server with Anonymous Authentication 7.5 Miscellaneous Examples 7.5.1 Checking for an Alert 7.5.2 X.509 Certificate Parsing Example 7.5.3 Certificate Request Generation 7.5.4 PKCS #12 Structure Generation 7.6 Compatibility with the OpenSSL Library 7.7 Opaque PRF Input TLS Extension 8 Included Programs 8.1 Invoking srptool 8.2 Invoking gnutls-cli 8.3 Invoking gnutls-cli-debug 8.4 Invoking gnutls-serv 8.4.1 Setting Up a Test HTTPS Server 8.5 Invoking certtool 9 Function Reference 9.1 Core Functions 9.2 X.509 Certificate Functions 9.3 GnuTLS-extra Functions 9.4 OpenPGP Functions 9.5 TLS Inner Application (TLS/IA) Functions 9.6 Error Codes and Descriptions 10 All the Supported Ciphersuites in GnuTLS 11 Guile Bindings 11.1 Guile Preparations 11.2 Guile API Conventions 11.2.1 Enumerates and Constants 11.2.2 Procedure Names 11.2.3 Representation of Binary Data 11.2.4 Input and Output 11.2.5 Exception Handling 11.3 Guile Examples 11.3.1 Anonymous Authentication Guile Example 11.3.2 OpenPGP Authentication Guile Example 11.3.3 Importing OpenPGP Keys Guile Example 11.4 Guile Reference 11.4.1 Core Interface 11.4.2 Extra Interface 12 Internal Architecture of GnuTLS 12.1 The TLS Protocol 12.2 TLS Handshake Protocol 12.3 TLS Authentication Methods 12.4 TLS Extension Handling 12.4.1 Adding a New TLS Extension 12.5 Certificate Handling Appendix A Copying Information A.1 GNU Free Documentation License A.2 GNU Lesser General Public License A.3 GNU General Public License Concept Index Function and Data Index Bibliography GNU TLS ******* This manual is last updated 6 May 2008 for version 2.2.3 of GNU TLS. Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". 1 Preface ********* This document tries to demonstrate and explain the GnuTLS library API. A brief introduction to the protocols and the technology involved, is also included so that an application programmer can better understand the GnuTLS purpose and actual offerings. Even if GnuTLS is a typical library software, it operates over several security and cryptographic protocols, which require the programmer to make careful and correct usage of them, otherwise he risks to offer just a false sense of security. Security and the network security terms are very general terms even for computer software thus cannot be easily restricted to a single cryptographic library. For that reason, do not consider a program secure just because it uses GnuTLS; there are several ways to compromise a program or a communication line and GnuTLS only helps with some of them. Although this document tries to be self contained, basic network programming and PKI knowlegde is assumed in most of it. A good introduction to networking can be found in [STEVENS] (*note Bibliography::) and for Public Key Infrastructure in [GUTPKI] (*note Bibliography::). Updated versions of the GnuTLS software and this document will be available from `http://www.gnutls.org/' and `http://www.gnu.org/software/gnutls/'. 1.1 Getting Help ================ A mailing list where users may help each other exists, and you can reach it by sending e-mail to . Archives of the mailing list discussions, and an interface to manage subscriptions, is available through the World Wide Web at `http://lists.gnu.org/mailman/listinfo/help-gnutls'. A mailing list for developers are also available, see `http://www.gnu.org/software/gnutls/lists.html'. Bug reports should be sent to , see *Note Bug Reports::. 1.2 Commercial Support ====================== Commercial support is available for users of GnuTLS. The kind of support that can be purchased may include: * Implement new features. Such as a new TLS extension. * Port GnuTLS to new platforms. This could include porting to an embedded platforms that may need memory or size optimization. * Integrating TLS as a security environment in your existing project. * System design of components related to TLS. If you are interested, please write to: Simon Josefsson Datakonsult Hagagatan 24 113 47 Stockholm Sweden E-mail: simon@josefsson.org If your company provide support related to GnuTLS and would like to be mentioned here, contact the author (*note Bug Reports::). 1.3 Downloading and Installing ============================== GnuTLS is available for download from the following URL: `http://www.gnutls.org/download.html' The latest version is stored in a file, e.g., `gnutls-2.2.3.tar.gz' where the `2.2.3' value is the highest version number in the directory. GnuTLS uses a Linux-like development cycle: even minor version numbers indicate a stable release and a odd minor version number indicates a development release. For example, GnuTLS 1.6.3 denote a stable release since 6 is even, and GnuTLS 1.7.11 denote a development release since 7 is odd. GnuTLS depends on Libgcrypt, and you will need to install Libgcrypt before installing GnuTLS. Libgcrypt is available from `ftp://ftp.gnupg.org/gcrypt/libgcrypt'. Libgcrypt needs another library, libgpg-error, and you need to install libgpg-error before installing Libgcrypt. Libgpg-error is available from `ftp://ftp.gnupg.org/gcrypt/libgpg-error'. Don't forget to verify the cryptographic signature after downloading source code packages. The package is then extracted, configured and built like many other packages that use Autoconf. For detailed information on configuring and building it, refer to the `INSTALL' file that is part of the distribution archive. Typically you invoke `./configure' and then `make check install'. There are a number of compile-time parameters, as discussed below. The compression libraries (libz and lzo) are optional dependencies. You can get libz from `http://www.zlib.net/'. You can get lzo from `http://www.oberhumer.com/opensource/lzo/'. If you do not have lzo installed, GnuTLS will enable an internal copy, called minilzo. Use parameter `--without-lzo' to disable LZO completely. Use parameter `--with-included-lzo' to unconditionally use the internal minilzo copy. The X.509 part of GnuTLS needs ASN.1 functionality, from a library called libtasn1. A copy of libtasn1 is included in GnuTLS. If you want to install it separately (e.g., to make it possibly to use libtasn1 in other programs), you can get it from `http://www.gnu.org/software/gnutls/download.html'. The OpenPGP part of GnuTLS-extra needs OpenCDK for parsing OpenPGP packets. A copy of OpenCDK is included in GnuTLS. If you want to install it separately (e.g., to make it possibly to use libtasn1 in other programs), you can get it from `http://www.gnu.org/software/gnutls/download.html'. Use parameter `--with-included-opencdk' to unconditionally use the internal copy of OpenCDK. Use parameter `--disable-openpgp-authentication' to disable the OpenPGP functionality in GnuTLS. Regarding the Guile bindings, there are additional installation considerations, see *Note Guile Preparations::. A few `configure' options may be relevant, summarized in the table. `--disable-srp-authentication' `--disable-psk-authentication' `--disable-anon-authentication' `--disable-extra-pki' `--disable-openpgp-authentication' `--disable-openssl-compatibility' Disable or enable particular features. Generally not recommended. For the complete list, refer to the output from `configure --help'. 1.4 Bug Reports =============== If you think you have found a bug in GnuTLS, please investigate it and report it. * Please make sure that the bug is really in GnuTLS, and preferably also check that it hasn't already been fixed in the latest version. * You have to send us a test case that makes it possible for us to reproduce the bug. * You also have to explain what is wrong; if you get a crash, or if the results printed are not good and in that case, in what way. Make sure that the bug report includes all information you would need to fix this kind of bug for someone else. Please make an effort to produce a self-contained report, with something definite that can be tested or debugged. Vague queries or piecemeal messages are difficult to act on and don't help the development effort. If your bug report is good, we will do our best to help you to get a corrected version of the software; if the bug report is poor, we won't do anything about it (apart from asking you to send better bug reports). If you think something in this manual is unclear, or downright incorrect, or if the language needs to be improved, please also send a note. Send your bug report to: `bug-gnutls@gnu.org' 1.5 Contributing ================ If you want to submit a patch for inclusion - from solve a typo you discovered, up to adding support for a new feature - you should submit it as a bug report (*note Bug Reports::). There are some things that you can do to increase the chances for it to be included in the official package. Unless your patch is very small (say, under 10 lines) we require that you assign the copyright of your work to the Free Software Foundation. This is to protect the freedom of the project. If you have not already signed papers, we will send you the necessary information when you submit your contribution. For contributions that doesn't consist of actual programming code, the only guidelines are common sense. Use it. For code contributions, a number of style guides will help you: * Coding Style. Follow the GNU Standards document (*note GNU Coding Standards: (standards)top.). If you normally code using another coding standard, there is no problem, but you should use `indent' to reformat the code (*note GNU Indent: (indent)top.) before submitting your work. * Use the unified diff format `diff -u'. * Return errors. No reason whatsoever should abort the execution of the library. Even memory allocation errors, e.g. when malloc return NULL, should work although result in an error code. * Design with thread safety in mind. Don't use global variables. Don't even write to per-handle global variables unless the documented behaviour of the function you write is to write to the per-handle global variable. * Avoid using the C math library. It causes problems for embedded implementations, and in most situations it is very easy to avoid using it. * Document your functions. Use comments before each function headers, that, if properly formatted, are extracted into Texinfo manuals and GTK-DOC web pages. * Supply a ChangeLog and NEWS entries, where appropriate. 2 The Library ************* In brief GnuTLS can be described as a library which offers an API to access secure communication protocols. These protocols provide privacy over insecure lines, and were designed to prevent eavesdropping, tampering, or message forgery. Technically GnuTLS is a portable ANSI C based library which implements the TLS 1.1 and SSL 3.0 protocols (*Note Introduction to TLS::, for a more detailed description of the protocols), accompanied with the required framework for authentication and public key infrastructure. The library is available under the GNU Lesser GPL license(1). Important features of the GnuTLS library include: * Support for TLS 1.0, TLS 1.1, and SSL 3.0 protocols. * Support for both X.509 and OpenPGP certificates. * Support for handling and verification of certificates. * Support for SRP for TLS authentication. * Support for PSK for TLS authentication. * Support for TLS Extension mechanism. * Support for TLS Compression Methods. Additionally GnuTLS provides a limited emulation API for the widely used OpenSSL(2) library, to ease integration with existing applications. GnuTLS consists of three independent parts, namely the "TLS protocol part", the "Certificate part", and the "Crypto backend" part. The `TLS protocol part' is the actual protocol implementation, and is entirely implemented within the GnuTLS library. The `Certificate part' consists of the certificate parsing, and verification functions which is partially implemented in the GnuTLS library. The Libtasn1(3), a library which offers ASN.1 parsing capabilities, is used for the X.509 certificate parsing functions, and Opencdk(4) is used for the OpenPGP key support in GnuTLS. The "Crypto backend" is provided by the Libgcrypt(5) library. In order to ease integration in embedded systems, parts of the GnuTLS library can be disabled at compile time. That way a small library, with the required features, can be generated. ---------- Footnotes ---------- (1) A copy of the license is included in the distribution (2) `http://www.openssl.org/' (3) `ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/libtasn1/' (4) `ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/opencdk/' (5) `ftp://ftp.gnupg.org/gcrypt/alpha/libgcrypt/' 2.1 General Idea ================ A brief description of how GnuTLS works internally is shown at the figure below. This section may be easier to understand after having seen the examples (*note examples::). As shown in the figure, there is a read-only global state that is initialized once by the global initialization function. This global structure, among others, contains the memory allocation functions used, and some structures needed for the ASN.1 parser. This structure is never modified by any GnuTLS function, except for the deinitialization function which frees all memory allocated in the global structure and is called after the program has permanently finished using GnuTLS. The credentials structure is used by some authentication methods, such as certificate authentication (*note Certificate Authentication::). A credentials structure may contain certificates, private keys, temporary parameters for diffie hellman or RSA key exchange, and other stuff that may be shared between several TLS sessions. This structure should be initialized using the appropriate initialization functions. For example an application which uses certificate authentication would probably initialize the credentials, using the appropriate functions, and put its trusted certificates in this structure. The next step is to associate the credentials structure with each TLS session. A GnuTLS session contains all the required stuff for a session to handle one secure connection. This session calls directly to the transport layer functions, in order to communicate with the peer. Every session has a unique session ID shared with the peer. Since TLS sessions can be resumed, servers would probably need a database backend to hold the session's parameters. Every GnuTLS session after a successful handshake calls the appropriate backend function (*Note resume::, for information on initialization) to store the newly negotiated session. The session database is examined by the server just after having received the client hello(1), and if the session ID sent by the client, matches a stored session, the stored session will be retrieved, and the new session will be a resumed one, and will share the same session ID with the previous one. ---------- Footnotes ---------- (1) The first message in a TLS handshake 2.2 Error Handling ================== In GnuTLS most functions return an integer type as a result. In almost all cases a zero or a positive number means success, and a negative number indicates failure, or a situation that some action has to be taken. Thus negative error codes may be fatal or not. Fatal errors terminate the connection immediately and further sends and receives will be disallowed. An example of a fatal error code is `GNUTLS_E_DECRYPTION_FAILED'. Non-fatal errors may warn about something, i.e., a warning alert was received, or indicate the some action has to be taken. This is the case with the error code `GNUTLS_E_REHANDSHAKE' returned by *note gnutls_record_recv::. This error code indicates that the server requests a re-handshake. The client may ignore this request, or may reply with an alert. You can test if an error code is a fatal one by using the *note gnutls_error_is_fatal::. If any non fatal errors, that require an action, are to be returned by a function, these error codes will be documented in the function's reference. *Note Error Codes::, for all the error codes. 2.3 Memory Handling =================== GnuTLS internally handles heap allocated objects differently, depending on the sensitivity of the data they contain. However for performance reasons, the default memory functions do not overwrite sensitive data from memory, nor protect such objects from being written to the swap. In order to change the default behavior the *note gnutls_global_set_mem_functions:: function is available which can be used to set other memory handlers than the defaults. The Libgcrypt library on which GnuTLS depends, has such secure memory allocation functions available. These should be used in cases where even the system's swap memory is not considered secure. See the documentation of Libgcrypt for more information. 2.4 Callback Functions ====================== There are several cases where GnuTLS may need some out of band input from your program. This is now implemented using some callback functions, which your program is expected to register. An example of this type of functions are the push and pull callbacks which are used to specify the functions that will retrieve and send data to the transport layer. * *note gnutls_transport_set_push_function:: * *note gnutls_transport_set_pull_function:: Other callback functions such as the one set by *note gnutls_srp_set_server_credentials_function::, may require more complicated input, including data to be allocated. These callbacks should allocate and free memory using the functions shown below. * *note gnutls_malloc:: * *note gnutls_free:: 3 Introduction to TLS ********************* TLS stands for "Transport Layer Security" and is the successor of SSL, the Secure Sockets Layer protocol [SSL3] (*note Bibliography::) designed by Netscape. TLS is an Internet protocol, defined by IETF(1), described in RFC 2246 and also in [RESCOLA] (*note Bibliography::). The protocol provides confidentiality, and authentication layers over any reliable transport layer. The description, below, refers to TLS 1.0 but also applies to TLS 1.1 [RFC4346] (*note Bibliography::) and SSL 3.0, since the differences of these protocols are minor. Older protocols such as SSL 2.0 are not discussed nor implemented in GnuTLS since they are not considered secure today. ---------- Footnotes ---------- (1) IETF, or Internet Engineering Task Force, is a large open international community of network designers, operators, vendors, and researchers concerned with the evolution of the Internet architecture and the smooth operation of the Internet. It is open to any interested individual. 3.1 TLS Layers ============== TLS is a layered protocol, and consists of the Record Protocol, the Handshake Protocol and the Alert Protocol. The Record Protocol is to serve all other protocols and is above the transport layer. The Record protocol offers symmetric encryption, data authenticity, and optionally compression. The Alert protocol offers some signaling to the other protocols. It can help informing the peer for the cause of failures and other error conditions. *Note The Alert Protocol::, for more information. The alert protocol is above the record protocol. The Handshake protocol is responsible for the security parameters' negotiation, the initial key exchange and authentication. *Note The Handshake Protocol::, for more information about the handshake protocol. The protocol layering in TLS is shown in the figure below. 3.2 The Transport Layer ======================= TLS is not limited to one transport layer, it can be used above any transport layer, as long as it is a reliable one. A set of functions is provided and their purpose is to load to GnuTLS the required callbacks to access the transport layer. * *note gnutls_transport_set_push_function:: * *note gnutls_transport_set_pull_function:: * *note gnutls_transport_set_ptr:: * *note gnutls_transport_set_lowat:: * *note gnutls_transport_set_errno:: These functions accept a callback function as a parameter. The callback functions should return the number of bytes written, or -1 on error and should set `errno' appropriately. In some environments, setting `errno' is unreliable, for example Windows have several errno variables in different CRTs, or it may be that errno is not a thread-local variable. If this is a concern to you, call `gnutls_transport_set_errno' with the intended errno value instead of setting `errno' directly. GnuTLS currently only interprets the EINTR and EAGAIN errno values and returns the corresponding GnuTLS error codes `GNUTLS_E_INTERRUPTED' and `GNUTLS_E_AGAIN'. These values are usually returned by interrupted system calls, or when non blocking IO is used. All GnuTLS functions can be resumed (called again), if any of these error codes is returned. The error codes above refer to the system call, not the GnuTLS function, since signals do not interrupt GnuTLS' functions. For non blocking sockets or other custom made pull/push functions the *note gnutls_transport_set_lowat:: must be called, with a zero low water mark value. By default, if the transport functions are not set, GnuTLS will use the Berkeley Sockets functions. In this case GnuTLS will use some hacks in order for `select' to work, thus making it easy to add TLS support to existing TCP/IP servers. 3.3 The TLS Record Protocol =========================== The Record protocol is the secure communications provider. Its purpose is to encrypt, authenticate and --optionally-- compress packets. The following functions are available: *note gnutls_record_send::: To send a record packet (with application data). *note gnutls_record_recv::: To receive a record packet (with application data). *note gnutls_record_get_direction::: To get the direction of the last interrupted function call. As you may have already noticed, the functions which access the Record protocol, are quite limited, given the importance of this protocol in TLS. This is because the Record protocol's parameters are all set by the Handshake protocol. The Record protocol initially starts with NULL parameters, which means no encryption, and no MAC is used. Encryption and authentication begin just after the handshake protocol has finished. 3.3.1 Encryption Algorithms Used in the Record Layer ---------------------------------------------------- Confidentiality in the record layer is achieved by using symmetric block encryption algorithms like `3DES', `AES'(1), or stream algorithms like `ARCFOUR_128'(2). Ciphers are encryption algorithms that use a single, secret, key to encrypt and decrypt data. Block algorithms in TLS also provide protection against statistical analysis of the data. Thus, if you're using the TLS protocol, a random number of blocks will be appended to data, to prevent eavesdroppers from guessing the actual data size. Supported cipher algorithms: `3DES_CBC' `3DES_CBC' is the DES block cipher algorithm used with triple encryption (EDE). Has 64 bits block size and is used in CBC mode. `ARCFOUR_128' ARCFOUR is a fast stream cipher. `ARCFOUR_40' This is the ARCFOUR cipher that is fed with a 40 bit key, which is considered weak. `AES_CBC' AES or RIJNDAEL is the block cipher algorithm that replaces the old DES algorithm. Has 128 bits block size and is used in CBC mode. This is not officially supported in TLS. Supported MAC algorithms: `MAC_MD5' MD5 is a cryptographic hash algorithm designed by Ron Rivest. Outputs 128 bits of data. `MAC_SHA' SHA is a cryptographic hash algorithm designed by NSA. Outputs 160 bits of data. ---------- Footnotes ---------- (1) AES, or Advanced Encryption Standard, is actually the RIJNDAEL algorithm. This is the algorithm that replaced DES. (2) `ARCFOUR_128' is a compatible algorithm with RSA's RC4 algorithm, which is considered to be a trade secret. 3.3.2 Compression Algorithms Used in the Record Layer ----------------------------------------------------- The TLS record layer also supports compression. The algorithms implemented in GnuTLS can be found in the table below. All the algorithms except for DEFLATE which is referenced in [RFC3749] (*note Bibliography::), should be considered as GnuTLS' extensions(1), and should be advertised only when the peer is known to have a compliant client, to avoid interoperability problems. The included algorithms perform really good when text, or other compressible data are to be transfered, but offer nothing on already compressed data, such as compressed images, zipped archives etc. These compression algorithms, may be useful in high bandwidth TLS tunnels, and in cases where network usage has to be minimized. As a drawback, compression increases latency. The record layer compression in GnuTLS is implemented based on the proposal [RFC3749] (*note Bibliography::). The supported compression algorithms are: `DEFLATE' Zlib compression, using the deflate algorithm. `LZO' LZO is a very fast compression algorithm. This algorithm is only available if the GnuTLS-extra library has been initialized and the private extensions are enabled. ---------- Footnotes ---------- (1) You should use *note gnutls_handshake_set_private_extensions:: to enable private extensions. 3.3.3 Weaknesses and Countermeasures ------------------------------------ Some weaknesses that may affect the security of the Record layer have been found in TLS 1.0 protocol. These weaknesses can be exploited by active attackers, and exploit the facts that 1. TLS has separate alerts for "decryption_failed" and "bad_record_mac" 2. The decryption failure reason can be detected by timing the response time. 3. The IV for CBC encrypted packets is the last block of the previous encrypted packet. Those weaknesses were solved in TLS 1.1 [RFC4346] (*note Bibliography::) which is implemented in GnuTLS. For a detailed discussion see the archives of the TLS Working Group mailing list and the paper [CBCATT] (*note Bibliography::). 3.4 The TLS Alert Protocol ========================== The Alert protocol is there to allow signals to be sent between peers. These signals are mostly used to inform the peer about the cause of a protocol failure. Some of these signals are used internally by the protocol and the application protocol does not have to cope with them (see `GNUTLS_A_CLOSE_NOTIFY'), and others refer to the application protocol solely (see `GNUTLS_A_USER_CANCELLED'). An alert signal includes a level indication which may be either fatal or warning. Fatal alerts always terminate the current connection, and prevent future renegotiations using the current session ID. The alert messages are protected by the record protocol, thus the information that is included does not leak. You must take extreme care for the alert information not to leak to a possible attacker, via public log files etc. *note gnutls_alert_send::: To send an alert signal. *note gnutls_error_to_alert::: To map a gnutls error number to an alert signal. *note gnutls_alert_get::: Returns the last received alert. *note gnutls_alert_get_name::: Returns the name, in a character array, of the given alert. 3.5 The TLS Handshake Protocol ============================== The Handshake protocol is responsible for the ciphersuite negotiation, the initial key exchange, and the authentication of the two peers. This is fully controlled by the application layer, thus your program has to set up the required parameters. Available functions to control the handshake protocol include: *note gnutls_priority_init::: To initialize a priority set of ciphers. *note gnutls_priority_deinit::: To deinitialize a priority set of ciphers. *note gnutls_priority_set::: To associate a priority set with a TLS session. *note gnutls_priority_set_direct::: To directly associate a session with a given priority string. *note gnutls_credentials_set::: To set the appropriate credentials structures. *note gnutls_certificate_server_set_request::: To set whether client certificate is required or not. *note gnutls_handshake::: To initiate the handshake. 3.5.1 TLS Cipher Suites ----------------------- The Handshake Protocol of TLS negotiates cipher suites of the form `TLS_DHE_RSA_WITH_3DES_CBC_SHA'. The usual cipher suites contain these parameters: * The key exchange algorithm. `DHE_RSA' in the example. * The Symmetric encryption algorithm and mode `3DES_CBC' in this example. * The MAC(1) algorithm used for authentication. `MAC_SHA' is used in the above example. The cipher suite negotiated in the handshake protocol will affect the Record Protocol, by enabling encryption and data authentication. Note that you should not over rely on TLS to negotiate the strongest available cipher suite. Do not enable ciphers and algorithms that you consider weak. The priority functions, dicussed above, allow the application layer to enable and set priorities on the individual ciphers. It may imply that all combinations of ciphersuites are allowed, but this is not true. For several reasons, not discussed here, some combinations were not defined in the TLS protocol. The supported ciphersuites are shown in *note ciphersuites::. 3.5.2 Client Authentication --------------------------- In the case of ciphersuites that use certificate authentication, the authentication of the client is optional in TLS. A server may request a certificate from the client -- using the *note gnutls_certificate_server_set_request:: function. If a certificate is to be requested from the client during the handshake, the server will send a certificate request message that contains a list of acceptable certificate signers. In GnuTLS the certificate signers list is constructed using the trusted Certificate Authorities by the server. That is the ones set using * *note gnutls_certificate_set_x509_trust_file:: * *note gnutls_certificate_set_x509_trust_mem:: Sending of the names of the CAs can be controlled using *note gnutls_certificate_send_x509_rdn_sequence::. The client, then, may send a certificate, signed by one of the server's acceptable signers. 3.5.3 Resuming Sessions ----------------------- The *note gnutls_handshake:: function, is expensive since a lot of calculations are performed. In order to support many fast connections to the same server a client may use session resuming. *Session resuming* is a feature of the TLS protocol which allows a client to connect to a server, after a successful handshake, without the expensive calculations. This is achieved by using the previously established keys. GnuTLS supports this feature, and the example (*note ex:resume-client::) illustrates a typical use of it. Keep in mind that sessions are expired after some time, for security reasons, thus it may be normal for a server not to resume a session even if you requested that. Also note that you must enable, using the priority functions, at least the algorithms used in the last session. 3.5.4 Resuming Internals ------------------------ The resuming capability, mostly in the server side, is one of the problems of a thread-safe TLS implementations. The problem is that all threads must share information in order to be able to resume sessions. The gnutls approach is, in case of a client, to leave all the burden of resuming to the client. I.e., copy and keep the necessary parameters. See the functions: * *note gnutls_session_get_data:: * *note gnutls_session_get_id:: * *note gnutls_session_set_data:: The server side is different. A server has to specify some callback functions which store, retrieve and delete session data. These can be registered with: * *note gnutls_db_set_remove_function:: * *note gnutls_db_set_store_function:: * *note gnutls_db_set_retrieve_function:: * *note gnutls_db_set_ptr:: It might also be useful to be able to check for expired sessions in order to remove them, and save space. The function *note gnutls_db_check_entry:: is provided for that reason. ---------- Footnotes ---------- (1) MAC stands for Message Authentication Code. It can be described as a keyed hash algorithm. See RFC2104. 3.6 TLS Extensions ================== A number of extensions to the TLS protocol have been proposed mainly in [TLSEXT] (*note Bibliography::). The extensions supported in GnuTLS are: * Maximum fragment length negotiation * Server name indication and they will be discussed in the subsections that follow. 3.6.1 Maximum Fragment Length Negotiation ----------------------------------------- This extension allows a TLS implementation to negotiate a smaller value for record packet maximum length. This extension may be useful to clients with constrained capabilities. See the *note gnutls_record_set_max_size:: and the *note gnutls_record_get_max_size:: functions. 3.6.2 Server Name Indication ---------------------------- A common problem in HTTPS servers is the fact that the TLS protocol is not aware of the hostname that a client connects to, when the handshake procedure begins. For that reason the TLS server has no way to know which certificate to send. This extension solves that problem within the TLS protocol, and allows a client to send the HTTP hostname before the handshake begins within the first handshake packet. The functions *note gnutls_server_name_set:: and *note gnutls_server_name_get:: can be used to enable this extension, or to retrieve the name sent by a client. 3.7 Selecting Cryptographic Key Sizes ===================================== In TLS, since a lot of algorithms are involved, it is not easy to set a consistent security level. For this reason this section will present some correspondance between key sizes of symmetric algorithms and public key algorithms based on the most conservative values of [SELKEY] (*note Bibliography::). Those can be used to generate certificates with appropriate key sizes as well as parameters for Diffie Hellman and SRP authentication. Year Symmetric key RSA key size, ECC key size size DH and SRP prime size 1982 56 417 105 1988 61 566 114 2002 72 1028 139 2015 82 1613 173 2028 92 2362 210 2040 101 3214 244 2050 109 4047 272 The first column provides an estimation of the year until these parameters are considered safe and the rest of the columns list the parameters for the various algorithms. Note however that the values suggested here are nothing more than an educated 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 used in TLS are selected in a conservative way and such catastrophic breakthroughs or failures are believed to be unlikely. 3.8 On SSL 2 and Older Protocols ================================ One of the initial decisions in the GnuTLS development was to implement the known security protocols for the transport layer. Initially TLS 1.0 was implemented since it was the latest at that time, and was considered to be the most advanced in security properties. Later the SSL 3.0 protocol was implemented since it is still the only protocol supported by several servers and there are no serious security vulnerabilities known. One question that may arise is why we didn't implement SSL 2.0 in the library. There are several reasons, most important being that it has serious security flaws, unacceptable for a modern security library. Other than that, this protocol is barely used by anyone these days since it has been deprecated since 1996. The security problems in SSL 2.0 include: * Message integrity compromised. The SSLv2 message authentication uses the MD5 function, and is insecure. * Man-in-the-middle attack. There is no protection of the handshake in SSLv2, which permits a man-in-the-middle attack. * Truncation attack. SSLv2 relies on TCP FIN to close the session, so the attacker can forge a TCP FIN, and the peer cannot tell if it was a legitimate end of data or not. * Weak message integrity for export ciphers. The cryptographic keys in SSLv2 are used for both message authentication and encryption, so if weak encryption schemes are negotiated (say 40-bit keys) the message authentication code use the same weak key, which isn't necessary. Other protocols such as Microsoft's PCT 1 and PCT 2 were not implemented because they were also abandoned and deprecated by SSL 3.0 and later TLS 1.0. 4 Authentication Methods ************************ The TLS protocol provides confidentiality and encryption, but also offers authentication, which is a prerequisite for a secure connection. The available authentication methods in GnuTLS are: * Certificate authentication * Anonymous authentication * SRP authentication * PSK authentication 4.1 Certificate Authentication ============================== 4.1.1 Authentication Using X.509 Certificates --------------------------------------------- X.509 certificates contain the public parameters, of a public key algorithm, and an authority's signature, which proves the authenticity of the parameters. *Note The X.509 trust model::, for more information on X.509 protocols. 4.1.2 Authentication Using OpenPGP Keys --------------------------------------- OpenPGP keys also contain public parameters of a public key algorithm, and signatures from several other parties. Depending on whether a signer is trusted the key is considered trusted or not. GnuTLS's OpenPGP authentication implementation is based on the [TLSPGP] (*note Bibliography::) proposal. *Note The OpenPGP trust model::, for more information about the OpenPGP trust model. For a more detailed introduction to OpenPGP and GnuPG see [GPGH] (*note Bibliography::). 4.1.3 Using Certificate Authentication -------------------------------------- In GnuTLS both the OpenPGP and X.509 certificates are part of the certificate authentication and thus are handled using a common API. When using certificates the server is required to have at least one certificate and private key pair. A client may or may not have such a pair. The certificate and key pair should be loaded, before any TLS session is initialized, in a certificate credentials structure. This should be done by using *note gnutls_certificate_set_x509_key_file:: or *note gnutls_certificate_set_openpgp_key_file:: depending on the certificate type. In the X.509 case, the functions will also accept and use a certificate list that leads to a trusted authority. The certificate list must be ordered in such way that every certificate certifies the one before it. The trusted authority's certificate need not to be included, since the peer should possess it already. As an alternative, a callback may be used so the server or the client specify the certificate and the key at the handshake time. That callback can be set using the functions: * *note gnutls_certificate_server_set_retrieve_function:: * *note gnutls_certificate_client_set_retrieve_function:: Certificate verification is possible by loading the trusted authorities into the credentials structure by using *note gnutls_certificate_set_x509_trust_file:: or *note gnutls_certificate_set_openpgp_keyring_file:: for openpgp keys. Note however that the peer's certificate is not automatically verified, you should call *note gnutls_certificate_verify_peers2::, after a successful handshake, to verify the signatures of the certificate. An alternative way, which reports a more detailed verification output, is to use *note gnutls_certificate_get_peers:: to obtain the raw certificate of the peer and verify it using the functions discussed in *note The X.509 trust model::. In a handshake, the negotiated cipher suite depends on the certificate's parameters, so not all key exchange methods will be available with some certificates. GnuTLS will disable ciphersuites that are not compatible with the key, or the enabled authentication methods. For example keys marked as sign-only, will not be able to access the plain RSA ciphersuites, but only the `DHE_RSA' ones. It is recommended not to use RSA keys for both signing and encryption. If possible use the same key for the `DHE_RSA' and `RSA_EXPORT' ciphersuites, which use signing, and a different key for the plain RSA ciphersuites, which use encryption. All the key exchange methods shown below are available in certificate authentication. Note that the DHE key exchange methods are generally slower(1) than plain RSA and require Diffie Hellman parameters to be generated and associated with a credentials structure, by the server. The `RSA-EXPORT' method also requires 512 bit RSA parameters, that should also be generated and associated with the credentials structure. See the functions: * *note gnutls_dh_params_generate2:: * *note gnutls_certificate_set_dh_params:: * *note gnutls_rsa_params_generate2:: * *note gnutls_certificate_set_rsa_export_params:: Sometimes in order to avoid bottlenecks in programs it is usefull to store and read parameters from formats that can be generated by external programs such as `certtool'. This is possible with GnuTLS by using the following functions: * *note gnutls_dh_params_import_pkcs3:: * *note gnutls_rsa_params_import_pkcs1:: * *note gnutls_dh_params_export_pkcs3:: * *note gnutls_rsa_params_export_pkcs1:: Key exchange algorithms for OpenPGP and X.509 certificates: `RSA:' The RSA algorithm is used to encrypt a key and send it to the peer. The certificate must allow the key to be used for encryption. `RSA_EXPORT:' The RSA algorithm is used to encrypt a key and send it to the peer. In the EXPORT algorithm, the server signs temporary RSA parameters of 512 bits -- which are considered weak -- and sends them to the client. `DHE_RSA:' The RSA algorithm is used to sign Ephemeral Diffie Hellman parameters which are sent to the peer. The key in the certificate must allow the key to be used for signing. Note that key exchange algorithms which use Ephemeral Diffie Hellman parameters, offer perfect forward secrecy. That means that even if the private key used for signing is compromised, it cannot be used to reveal past session data. `DHE_DSS:' The DSS algorithm is used to sign Ephemeral Diffie Hellman parameters which are sent to the peer. The certificate must contain DSA parameters to use this key exchange algorithm. DSS stands for Digital Signature Standard. ---------- Footnotes ---------- (1) It really depends on the group used. Primes with lesser bits are always faster, but also easier to break. Values less than 768 should not be used today 4.2 Anonymous Authentication ============================ The anonymous key exchange performs encryption but there is no indication of the identity of the peer. This kind of authentication is vulnerable to a man in the middle attack, but this protocol can be used even if there is no prior communication and trusted parties with the peer, or when full anonymity is required. Unless really required, do not use anonymous authentication. Available key exchange methods are shown below. Note that the key exchange methods for anonymous authentication require Diffie Hellman parameters to be generated by the server and associated with an anonymous credentials structure. Supported anonymous key exchange algorithms: `ANON_DH:' This algorithm exchanges Diffie Hellman parameters. 4.3 Authentication using SRP ============================ Authentication via the Secure Remote Password protocol, SRP(1), is supported. The SRP key exchange is an extension to the TLS protocol, and it is a password based authentication (unlike X.509 or OpenPGP that use certificates). The two peers can be identified using a single password, or there can be combinations where the client is authenticated using SRP and the server using a certificate. The advantage of SRP authentication, over other proposed secure password authentication schemes, is that SRP does not require the server to hold the user's password. This kind of protection is similar to the one used traditionally in the _UNIX_ `/etc/passwd' file, where the contents of this file did not cause harm to the system security if they were revealed. The SRP needs instead of the plain password something called a verifier, which is calculated using the user's password, and if stolen cannot be used to impersonate the user. Check [TOMSRP] (*note Bibliography::) for a detailed description of the SRP protocol and the Stanford SRP libraries, which includes a PAM module that synchronizes the system's users passwords with the SRP password files. That way SRP authentication could be used for all the system's users. The implementation in GnuTLS is based on paper [TLSSRP] (*note Bibliography::). The supported SRP key exchange methods are: `SRP:' Authentication using the SRP protocol. `SRP_DSS:' Client authentication using the SRP protocol. Server is authenticated using a certificate with DSA parameters. `SRP_RSA:' Client authentication using the SRP protocol. Server is authenticated using a certificate with RSA parameters. If clients supporting SRP know the username and password before the connection, should initialize the client credentials and call the function *note gnutls_srp_set_client_credentials::. Alternatively they could specify a callback function by using the function *note gnutls_srp_set_client_credentials_function::. This has the advantage that allows probing the server for SRP support. In that case the callback function will be called twice per handshake. The first time is before the ciphersuite is negotiated, and if the callback returns a negative error code, the callback will be called again if SRP has been negotiated. This uses a special TLS-SRP handshake idiom in order to avoid, in interactive applications, to ask the user for SRP password and username if the server does not negotiate an SRP ciphersuite. In server side the default behaviour of GnuTLS is to read the usernames and SRP verifiers from password files. These password files are the ones used by the _Stanford srp libraries_ and can be specified using the *note gnutls_srp_set_server_credentials_file::. If a different password file format is to be used, then the function *note gnutls_srp_set_server_credentials_function::, should be called, in order to set an appropriate callback. Some helper functions such as * *note gnutls_srp_verifier:: * *note gnutls_srp_base64_encode:: * *note gnutls_srp_base64_decode:: are included in GnuTLS, and can be used to generate and maintain SRP verifiers and password files. A program to manipulate the required parameters for SRP authentication is also included. *Note srptool::, for more information. ---------- Footnotes ---------- (1) SRP is described in [RFC2945] (*note Bibliography::) 4.4 Authentication using PSK ============================ Authentication using Pre-shared keys is a method to authenticate using usernames and binary keys. This protocol avoids making use of public key infrastructure and expensive calculations, thus it is suitable for constraint clients. The implementation in GnuTLS is based on paper [TLSPSK] (*note Bibliography::). The supported PSK key exchange methods are: `PSK:' Authentication using the PSK protocol. `DHE-PSK:' Authentication using the PSK protocol and Diffie Hellman key exchange. This method offers perfect forward secrecy. Clients supporting PSK should supply the username and key before the connection to the client credentials by calling the function *note gnutls_psk_set_client_credentials::. Alternatively they could specify a callback function by using the function *note gnutls_psk_set_client_credentials_function::. This has the advantage that the callback will be called only if PSK has been negotiated. In server side the default behaviour of GnuTLS is to read the usernames and PSK keys from a password file. The password file should contain usernames and keys in hexadecimal format. The name of the password file can be stored to the credentials structure by calling *note gnutls_psk_set_server_credentials_file::. If a different password file format is to be used, then the function *note gnutls_psk_set_server_credentials_function::, should be used instead. Some helper functions such as: * *note gnutls_hex_encode:: * *note gnutls_hex_decode:: are included in GnuTLS, and may be used to generate and maintain PSK keys. 4.5 Authentication and Credentials ================================== In GnuTLS every key exchange method is associated with a credentials type. So in order to enable to enable a specific method, the corresponding credentials type should be initialized and set using *note gnutls_credentials_set::. A mapping is shown below. Key exchange algorithms and the corresponding credential types: Key exchange Client credentials Server credentials --------------------------------------------------------------------- `KX_RSA' `KX_DHE_RSA' `KX_DHE_DSS' `KX_RSA_EXPORT' `CRD_CERTIFICATE' `CRD_CERTIFICATE' `KX_SRP_RSA' `CRD_SRP' `CRD_SRP' `KX_SRP_DSS' `CRD_CERTIFICATE' `KX_SRP' `CRD_SRP' `CRD_SRP' `KX_ANON_DH' `CRD_ANON' `CRD_ANON' `KX_PSK' `CRD_PSK' `CRD_PSK' 4.6 Parameters Stored in Credentials ==================================== Several parameters such as the ones used for Diffie-Hellman authentication are stored within the credentials structures, so all sessions can access them. Those parameters are stored in structures such as `gnutls_dh_params_t' and `gnutls_rsa_params_t', and functions like *note gnutls_certificate_set_dh_params:: and *note gnutls_certificate_set_rsa_export_params:: can be used to associate those parameters with the given credentials structure. Since those parameters need to be renewed from time to time and a global structure such as the credentials, may not be easy to modify since it is accessible by all sessions, an alternative interface is available using a callback function. This can be set using the *note gnutls_certificate_set_params_function::. An example is shown below. #include gnutls_rsa_params_t rsa_params; gnutls_dh_params_t dh_params; /* This function will be called once a session requests DH * or RSA parameters. The parameters returned (if any) will * be used for the first handshake only. */ static int get_params( gnutls_session_t session, gnutls_params_type_t type, gnutls_params_st *st) { if (type == GNUTLS_PARAMS_RSA_EXPORT) st->params.rsa_export = rsa_params; else if (type == GNUTLS_PARAMS_DH) st->params.dh = dh_params; else return -1; st->type = type; /* do not deinitialize those parameters. */ st->deinit = 0; return 0; } int main() { gnutls_certificate_credentials_t cert_cred; initialize_params(); /* ... */ gnutls_certificate_set_params_function( cert_cred, get_params); } 5 More on Certificate Authentication ************************************ 5.1 The X.509 Trust Model ========================= The X.509 protocols rely on a hierarchical trust model. In this trust model Certification Authorities (CAs) are used to certify entities. Usually more than one certification authorities exist, and certification authorities may certify other authorities to issue certificates as well, following a hierarchical model. One needs to trust one or more CAs for his secure communications. In that case only the certificates issued by the trusted authorities are acceptable. See the figure above for a typical example. The API for handling X.509 certificates is described at section *note sec:x509api::. Some examples are listed below. 5.1.1 X.509 Certificates ------------------------ An X.509 certificate usually contains information about the certificate holder, the signer, a unique serial number, expiration dates and some other fields [RFC3280] (*note Bibliography::) as shown in the table below. `version:' The field that indicates the version of the certificate. `serialNumber:' This field holds a unique serial number per certificate. `issuer:' Holds the issuer's distinguished name. `validity:' The activation and expiration dates. `subject:' The subject's distinguished name of the certificate. `extensions:' The extensions are fields only present in version 3 certificates. The certificate's _subject or issuer name_ is not just a single string. It is a Distinguished name and in the ASN.1 notation is a sequence of several object IDs with their corresponding values. Some of available OIDs to be used in an X.509 distinguished name are defined in `gnutls/x509.h'. The _Version_ field in a certificate has values either 1 or 3 for version 3 certificates. Version 1 certificates do not support the extensions field so it is not possible to distinguish a CA from a person, thus their usage should be avoided. The _validity_ dates are there to indicate the date that the specific certificate was activated and the date the certificate's key would be considered invalid. Certificate _extensions_ are there to include information about the certificate's subject that did not fit in the typical certificate fields. Those may be e-mail addresses, flags that indicate whether the belongs to a CA etc. All the supported X.509 version 3 extensions are shown in the table below. `subject key id (2.5.29.14):' An identifier of the key of the subject. `authority key id (2.5.29.35):' An identifier of the authority's key used to sign the certificate. `subject alternative name (2.5.29.17):' Alternative names to subject's distinguished name. `key usage (2.5.29.15):' Constraints the key's usage of the certificate. `extended key usage (2.5.29.37):' Constraints the purpose of the certificate. `basic constraints (2.5.29.19):' Indicates whether this is a CA certificate or not, and specify the maximum path lengths of certificate chains. `CRL distribution points (2.5.29.31):' This extension is set by the CA, in order to inform about the issued CRLs. `Proxy Certification Information (1.3.6.1.5.5.7.1.14):' Proxy Certificates includes this extension that contains the OID of the proxy policy language used, and can specify limits on the maximum lengths of proxy chains. Proxy Certificates are specified in [RFC3820] (*note Bibliography::). In GnuTLS the X.509 certificate structures are handled using the `gnutls_x509_crt_t' type and the corresponding private keys with the `gnutls_x509_privkey_t' type. All the available functions for X.509 certificate handling have their prototypes in `gnutls/x509.h'. An example program to demonstrate the X.509 parsing capabilities can be found at section *note ex:x509-info::. 5.1.2 Verifying X.509 Certificate Paths --------------------------------------- Verifying certificate paths is important in X.509 authentication. For this purpose the function *note gnutls_x509_crt_verify:: is provided. The output of this function is the bitwise OR of the elements of the `gnutls_certificate_status_t' enumeration. A detailed description of these elements can be found in figure below. The function *note gnutls_certificate_verify_peers2:: is equivalent to the previous one, and will verify the peer's certificate in a TLS session. `CERT_INVALID:' The certificate is not signed by one of the known authorities, or the signature is invalid. `CERT_REVOKED:' The certificate has been revoked by its CA. `CERT_SIGNER_NOT_FOUND:' The certificate's issuer is not known. This is the case when the issuer is not in the trusted certificates list. `GNUTLS_CERT_SIGNER_NOT_CA:' The certificate's signer was not a CA. This may happen if this was a version 1 certificate, which is common with some CAs, or a version 3 certificate without the basic constrains extension. `GNUTLS_CERT_INSECURE_ALGORITHM:' The certificate was signed using an insecure algorithm such as MD2 or MD5. These algorithms have been broken and should not be trusted. There is also to possibility to pass some input to the verification functions in the form of flags. For *note gnutls_x509_crt_verify:: the flags are passed straightforward, but *note gnutls_certificate_verify_peers2:: depends on the flags set by calling *note gnutls_certificate_set_verify_flags::. All the available flags are part of the enumeration *note gnutls_certificate_verify_flags:: and are explained in the table below. `GNUTLS_VERIFY_DISABLE_CA_SIGN:' If set a signer does not have to be a certificate authority. This flag should normaly be disabled, unless you know what this means. `GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT:' Allow only trusted CA certificates that have version 1. This is safer than GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT, and should be used instead. That way only signers in your trusted list will be allowed to have certificates of version 1. `GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT:' Allow CA certificates that have version 1 (both root and intermediate). This is dangerous since those haven't the basicConstraints extension. Must be used in combination with GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT. `GNUTLS_VERIFY_DO_NOT_ALLOW_SAME:' If a certificate is not signed by anyone trusted but exists in the trusted CA list do not treat it as trusted. `GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2:' Allow certificates to be signed using the old MD2 algorithm. `GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5:' Allow certificates to be signed using the broken MD5 algorithm. Although the verification of a certificate path indicates that the certificate is signed by trusted authority, does not reveal anything about the peer's identity. It is required to verify if the certificate's owner is the one you expect. For more information consult [RFC2818] (*note Bibliography::) and section *note ex:verify:: for an example. 5.1.3 PKCS #10 Certificate Requests ----------------------------------- A certificate request is a structure, which contain information about an applicant of a certificate service. It usually contains a private key, a distinguished name and secondary data such as a challenge password. GnuTLS supports the requests defined in PKCS #10 [RFC2986] (*note Bibliography::). Other certificate request's format such as PKIX's [RFC4211] (*note Bibliography::) are not currently supported. In GnuTLS the PKCS #10 structures are handled using the `gnutls_x509_crq_t' type. An example of a certificate request generation can be found at section *note ex:crq::. 5.1.4 PKCS #12 Structures ------------------------- A PKCS #12 structure [PKCS12] (*note Bibliography::) usually contains a user's private keys and certificates. It is commonly used in browsers to export and import the user's identities. In GnuTLS the PKCS #12 structures are handled using the `gnutls_pkcs12_t' type. This is an abstract type that may hold several `gnutls_pkcs12_bag_t' types. The Bag types are the holders of the actual data, which may be certificates, private keys or encrypted data. An Bag of type encrypted should be decrypted in order for its data to be accessed. An example of a PKCS #12 structure generation can be found at section *note ex:pkcs12::. 5.2 The OpenPGP Trust Model =========================== The OpenPGP key authentication relies on a distributed trust model, called the "web of trust". The "web of trust" uses a decentralized system of trusted introducers, which are the same as a CA. OpenPGP allows anyone to sign anyone's else public key. When Alice signs Bob's key, she is introducing Bob's key to anyone who trusts Alice. If someone trusts Alice to introduce keys, then Alice is a trusted introducer in the mind of that observer. For example: If David trusts Alice to be an introducer, and Alice signed Bob's key, Dave also trusts Bob's key to be the real one. There are some key points that are important in that model. In the example Alice has to sign Bob's key, only if she is sure that the key belongs to Bob. Otherwise she may also make Dave falsely believe that this is Bob's key. Dave has also the responsibility to know who to trust. This model is similar to real life relations. Just see how Charlie behaves in the previous example. Although he has signed Bob's key - because he knows, somehow, that it belongs to Bob - he does not trust Bob to be an introducer. Charlie decided to trust only Kevin, for some reason. A reason could be that Bob is lazy enough, and signs other people's keys without being sure that they belong to the actual owner. 5.2.1 OpenPGP Keys ------------------ In GnuTLS the OpenPGP key structures [RFC2440] (*note Bibliography::) are handled using the `gnutls_openpgp_crt_t' type and the corresponding private keys with the `gnutls_openpgp_privkey_t' type. All the prototypes for the key handling functions can be found at `gnutls/openpgp.h'. 5.2.2 Verifying an OpenPGP Key ------------------------------ The verification functions of OpenPGP keys, included in GnuTLS, are simple ones, and do not use the features of the "web of trust". For that reason, if the verification needs are complex, the assistance of external tools like GnuPG and GPGME (`http://www.gnupg.org/related_software/gpgme/') is recommended. There is one verification function in GnuTLS, the *note gnutls_openpgp_crt_verify_ring::. This checks an OpenPGP key against a given set of public keys (keyring) and returns the key status. The key verification status is the same as in X.509 certificates, although the meaning and interpretation are different. For example an OpenPGP key may be valid, if the self signature is ok, even if no signers were found. The meaning of verification status is shown in the figure below. `CERT_INVALID:' A signature on the key is invalid. That means that the key was modified by somebody, or corrupted during transport. `CERT_REVOKED:' The key has been revoked by its owner. `CERT_SIGNER_NOT_FOUND:' The key was not signed by a known signer. `GNUTLS_CERT_INSECURE_ALGORITHM:' The certificate was signed using an insecure algorithm such as MD2 or MD5. These algorithms have been broken and should not be trusted. 5.3 Digital Signatures ====================== In this section we will provide some information about digital signatures, how they work, and give the rationale for disabling some of the algorithms used. Digital signatures work by using somebody's secret key to sign some arbitrary data. Then anybody else could use the public key of that person to verify the signature. Since the data may be arbitrary it is not suitable input to a cryptographic digital signature algorithm. For this reason and also for performance cryptographic hash algorithms are used to preprocess the input to the signature algorithm. This works as long as it is difficult enough to generate two different messages with the same hash algorithm output. In that case the same signature could be used as a proof for both messages. Nobody wants to sign an innocent message of donating 1 Euro to Greenpeace and find out that he donated 1.000.000 Euro to Bad Inc. For a hash algorithm to be called cryptographic the following three requirements must hold 1. Preimage resistance. That means the algorithm must be one way and given the output of the hash function H(x), it is impossible to calculate x. 2. 2nd preimage resistance. That means that given a pair x,y with y=H(x) it is impossible to calculate an x' such that y=H(x'). 3. Collision resistance. That means that it is impossible to calculate random x and x' such H(x')=H(x). The last two requirements in the list are the most important in digital signatures. These protect against somebody who would like to generate two messages with the same hash output. When an algorithm is considered broken usually it means that the Collision resistance of the algorithm is less than brute force. Using the birthday paradox the brute force attack takes 2^((hash size) / 2) operations. Today colliding certificates using the MD5 hash algorithm have been generated as shown in [WEGER] (*note Bibliography::). There has been cryptographic results for the SHA-1 hash algorithms as well, although they are not yet critical. Before 2004, MD5 had a presumed collision strength of 2^64, but it has been showed to have a collision strength well under 2^50. As of November 2005, it is believed that SHA-1's collision strength is around 2^63. We consider this sufficiently hard so that we still support SHA-1. We anticipate that SHA-256/386/512 will be used in publicly-distributed certificates in the future. When 2^63 can be considered too weak compared to the computer power available sometime in the future, SHA-1 will be disabled as well. The collision attacks on SHA-1 may also get better, given the new interest in tools for creating them. 5.3.1 Supported Algorithms -------------------------- The available digital signature algorithms in GnuTLS are listed below: `RSA' RSA is public key cryptosystem designed by Ronald Rivest, Adi Shamir and Leonard Adleman. It can be used with any hash functions. `DSA' DSA is the USA's Digital Signature Standard. It uses only the SHA-1 hash algorithm. The supported cryptographic hash algorithms are: `MD2' MD2 is a cryptographic hash algorithm designed by Ron Rivest. It is optimized for 8-bit processors. Outputs 128 bits of data. There are no known weaknesses of this algorithm but since this algorithm is rarely used and not really studied it should not be used today. `MD5' MD5 is a cryptographic hash algorithm designed by Ron Rivest. Outputs 128 bits of data. It is considered to be broken. `SHA-1' SHA is a cryptographic hash algorithm designed by NSA. Outputs 160 bits of data. It is also considered to be broken, though no practical attacks have been found. `RMD160' RIPEMD is a cryptographic hash algorithm developed in the framework of the EU project RIPE. Outputs 160 bits of data. 5.3.2 Trading Security for Interoperability ------------------------------------------- If you connect to a server and use GnuTLS' functions to verify the certificate chain, and get a *note GNUTLS_CERT_INSECURE_ALGORITHM:: validation error (*note Verifying X.509 certificate paths::), it means that somewhere in the certificate chain there is a certificate signed using `RSA-MD2' or `RSA-MD5'. These two digital signature algorithms are considered broken, so GnuTLS fail when attempting to verify the certificate. In some situations, it may be useful to be able to verify the certificate chain anyway, assuming an attacker did not utilize the fact that these signatures algorithms are broken. This section will give help on how to achieve that. First, it is important to know that you do not have to enable any of the flags discussed here to be able to use trusted root CA certificates signed using `RSA-MD2' or `RSA-MD5'. The only attack today is that it is possible to generate certificates with colliding signatures (collision resistance); you cannot generate a certificate that has the same signature as an already existing signature (2nd preimage resistance). If you are using *note gnutls_certificate_verify_peers2:: to verify the certificate chain, you can call *note gnutls_certificate_set_verify_flags:: with the `GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2' or `GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5' flag, as in: gnutls_certificate_set_verify_flags (x509cred, GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5); This will tell the verifier algorithm to enable `RSA-MD5' when verifying the certificates. If you are using *note gnutls_x509_crt_verify:: or *note gnutls_x509_crt_list_verify::, you can pass the `GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5' parameter directly in the `flags' parameter. If you are using these flags, it may also be a good idea to warn the user when verification failure occur for this reason. The simplest is to not use the flags by default, and only fall back to using them after warning the user. If you wish to inspect the certificate chain yourself, you can use *note gnutls_certificate_get_peers:: to extract the raw server's certificate chain, then use *note gnutls_x509_crt_import:: to parse each of the certificates, and then use *note gnutls_x509_crt_get_signature_algorithm:: to find out the signing algorithm used for each certificate. If any of the intermediary certificates are using `GNUTLS_SIGN_RSA_MD2' or `GNUTLS_SIGN_RSA_MD5', you could present a warning. 6 How To Use TLS in Application Protocols ***************************************** This chapter is intended to provide some hints on how to use the TLS over simple custom made application protocols. The discussion below mainly refers to the _TCP/IP_ transport layer but may be extended to other ones too. 6.1 Separate Ports ================== Traditionally SSL was used in application protocols by assigning a new port number for the secure services. That way two separate ports were assigned, one for the non secure sessions, and one for the secured ones. This has the benefit that if a user requests a secure session then the client will try to connect to the secure port and fail otherwise. The only possible attack with this method is a denial of service one. The most famous example of this method is the famous "HTTP over TLS" or HTTPS protocol [RFC2818] (*note Bibliography::). Despite its wide use, this method is not as good as it seems. This approach starts the TLS Handshake procedure just after the client connects on the --so called-- secure port. That way the TLS protocol does not know anything about the client, and popular methods like the host advertising in HTTP do not work(1). There is no way for the client to say "I connected to YYY server" before the Handshake starts, so the server cannot possibly know which certificate to use. Other than that it requires two separate ports to run a single service, which is unnecessary complication. Due to the fact that there is a limitation on the available privileged ports, this approach was soon obsoleted. ---------- Footnotes ---------- (1) See also the Server Name Indication extension on *note serverind::. 6.2 Upward Negotiation ====================== Other application protocols(1) use a different approach to enable the secure layer. They use something called the "TLS upgrade" method. This method is quite tricky but it is more flexible. The idea is to extend the application protocol to have a "STARTTLS" request, whose purpose it to start the TLS protocols just after the client requests it. This is a really neat idea and does not require an extra port. This method is used by almost all modern protocols and there is even the [RFC2817] (*note Bibliography::) paper which proposes extensions to HTTP to support it. The tricky part, in this method, is that the "STARTTLS" request is sent in the clear, thus is vulnerable to modifications. A typical attack is to modify the messages in a way that the client is fooled and thinks that the server does not have the "STARTTLS" capability. See a typical conversation of a hypothetical protocol: (client connects to the server) CLIENT: HELLO I'M MR. XXX SERVER: NICE TO MEET YOU XXX CLIENT: PLEASE START TLS SERVER: OK *** TLS STARTS CLIENT: HERE ARE SOME CONFIDENTIAL DATA And see an example of a conversation where someone is acting in between: (client connects to the server) CLIENT: HELLO I'M MR. XXX SERVER: NICE TO MEET YOU XXX CLIENT: PLEASE START TLS (here someone inserts this message) SERVER: SORRY I DON'T HAVE THIS CAPABILITY CLIENT: HERE ARE SOME CONFIDENTIAL DATA As you can see above the client was fooled, and was dummy enough to send the confidential data in the clear. How to avoid the above attack? As you may have already thought this one is easy to avoid. The client has to ask the user before it connects whether the user requests TLS or not. If the user answered that he certainly wants the secure layer the last conversation should be: (client connects to the server) CLIENT: HELLO I'M MR. XXX SERVER: NICE TO MEET YOU XXX CLIENT: PLEASE START TLS (here someone inserts this message) SERVER: SORRY I DON'T HAVE THIS CAPABILITY CLIENT: BYE (the client notifies the user that the secure connection was not possible) This method, if implemented properly, is far better than the traditional method, and the security properties remain the same, since only denial of service is possible. The benefit is that the server may request additional data before the TLS Handshake protocol starts, in order to send the correct certificate, use the correct password file(2), or anything else! ---------- Footnotes ---------- (1) See LDAP, IMAP etc. (2) in SRP authentication 7 How To Use GnuTLS in Applications *********************************** 7.1 Preparation =============== To use GnuTLS, you have to perform some changes to your sources and your build system. The necessary changes are explained in the following subsections. 7.1.1 Headers ------------- All the data types and functions of the GnuTLS library are defined in the header file `gnutls/gnutls.h'. This must be included in all programs that make use of the GnuTLS library. The extra functionality of the GnuTLS-extra library is available by including the header file `gnutls/extra.h' in your programs. 7.1.2 Version Check ------------------- It is often desirable to check that the version of `gnutls' used is indeed one which fits all requirements. Even with binary compatibility new features may have been introduced but due to problem with the dynamic linker an old version is actually used. So you may want to check that the version is okay right after program startup. See the function *note gnutls_check_version::. 7.1.3 Debugging --------------- In many cases things may not go as expected and further information, to assist debugging, from GnuTLS is desired. Those are the case where the *note gnutls_global_set_log_level:: and *note gnutls_global_set_log_function:: are to be used. Those will print verbose information on the GnuTLS functions internal flow. 7.1.4 Building the Source ------------------------- If you want to compile a source file including the `gnutls/gnutls.h' header file, you must make sure that the compiler can find it in the directory hierarchy. This is accomplished by adding the path to the directory in which the header file is located to the compilers include file search path (via the -I option). However, the path to the include file is determined at the time the source is configured. To solve this problem, GnuTLS ships with two small helper programs `libgnutls-config' and `libgnutls-extra-config' that knows about the path to the include file and other configuration options. The options that need to be added to the compiler invocation at compile time are output by the `--cflags' option to `libgnutls-config'. The following example shows how it can be used at the command line: gcc -c foo.c `libgnutls-config --cflags` Adding the output of `libgnutls-config --cflags' to the compilers command line will ensure that the compiler can find the GnuTLS header file. A similar problem occurs when linking the program with the library. Again, the compiler has to find the library files. For this to work, the path to the library files has to be added to the library search path (via the -L option). For this, the option `--libs' to `libgnutls-config' can be used. For convenience, this option also outputs all other options that are required to link the program with the GnuTLS libararies. The example shows how to link `foo.o' with the GnuTLS libraries to a program _foo_. gcc -o foo foo.o `libgnutls-config --libs` Of course you can also combine both examples to a single command by specifying both options to `libgnutls-config': gcc -o foo foo.c `libgnutls-config --cflags --libs` 7.2 Multi-Threaded Applications =============================== Although the GnuTLS library is thread safe by design, some parts of the crypto backend, such as the random generator, are not. Since _libgcrypt 1.1.92_ there was an automatic detection of the thread library used by the application, so most applications wouldn't need to do any changes to ensure thread-safety. Due to the unportability of the automatic thread detection, this was removed from later releases of _libgcrypt_, so applications have now to register callback functions to ensure proper locking in sensitive parts of _libgcrypt_. There are helper macros to help you properly initialize the libraries. Examples are shown below. * POSIX threads #include #include #include #include GCRY_THREAD_OPTION_PTHREAD_IMPL; int main() { /* The order matters. */ gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); gnutls_global_init(); } * GNU PTH threads #include #include #include #include GCRY_THREAD_OPTION_PTH_IMPL; int main() { gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth); gnutls_global_init(); } * Other thread packages /* The gcry_thread_cbs structure must have been * initialized. */ static struct gcry_thread_cbs gcry_threads_other = { ... }; int main() { gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_other); } 7.3 Client Examples =================== This section contains examples of TLS and SSL clients, using GnuTLS. Note that these examples contain little or no error checking. Some of the examples require functions implemented by another example. 7.3.1 Simple Client Example with Anonymous Authentication --------------------------------------------------------- The simplest client using TLS is the one that doesn't do any authentication. This means no external certificates or passwords are needed to set up the connection. As could be expected, the connection is vulnerable to man-in-the-middle (active or redirection) attacks. However, the data is integrity and privacy protected. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include /* A very basic TLS client, with anonymous authentication. */ #define MAX_BUF 1024 #define SA struct sockaddr #define MSG "GET / HTTP/1.0\r\n\r\n" extern int tcp_connect (void); extern void tcp_close (int sd); int main (void) { int ret, sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; gnutls_anon_client_credentials_t anoncred; /* Need to enable anonymous KX specifically. */ gnutls_global_init (); gnutls_anon_allocate_client_credentials (&anoncred); /* Initialize TLS session */ gnutls_init (&session, GNUTLS_CLIENT); /* Use default priorities */ gnutls_priority_set_direct (session, "PERFORMANCE:+ANON-DH:!ARCFOUR-128", NULL); /* put the anonymous credentials to the current session */ gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred); /* connect to the peer */ sd = tcp_connect (); gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); /* Perform the TLS handshake */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "*** Handshake failed\n"); gnutls_perror (ret); goto end; } else { printf ("- Handshake was completed\n"); } gnutls_record_send (session, MSG, strlen (MSG)); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (ret == 0) { printf ("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0) { fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret)); goto end; } printf ("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fputs ("\n", stdout); gnutls_bye (session, GNUTLS_SHUT_RDWR); end: tcp_close (sd); gnutls_deinit (session); gnutls_anon_free_client_credentials (anoncred); gnutls_global_deinit (); return 0; } 7.3.2 Simple Client Example with X.509 Certificate Support ---------------------------------------------------------- Let's assume now that we want to create a TCP client which communicates with servers that use X.509 or OpenPGP certificate authentication. The following client is a very simple TLS client, it does not support session resuming, not even certificate verification. The TCP functions defined in this example are used in most of the other examples below, without redefining them. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include /* A very basic TLS client, with X.509 authentication. */ #define MAX_BUF 1024 #define CAFILE "ca.pem" #define MSG "GET / HTTP/1.0\r\n\r\n" extern int tcp_connect (void); extern void tcp_close (int sd); int main (void) { int ret, sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; const char *err; gnutls_certificate_credentials_t xcred; gnutls_global_init (); /* X509 stuff */ gnutls_certificate_allocate_credentials (&xcred); /* sets the trusted cas file */ gnutls_certificate_set_x509_trust_file (xcred, CAFILE, GNUTLS_X509_FMT_PEM); /* Initialize TLS session */ gnutls_init (&session, GNUTLS_CLIENT); /* Use default priorities */ ret = gnutls_priority_set_direct (session, "PERFORMANCE", &err); if (ret < 0) { if (ret == GNUTLS_E_INVALID_REQUEST) { fprintf(stderr, "Syntax error at: %s\n", err); } exit(1); } /* put the x509 credentials to the current session */ gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred); /* connect to the peer */ sd = tcp_connect (); gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); /* Perform the TLS handshake */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "*** Handshake failed\n"); gnutls_perror (ret); goto end; } else { printf ("- Handshake was completed\n"); } gnutls_record_send (session, MSG, strlen (MSG)); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (ret == 0) { printf ("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0) { fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret)); goto end; } printf ("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fputs ("\n", stdout); gnutls_bye (session, GNUTLS_SHUT_RDWR); end: tcp_close (sd); gnutls_deinit (session); gnutls_certificate_free_credentials (xcred); gnutls_global_deinit (); return 0; } 7.3.3 Obtaining Session Information ----------------------------------- Most of the times it is desirable to know the security properties of the current established session. This includes the underlying ciphers and the protocols involved. That is the purpose of the following function. Note that this function will print meaningful values only if called after a successful *note gnutls_handshake::. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include extern void print_x509_certificate_info (gnutls_session_t); /* This function will print some details of the * given session. */ int print_info (gnutls_session_t session) { const char *tmp; gnutls_credentials_type_t cred; gnutls_kx_algorithm_t kx; /* print the key exchange's algorithm name */ kx = gnutls_kx_get (session); tmp = gnutls_kx_get_name (kx); printf ("- Key Exchange: %s\n", tmp); /* Check the authentication type used and switch * to the appropriate. */ cred = gnutls_auth_get_type (session); switch (cred) { case GNUTLS_CRD_IA: printf ("- TLS/IA session\n"); break; case GNUTLS_CRD_SRP: printf ("- SRP session with username %s\n", gnutls_srp_server_get_username (session)); break; case GNUTLS_CRD_PSK: if (gnutls_psk_server_get_username (session) != NULL) printf ("- PSK authentication. Connected as '%s'\n", gnutls_psk_server_get_username (session)); break; case GNUTLS_CRD_ANON: /* anonymous authentication */ printf ("- Anonymous DH using prime of %d bits\n", gnutls_dh_get_prime_bits (session)); break; case GNUTLS_CRD_CERTIFICATE: /* certificate authentication */ /* Check if we have been using ephemeral Diffie Hellman. */ if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS) { printf ("\n- Ephemeral DH using prime of %d bits\n", gnutls_dh_get_prime_bits (session)); } /* if the certificate list is available, then * print some information about it. */ print_x509_certificate_info (session); } /* switch */ /* print the protocol's name (ie TLS 1.0) */ tmp = gnutls_protocol_get_name (gnutls_protocol_get_version (session)); printf ("- Protocol: %s\n", tmp); /* print the certificate type of the peer. * ie X.509 */ tmp = gnutls_certificate_type_get_name (gnutls_certificate_type_get (session)); printf ("- Certificate Type: %s\n", tmp); /* print the compression algorithm (if any) */ tmp = gnutls_compression_get_name (gnutls_compression_get (session)); printf ("- Compression: %s\n", tmp); /* print the name of the cipher used. * ie 3DES. */ tmp = gnutls_cipher_get_name (gnutls_cipher_get (session)); printf ("- Cipher: %s\n", tmp); /* Print the MAC algorithms name. * ie SHA1 */ tmp = gnutls_mac_get_name (gnutls_mac_get (session)); printf ("- MAC: %s\n", tmp); return 0; } 7.3.4 Verifying Peer's Certificate ---------------------------------- A TLS session is not secure just after the handshake procedure has finished. It must be considered secure, only after the peer's certificate and identity have been verified. That is, you have to verify the signature in peer's certificate, the hostname in the certificate, and expiration dates. Just after this step you should treat the connection as being a secure one. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include /* This function will try to verify the peer's certificate, and * also check if the hostname matches, and the activation, expiration dates. */ void verify_certificate (gnutls_session_t session, const char *hostname) { unsigned int status; const gnutls_datum_t *cert_list; unsigned int cert_list_size; int ret; gnutls_x509_crt_t cert; /* This verification function uses the trusted CAs in the credentials * structure. So you must have installed one or more CA certificates. */ ret = gnutls_certificate_verify_peers2 (session, &status); if (ret < 0) { printf ("Error\n"); return; } if (status & GNUTLS_CERT_INVALID) printf ("The certificate is not trusted.\n"); if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) printf ("The certificate hasn't got a known issuer.\n"); if (status & GNUTLS_CERT_REVOKED) printf ("The certificate has been revoked.\n"); /* Up to here the process is the same for X.509 certificates and * OpenPGP keys. From now on X.509 certificates are assumed. This can * be easily extended to work with openpgp keys as well. */ if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509) return; if (gnutls_x509_crt_init (&cert) < 0) { printf ("error in initialization\n"); return; } cert_list = gnutls_certificate_get_peers (session, &cert_list_size); if (cert_list == NULL) { printf ("No certificate was found!\n"); return; } /* This is not a real world example, since we only check the first * certificate in the given chain. */ if (gnutls_x509_crt_import (cert, &cert_list[0], GNUTLS_X509_FMT_DER) < 0) { printf ("error parsing certificate\n"); return; } /* Beware here we do not check for errors. */ if (gnutls_x509_crt_get_expiration_time (cert) < time (0)) { printf ("The certificate has expired\n"); return; } if (gnutls_x509_crt_get_activation_time (cert) > time (0)) { printf ("The certificate is not yet activated\n"); return; } if (!gnutls_x509_crt_check_hostname (cert, hostname)) { printf ("The certificate's owner does not match hostname '%s'\n", hostname); return; } gnutls_x509_crt_deinit (cert); return; } An other example is listed below which provides a more detailed verification output. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include /* All the available CRLs */ gnutls_x509_crl_t *crl_list; int crl_list_size; /* All the available trusted CAs */ gnutls_x509_crt_t *ca_list; int ca_list_size; static void verify_cert2 (gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_x509_crl_t * crl_list, int crl_list_size); static void verify_last_cert (gnutls_x509_crt_t crt, gnutls_x509_crt_t * ca_list, int ca_list_size, gnutls_x509_crl_t * crl_list, int crl_list_size); /* This function will try to verify the peer's certificate chain, and * also check if the hostname matches, and the activation, expiration dates. */ void verify_certificate_chain (gnutls_session_t session, const char *hostname, const gnutls_datum_t * cert_chain, int cert_chain_length) { int i; gnutls_x509_crt_t *cert; cert = malloc (sizeof (*cert) * cert_chain_length); /* Import all the certificates in the chain to * native certificate format. */ for (i = 0; i < cert_chain_length; i++) { gnutls_x509_crt_init (&cert[i]); gnutls_x509_crt_import (cert[i], &cert_chain[i], GNUTLS_X509_FMT_DER); } /* If the last certificate in the chain is self signed ignore it. * That is because we want to check against our trusted certificate * list. */ if (gnutls_x509_crt_check_issuer (cert[cert_chain_length - 1], cert[cert_chain_length - 1]) > 0 && cert_chain_length > 0) { cert_chain_length--; } /* Now verify the certificates against their issuers * in the chain. */ for (i = 1; i < cert_chain_length; i++) { verify_cert2 (cert[i - 1], cert[i], crl_list, crl_list_size); } /* Here we must verify the last certificate in the chain against * our trusted CA list. */ verify_last_cert (cert[cert_chain_length - 1], ca_list, ca_list_size, crl_list, crl_list_size); /* Check if the name in the first certificate matches our destination! */ if (!gnutls_x509_crt_check_hostname (cert[0], hostname)) { printf ("The certificate's owner does not match hostname '%s'\n", hostname); } for (i = 0; i < cert_chain_length; i++) gnutls_x509_crt_deinit (cert[i]); return; } /* Verifies a certificate against an other certificate * which is supposed to be it's issuer. Also checks the * crl_list if the certificate is revoked. */ static void verify_cert2 (gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_x509_crl_t * crl_list, int crl_list_size) { unsigned int output; int ret; time_t now = time (0); size_t name_size; char name[64]; /* Print information about the certificates to * be checked. */ name_size = sizeof (name); gnutls_x509_crt_get_dn (crt, name, &name_size); fprintf (stderr, "\nCertificate: %s\n", name); name_size = sizeof (name); gnutls_x509_crt_get_issuer_dn (crt, name, &name_size); fprintf (stderr, "Issued by: %s\n", name); /* Get the DN of the issuer cert. */ name_size = sizeof (name); gnutls_x509_crt_get_dn (issuer, name, &name_size); fprintf (stderr, "Checking against: %s\n", name); /* Do the actual verification. */ gnutls_x509_crt_verify (crt, &issuer, 1, 0, &output); if (output & GNUTLS_CERT_INVALID) { fprintf (stderr, "Not trusted"); if (output & GNUTLS_CERT_SIGNER_NOT_FOUND) fprintf (stderr, ": no issuer was found"); if (output & GNUTLS_CERT_SIGNER_NOT_CA) fprintf (stderr, ": issuer is not a CA"); fprintf (stderr, "\n"); } else fprintf (stderr, "Trusted\n"); /* Now check the expiration dates. */ if (gnutls_x509_crt_get_activation_time (crt) > now) fprintf (stderr, "Not yet activated\n"); if (gnutls_x509_crt_get_expiration_time (crt) < now) fprintf (stderr, "Expired\n"); /* Check if the certificate is revoked. */ ret = gnutls_x509_crt_check_revocation (crt, crl_list, crl_list_size); if (ret == 1) { /* revoked */ fprintf (stderr, "Revoked\n"); } } /* Verifies a certificate against our trusted CA list. * Also checks the crl_list if the certificate is revoked. */ static void verify_last_cert (gnutls_x509_crt_t crt, gnutls_x509_crt_t * ca_list, int ca_list_size, gnutls_x509_crl_t * crl_list, int crl_list_size) { unsigned int output; int ret; time_t now = time (0); size_t name_size; char name[64]; /* Print information about the certificates to * be checked. */ name_size = sizeof (name); gnutls_x509_crt_get_dn (crt, name, &name_size); fprintf (stderr, "\nCertificate: %s\n", name); name_size = sizeof (name); gnutls_x509_crt_get_issuer_dn (crt, name, &name_size); fprintf (stderr, "Issued by: %s\n", name); /* Do the actual verification. */ gnutls_x509_crt_verify (crt, ca_list, ca_list_size, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT, &output); if (output & GNUTLS_CERT_INVALID) { fprintf (stderr, "Not trusted"); if (output & GNUTLS_CERT_SIGNER_NOT_CA) fprintf (stderr, ": Issuer is not a CA\n"); else fprintf (stderr, "\n"); } else fprintf (stderr, "Trusted\n"); /* Now check the expiration dates. */ if (gnutls_x509_crt_get_activation_time (crt) > now) fprintf (stderr, "Not yet activated\n"); if (gnutls_x509_crt_get_expiration_time (crt) < now) fprintf (stderr, "Expired\n"); /* Check if the certificate is revoked. */ ret = gnutls_x509_crt_check_revocation (crt, crl_list, crl_list_size); if (ret == 1) { /* revoked */ fprintf (stderr, "Revoked\n"); } } 7.3.5 Using a Callback to Select the Certificate to Use ------------------------------------------------------- There are cases where a client holds several certificate and key pairs, and may not want to load all of them in the credentials structure. The following example demonstrates the use of the certificate selection callback. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include #include #include #include #include /* A TLS client that loads the certificate and key. */ #define MAX_BUF 1024 #define MSG "GET / HTTP/1.0\r\n\r\n" #define CERT_FILE "cert.pem" #define KEY_FILE "key.pem" #define CAFILE "ca.pem" extern int tcp_connect (void); extern void tcp_close (int sd); static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st); gnutls_x509_crt_t crt; gnutls_x509_privkey_t key; /* Helper functions to load a certificate and key * files into memory. */ static gnutls_datum_t load_file (const char *file) { FILE *f; gnutls_datum_t loaded_file = { NULL, 0 }; long filelen; void *ptr; if (!(f = fopen(file, "r")) || fseek(f, 0, SEEK_END) != 0 || (filelen = ftell(f)) < 0 || fseek(f, 0, SEEK_SET) != 0 || !(ptr = malloc((size_t)filelen)) || fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) { return loaded_file; } loaded_file.data = ptr; loaded_file.size = (unsigned int)filelen; return loaded_file; } static void unload_file(gnutls_datum_t data) { free(data.data); } /* Load the certificate and the private key. */ static void load_keys (void) { int ret; gnutls_datum_t data; data = load_file (CERT_FILE); if (data.data == NULL) { fprintf (stderr, "*** Error loading cert file.\n"); exit (1); } gnutls_x509_crt_init (&crt); ret = gnutls_x509_crt_import (crt, &data, GNUTLS_X509_FMT_PEM); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit (1); } unload_file (data); data = load_file (KEY_FILE); if (data.data == NULL) { fprintf (stderr, "*** Error loading key file.\n"); exit (1); } gnutls_x509_privkey_init (&key); ret = gnutls_x509_privkey_import (key, &data, GNUTLS_X509_FMT_PEM); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit (1); } unload_file (data); } int main (void) { int ret, sd, ii; gnutls_session_t session; gnutls_priority_t priorities_cache; char buffer[MAX_BUF + 1]; gnutls_certificate_credentials_t xcred; /* Allow connections to servers that have OpenPGP keys as well. */ gnutls_global_init (); load_keys (); /* X509 stuff */ gnutls_certificate_allocate_credentials (&xcred); /* priorities */ gnutls_priority_init( &priorities_cache, "NORMAL", NULL); /* sets the trusted cas file */ gnutls_certificate_set_x509_trust_file (xcred, CAFILE, GNUTLS_X509_FMT_PEM); gnutls_certificate_client_set_retrieve_function (xcred, cert_callback); /* Initialize TLS session */ gnutls_init (&session, GNUTLS_CLIENT); /* Use default priorities */ gnutls_priority_set (session, priorities_cache); /* put the x509 credentials to the current session */ gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred); /* connect to the peer */ sd = tcp_connect (); gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); /* Perform the TLS handshake */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "*** Handshake failed\n"); gnutls_perror (ret); goto end; } else { printf ("- Handshake was completed\n"); } gnutls_record_send (session, MSG, strlen (MSG)); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (ret == 0) { printf ("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0) { fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret)); goto end; } printf ("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fputs ("\n", stdout); gnutls_bye (session, GNUTLS_SHUT_RDWR); end: tcp_close (sd); gnutls_deinit (session); gnutls_certificate_free_credentials (xcred); gnutls_priority_deinit( priorities_cache); gnutls_global_deinit (); return 0; } /* This callback should be associated with a session by calling * gnutls_certificate_client_set_retrieve_function( session, cert_callback), * before a handshake. */ static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) { char issuer_dn[256]; int i, ret; size_t len; gnutls_certificate_type_t type; /* Print the server's trusted CAs */ if (nreqs > 0) printf ("- Server's trusted authorities:\n"); else printf ("- Server did not send us any trusted authorities names.\n"); /* print the names (if any) */ for (i = 0; i < nreqs; i++) { len = sizeof (issuer_dn); ret = gnutls_x509_rdn_get (&req_ca_rdn[i], issuer_dn, &len); if (ret >= 0) { printf (" [%d]: ", i); printf ("%s\n", issuer_dn); } } /* Select a certificate and return it. * The certificate must be of any of the "sign algorithms" * supported by the server. */ type = gnutls_certificate_type_get (session); if (type == GNUTLS_CRT_X509) { st->type = type; st->ncerts = 1; st->cert.x509 = &crt; st->key.x509 = key; st->deinit_all = 0; } else { return -1; } return 0; } 7.3.6 Client with Resume Capability Example ------------------------------------------- This is a modification of the simple client example. Here we demonstrate the use of session resumption. The client tries to connect once using TLS, close the connection and then try to establish a new connection using the previously negotiated data. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include /* Those functions are defined in other examples. */ extern void check_alert (gnutls_session_t session, int ret); extern int tcp_connect (void); extern void tcp_close (int sd); #define MAX_BUF 1024 #define CRLFILE "crl.pem" #define CAFILE "ca.pem" #define MSG "GET / HTTP/1.0\r\n\r\n" int main (void) { int ret; int sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; gnutls_certificate_credentials_t xcred; /* variables used in session resuming */ int t; char *session_data; size_t session_data_size; gnutls_global_init (); /* X509 stuff */ gnutls_certificate_allocate_credentials (&xcred); gnutls_certificate_set_x509_trust_file (xcred, CAFILE, GNUTLS_X509_FMT_PEM); for (t = 0; t < 2; t++) { /* connect 2 times to the server */ sd = tcp_connect (); gnutls_init (&session, GNUTLS_CLIENT); gnutls_priority_set_direct (session, "PERFORMANCE:!ARCFOUR-128", NULL); gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred); if (t > 0) { /* if this is not the first time we connect */ gnutls_session_set_data (session, session_data, session_data_size); free (session_data); } gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); /* Perform the TLS handshake */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "*** Handshake failed\n"); gnutls_perror (ret); goto end; } else { printf ("- Handshake was completed\n"); } if (t == 0) { /* the first time we connect */ /* get the session data size */ gnutls_session_get_data (session, NULL, &session_data_size); session_data = malloc (session_data_size); /* put session data to the session variable */ gnutls_session_get_data (session, session_data, &session_data_size); } else { /* the second time we connect */ /* check if we actually resumed the previous session */ if (gnutls_session_is_resumed (session) != 0) { printf ("- Previous session was resumed\n"); } else { fprintf (stderr, "*** Previous session was NOT resumed\n"); } } /* This function was defined in a previous example */ /* print_info(session); */ gnutls_record_send (session, MSG, strlen (MSG)); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (ret == 0) { printf ("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0) { fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret)); goto end; } printf ("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fputs ("\n", stdout); gnutls_bye (session, GNUTLS_SHUT_RDWR); end: tcp_close (sd); gnutls_deinit (session); } /* for() */ gnutls_certificate_free_credentials (xcred); gnutls_global_deinit (); return 0; } 7.3.7 Simple Client Example with SRP Authentication --------------------------------------------------- The following client is a very simple SRP TLS client which connects to a server and authenticates using a _username_ and a _password_. The server may authenticate itself using a certificate, and in that case it has to be verified. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include /* Those functions are defined in other examples. */ extern void check_alert (gnutls_session_t session, int ret); extern int tcp_connect (void); extern void tcp_close (int sd); #define MAX_BUF 1024 #define USERNAME "user" #define PASSWORD "pass" #define CAFILE "ca.pem" #define SA struct sockaddr #define MSG "GET / HTTP/1.0\r\n\r\n" #define MAX_PRIORITIES 3 int main (void) { int ret; int sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; gnutls_srp_client_credentials_t srp_cred; gnutls_certificate_credentials_t cert_cred; gnutls_global_init (); /* now enable the gnutls-extra library which contains the * SRP stuff. */ gnutls_global_init_extra (); gnutls_srp_allocate_client_credentials (&srp_cred); gnutls_certificate_allocate_credentials (&cert_cred); gnutls_certificate_set_x509_trust_file (cert_cred, CAFILE, GNUTLS_X509_FMT_PEM); gnutls_srp_set_client_credentials (srp_cred, USERNAME, PASSWORD); /* connects to server */ sd = tcp_connect (); /* Initialize TLS session */ gnutls_init (&session, GNUTLS_CLIENT); /* Set the priorities. */ gnutls_priority_set_direct (session, "NORMAL:+SRP:+SRP-RSA:+SRP-DSS", NULL); /* put the SRP credentials to the current session */ gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred); gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, cert_cred); gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); /* Perform the TLS handshake */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "*** Handshake failed\n"); gnutls_perror (ret); goto end; } else { printf ("- Handshake was completed\n"); } gnutls_record_send (session, MSG, strlen (MSG)); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (gnutls_error_is_fatal (ret) == 1 || ret == 0) { if (ret == 0) { printf ("- Peer has closed the GNUTLS connection\n"); goto end; } else { fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret)); goto end; } } else check_alert (session, ret); if (ret > 0) { printf ("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fputs ("\n", stdout); } gnutls_bye (session, GNUTLS_SHUT_RDWR); end: tcp_close (sd); gnutls_deinit (session); gnutls_srp_free_client_credentials (srp_cred); gnutls_certificate_free_credentials (cert_cred); gnutls_global_deinit (); return 0; } 7.3.8 Simple Client Example with TLS/IA Support ----------------------------------------------- The following client is a simple client which uses the TLS/IA extension to authenticate with the server. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include #include /* A basic TLS client, with anonymous authentication and TLS/IA handshake. */ #define MAX_BUF 1024 #define SA struct sockaddr #define MSG "GET / HTTP/1.0\r\n\r\n" extern int tcp_connect (void); extern void tcp_close (int sd); int client_avp (gnutls_session_t session, void *ptr, const char *last, size_t lastlen, char **new, size_t *newlen) { if (last) printf ("- received %d bytes AVP: `%.*s'\n", lastlen, lastlen, last); else printf ("- new application phase\n"); *new = gnutls_strdup ("client avp"); if (!*new) return -1; *newlen = strlen (*new); printf ("- sending %d bytes AVP: `%s'\n", *newlen, *new); gnutls_ia_permute_inner_secret (session, 3, "foo"); return 0; } int main (void) { int ret, sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; gnutls_anon_client_credentials_t anoncred; gnutls_ia_client_credentials_t iacred; /* Need to enable anonymous KX specifically. */ gnutls_global_init (); gnutls_anon_allocate_client_credentials (&anoncred); gnutls_ia_allocate_client_credentials (&iacred); /* Set TLS/IA stuff */ gnutls_ia_set_client_avp_function (iacred, client_avp); /* Initialize TLS session */ gnutls_init (&session, GNUTLS_CLIENT); /* Use default priorities */ gnutls_priority_set_direct (session, "NORMAL:+ANON-DH", NULL); /* put the anonymous and TLS/IA credentials to the current session */ gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred); gnutls_credentials_set (session, GNUTLS_CRD_IA, iacred); /* connect to the peer */ sd = tcp_connect (); gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); /* Perform the TLS handshake */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "*** Handshake failed\n"); gnutls_perror (ret); goto end; } else { printf ("- Handshake was completed\n"); } if (!gnutls_ia_handshake_p (session)) { fprintf (stderr, "*** TLS/IA not negotiated...\n"); goto end; } else { printf ("- Starting TLS/IA handshake...\n"); ret = gnutls_ia_handshake (session); if (ret < 0) { fprintf (stderr, "*** TLS/IA handshake failed\n"); gnutls_perror (ret); goto end; } else { printf ("- TLS/IA Handshake was completed\n"); } } gnutls_record_send (session, MSG, strlen (MSG)); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (ret == 0) { printf ("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0) { fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret)); goto end; } printf ("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fputs ("\n", stdout); gnutls_bye (session, GNUTLS_SHUT_RDWR); end: tcp_close (sd); gnutls_deinit (session); gnutls_ia_free_client_credentials (iacred); gnutls_anon_free_client_credentials (anoncred); gnutls_global_deinit (); return 0; } 7.3.9 Helper Function for TCP Connections ----------------------------------------- This helper function abstracts away TCP connection handling from the other examples. It is required to build some examples. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include #define SA struct sockaddr /* Connects to the peer and returns a socket * descriptor. */ extern int tcp_connect (void) { const char *PORT = "5556"; const char *SERVER = "127.0.0.1"; int err, sd; struct sockaddr_in sa; /* connects to server */ sd = socket (AF_INET, SOCK_STREAM, 0); memset (&sa, '\0', sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (atoi (PORT)); inet_pton (AF_INET, SERVER, &sa.sin_addr); err = connect (sd, (SA *) & sa, sizeof (sa)); if (err < 0) { fprintf (stderr, "Connect error\n"); exit (1); } return sd; } /* closes the given socket descriptor. */ extern void tcp_close (int sd) { shutdown (sd, SHUT_RDWR); /* no more receptions */ close (sd); } 7.4 Server Examples =================== This section contains examples of TLS and SSL servers, using GnuTLS. 7.4.1 Echo Server with X.509 Authentication ------------------------------------------- This example is a very simple echo server which supports X.509 authentication, using the RSA ciphersuites. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include #include #include #include /* for gcry_control */ #define KEYFILE "key.pem" #define CERTFILE "cert.pem" #define CAFILE "ca.pem" #define CRLFILE "crl.pem" /* This is a sample TLS 1.0 echo server, using X.509 authentication. */ #define SA struct sockaddr #define SOCKET_ERR(err,s) if(err==-1) {perror(s);return(1);} #define MAX_BUF 1024 #define PORT 5556 /* listen to 5556 port */ #define DH_BITS 1024 /* These are global */ gnutls_certificate_credentials_t x509_cred; gnutls_priority_t priority_cache; gnutls_session_t initialize_tls_session (void) { gnutls_session_t session; gnutls_init (&session, GNUTLS_SERVER); gnutls_priority_set (session, priority_cache); gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred); /* request client certificate if any. */ gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUEST); /* Set maximum compatibility mode. This is only suggested on public webservers * that need to trade security for compatibility */ gnutls_session_enable_compatibility_mode( session); return session; } static gnutls_dh_params_t dh_params; static int generate_dh_params (void) { /* Generate Diffie Hellman parameters - for use with DHE * kx algorithms. When short bit length is used, it might * be wise to regenerate parameters. * * Check the ex-serv-export.c example for using static * parameters. */ gnutls_dh_params_init (&dh_params); gnutls_dh_params_generate2 (dh_params, DH_BITS); return 0; } int main (void) { int err, listen_sd, i; int sd, ret; struct sockaddr_in sa_serv; struct sockaddr_in sa_cli; int client_len; char topbuf[512]; gnutls_session_t session; char buffer[MAX_BUF + 1]; int optval = 1; /* to disallow usage of the blocking /dev/random */ gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); /* this must be called once in the program */ gnutls_global_init (); gnutls_certificate_allocate_credentials (&x509_cred); gnutls_certificate_set_x509_trust_file (x509_cred, CAFILE, GNUTLS_X509_FMT_PEM); gnutls_certificate_set_x509_crl_file (x509_cred, CRLFILE, GNUTLS_X509_FMT_PEM); gnutls_certificate_set_x509_key_file (x509_cred, CERTFILE, KEYFILE, GNUTLS_X509_FMT_PEM); generate_dh_params (); gnutls_priority_init( &priority_cache, "NORMAL", NULL); gnutls_certificate_set_dh_params (x509_cred, dh_params); /* Socket operations */ listen_sd = socket (AF_INET, SOCK_STREAM, 0); SOCKET_ERR (listen_sd, "socket"); memset (&sa_serv, '\0', sizeof (sa_serv)); sa_serv.sin_family = AF_INET; sa_serv.sin_addr.s_addr = INADDR_ANY; sa_serv.sin_port = htons (PORT); /* Server Port number */ setsockopt (listen_sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (int)); err = bind (listen_sd, (SA *) & sa_serv, sizeof (sa_serv)); SOCKET_ERR (err, "bind"); err = listen (listen_sd, 1024); SOCKET_ERR (err, "listen"); printf ("Server ready. Listening to port '%d'.\n\n", PORT); client_len = sizeof (sa_cli); for (;;) { session = initialize_tls_session (); sd = accept (listen_sd, (SA *) & sa_cli, &client_len); printf ("- connection from %s, port %d\n", inet_ntop (AF_INET, &sa_cli.sin_addr, topbuf, sizeof (topbuf)), ntohs (sa_cli.sin_port)); gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); ret = gnutls_handshake (session); if (ret < 0) { close (sd); gnutls_deinit (session); fprintf (stderr, "*** Handshake has failed (%s)\n\n", gnutls_strerror (ret)); continue; } printf ("- Handshake was completed\n"); /* see the Getting peer's information example */ /* print_info(session); */ i = 0; for (;;) { memset (buffer, 0, MAX_BUF + 1); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (ret == 0) { printf ("\n- Peer has closed the GNUTLS connection\n"); break; } else if (ret < 0) { fprintf (stderr, "\n*** Received corrupted " "data(%d). Closing the connection.\n\n", ret); break; } else if (ret > 0) { /* echo data back to the client */ gnutls_record_send (session, buffer, strlen (buffer)); } } printf ("\n"); /* do not wait for the peer to close the connection. */ gnutls_bye (session, GNUTLS_SHUT_WR); close (sd); gnutls_deinit (session); } close (listen_sd); gnutls_certificate_free_credentials (x509_cred); gnutls_priority_deinit(priority_cache); gnutls_global_deinit (); return 0; } 7.4.2 Echo Server with X.509 Authentication II ---------------------------------------------- The following example is a server which supports X.509 authentication. This server supports the export-grade cipher suites, the DHE ciphersuites and session resuming. /* Copyright 2007 Free Software Foundation * * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include #include #include #include /* for gcry_control */ #define KEYFILE "key.pem" #define CERTFILE "cert.pem" #define CAFILE "ca.pem" #define CRLFILE "crl.pem" /* This is a sample TLS 1.0 echo server. * Export-grade ciphersuites and session resuming are supported. */ #define SA struct sockaddr #define SOCKET_ERR(err,s) if(err==-1) {perror(s);return(1);} #define MAX_BUF 1024 #define PORT 5556 /* listen to 5556 port */ #define DH_BITS 1024 /* These are global */ gnutls_certificate_credentials_t cert_cred; static void wrap_db_init (void); static void wrap_db_deinit (void); static int wrap_db_store (void *dbf, gnutls_datum_t key, gnutls_datum_t data); static gnutls_datum_t wrap_db_fetch (void *dbf, gnutls_datum_t key); static int wrap_db_delete (void *dbf, gnutls_datum_t key); #define TLS_SESSION_CACHE 50 gnutls_session_t initialize_tls_session (void) { gnutls_session_t session; gnutls_init (&session, GNUTLS_SERVER); /* Use the default priorities, plus, export cipher suites. */ gnutls_priority_set_direct( session, "EXPORT", NULL); gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, cert_cred); /* request client certificate if any. */ gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUEST); gnutls_dh_set_prime_bits (session, DH_BITS); if (TLS_SESSION_CACHE != 0) { gnutls_db_set_retrieve_function (session, wrap_db_fetch); gnutls_db_set_remove_function (session, wrap_db_delete); gnutls_db_set_store_function (session, wrap_db_store); gnutls_db_set_ptr (session, NULL); } return session; } gnutls_dh_params_t dh_params; /* Export-grade cipher suites require temporary RSA * keys. */ gnutls_rsa_params_t rsa_params; static char srp_dh_group2048[] = "-----BEGIN DH PARAMETERS-----\n" "MIIBBwKCAQCsa9tBMkqam/Fm3l4TiVgvr3K2ZRmH7gf8MZKUPbVgUKNzKcu0oJnt\n" "gZPgdXdnoT3VIxKrSwMxDc1/SKnaBP1Q6Ag5ae23Z7DPYJUXmhY6s2YaBfvV+qro\n" "KRipli8Lk7hV+XmT7Jde6qgNdArb9P90c1nQQdXDPqcdKB5EaxR3O8qXtDoj+4AW\n" "dr0gekNsZIHx0rkHhxdGGludMuaI+HdIVEUjtSSw1X1ep3onddLs+gMs+9v1L7N4\n" "YWAnkATleuavh05zA85TKZzMBBx7wwjYKlaY86jQw4JxrjX46dv7tpS1yAPYn3rk\n" "Nd4jbVJfVHWbZeNy/NaO8g+nER+eSv9zAgEC\n" "-----END DH PARAMETERS-----\n"; int generate_dh_params (void) { gnutls_datum_t dparams = { srp_dh_group2048, sizeof( srp_dh_group2048) }; /* Here instead of generating Diffie Hellman parameters (for use with DHE * kx algorithms) we import them. */ gnutls_dh_params_init (&dh_params); gnutls_dh_params_import_pkcs3 (dh_params, &dparams, GNUTLS_X509_FMT_PEM); return 0; } static int generate_rsa_params (void) { gnutls_rsa_params_init (&rsa_params); /* Generate RSA parameters - for use with RSA-export * cipher suites. This is an RSA private key and should be * discarded and regenerated once a day, once every 500 * transactions etc. Depends on the security requirements. */ gnutls_rsa_params_generate2 (rsa_params, 512); return 0; } int main (void) { int err, listen_sd, i; int sd, ret; struct sockaddr_in sa_serv; struct sockaddr_in sa_cli; int client_len; char topbuf[512]; gnutls_session_t session; char buffer[MAX_BUF + 1]; int optval = 1; char name[256]; strcpy (name, "Echo Server"); /* to disallow usage of the blocking /dev/random */ gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); /* this must be called once in the program */ gnutls_global_init (); gnutls_certificate_allocate_credentials (&cert_cred); gnutls_certificate_set_x509_trust_file (cert_cred, CAFILE, GNUTLS_X509_FMT_PEM); gnutls_certificate_set_x509_crl_file (cert_cred, CRLFILE, GNUTLS_X509_FMT_PEM); gnutls_certificate_set_x509_key_file (cert_cred, CERTFILE, KEYFILE, GNUTLS_X509_FMT_PEM); generate_dh_params (); generate_rsa_params (); if (TLS_SESSION_CACHE != 0) { wrap_db_init (); } gnutls_certificate_set_dh_params (cert_cred, dh_params); gnutls_certificate_set_rsa_export_params (cert_cred, rsa_params); /* Socket operations */ listen_sd = socket (AF_INET, SOCK_STREAM, 0); SOCKET_ERR (listen_sd, "socket"); memset (&sa_serv, '\0', sizeof (sa_serv)); sa_serv.sin_family = AF_INET; sa_serv.sin_addr.s_addr = INADDR_ANY; sa_serv.sin_port = htons (PORT); /* Server Port number */ setsockopt (listen_sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (int)); err = bind (listen_sd, (SA *) & sa_serv, sizeof (sa_serv)); SOCKET_ERR (err, "bind"); err = listen (listen_sd, 1024); SOCKET_ERR (err, "listen"); printf ("%s ready. Listening to port '%d'.\n\n", name, PORT); client_len = sizeof (sa_cli); for (;;) { session = initialize_tls_session (); sd = accept (listen_sd, (SA *) & sa_cli, &client_len); printf ("- connection from %s, port %d\n", inet_ntop (AF_INET, &sa_cli.sin_addr, topbuf, sizeof (topbuf)), ntohs (sa_cli.sin_port)); gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd); ret = gnutls_handshake (session); if (ret < 0) { close (sd); gnutls_deinit (session); fprintf (stderr, "*** Handshake has failed (%s)\n\n", gnutls_strerror (ret)); continue; } printf ("- Handshake was completed\n"); /* print_info(session); */ i = 0; for (;;) { memset (buffer, 0, MAX_BUF + 1); ret = gnutls_record_recv (session, buffer, MAX_BUF); if (ret == 0) { printf ("\n- Peer has closed the TLS connection\n");