GNUTLS

a Transport Layer Security Library
This is a Draft document
Applies to GnuTLS 1.0.17


Copyright © 2001,2002,2003,2004 Nikos Mavroyanopoulos

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


Contents

[RE] [LO] [RO,LE] [C]

Preface

Introduction

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.

This document tries to be self contained, although basic network programming and PKI knowlegde is assumed in most of it. [6] is a good introduction to Public Key Infrastructure.

Availability

Updated versions of the GnuTLS software and this document will be available from http://www.gnutls.org/ and http://www.gnu.org/software/gnutls/.

The Library

Description

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.01.1 and SSL 3.0 protocols, accompanied with the required framework for authentication and public key infrastructure. The library is available under the GNU Lesser GPL license1.2. Important features of the GnuTLS library include:

Additionally GnuTLS provides a limited emulation API for the widely used OpenSSL1.3 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 Libtasn11.4a library which offers ASN.1 parsing capabilities, is used for the X.509 certificate parsing functions, and Opencdk1.5is used for the OpenPGP key support in GnuTLS. The `Crypto backend' is provided by the libgcrypt1.6library.

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.

General Idea

A brief description of how GnuTLS works internally is shown at the figure 1.2. This section may be easier to understand after having seen the examples on page [*].

\includegraphics[height=8cm,width=12cm]{internals}

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 authentication1.7. 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 function1.8 to store the newly negotiated session. The session database is examined by the server just after having received the client hello1.9, 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.


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, ie 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 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 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. All the error codes are documented in appendix B on page [*].

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


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.

Other callback functions such as the one set by 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.

Introduction to TLS

TLS stands for 'Transport Layer Security' and is the successor of SSL, the Secure Sockets Layer protocol2.1 designed by Netscape. TLS 1.0 is an Internet protocol, defined by IETF2.2, described in [4] and also in [16]. The protocol provides confidentiality, and authentication layers over any reliable transport layer. The description, below, refers to TLS 1.0 but also applies to 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.


TLS layers

TLS 1.0 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. See section 2.4 on page [*] 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. See section 2.5 on page [*] for more information about the handshake protocol. The protocol layering in TLS is shown at figure.

Figure 2.1: Layers in the TLS protocol
\includegraphics[height=8cm,width=12cm]{layers}

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.

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.

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.

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.


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:

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.


Encryption algorithms used in the record layer

Confidentiality in the record layer is achieved by using symmetric block encryption algorithms like 3DES, AES2.3, or stream algorithms like ARCFOUR_1282.4 See fig:ciphers for a complete list. 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 1.0 protocol, a random number of blocks will be appended to data, to prevent eavesdroppers from guessing the actual data size.

Figure 2.2: Supported cipher algorithms
\begin{figure}\begin{tabular}{\vert l\vert p{9cm}\vert}
\par\hline
3DES\_CBC & 3...
...e. This is not officially
supported in TLS.
\\
\hline
\end{tabular}\end{figure}

Figure 2.3: Supported MAC algorithms
\begin{figure}\begin{tabular}{\vert l\vert p{9cm}\vert}
\par\hline
MAC\_MD5 & MD...
...uts 160 bits of data.
\\
\hline
\end{tabular}\index{MAC algorithms}\end{figure}


Compression algorithms used in the record layer

The TLS' record layer also supports compression. The algorithms implemented in GnuTLS can be found in figure 2.4. All the algorithms except for DEFLATE which is referenced in [7], should be considered as GnuTLS' extensions2.5, 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 compressable 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 paper [7].

Figure 2.4: Supported compression algorithms
\begin{figure}\begin{tabular}{\vert l\vert p{9cm}\vert}
\par\hline
DEFLATE & Zli...
...zed and the
private extensions are enabled.
\\
\hline
\end{tabular}\end{figure}


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 which is implemented in GnuTLS. For a detailed discussion see the archives of the TLS Working Group mailing list and the paper [12].


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.


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:

TLS cipher suites

The Handshake Protocol of TLS 1.0 negotiates cipher suites of the form
TLS_DHE_RSA_WITH_3DES_CBC_SHA. The usual cipher suites contain these parameters:

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 appendix C on page [*].

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 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. The client may then send a certificate, signed by one of the server's acceptable signers. In GnuTLS the server's acceptable signers list is constructed using the trusted CA certificates in the credentials structure.


Resuming Sessions

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

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. Ie. copy and keep the necessary parameters. See the functions:

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:

It might also be useful to be able to check for expired sessions in order to remove them, and save space. The function gnutls_db_check_entry is provided for that reason.


TLS Extensions

A number of extensions to the TLS protocol have been proposed mainly in [2]. The extensions supported in GnuTLS are

discussed in the subsections that follow.


Maximum fragment length negotiation

This extension allows a TLS 1.0 implementation to negotiate a smaller value for record packet maximum length. This extension may be useful to clients with constrained capabilities. See the gnutls_record_set_max_size and the gnutls_record_get_max_size functions.


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 gnutls_server_name_set and gnutls_server_name_get can be used to enable this extension, or to retrieve the name sent by a client.

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:

  1. Certificate authentication
  2. Anonymous authentication
  3. SRP authentication

Certificate authentication


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. See section 4.1 on page [*] for more information on X.509 protocols.


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 [11] proposal.

See 4.2 on page [*] for more information about the OpenPGP trust model. For a more detailed introduction to OpenPGP and GnuPG see [1].

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 gnutls_certificate_set_x509_key_file or 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:

Certificate verification is possible by loading the trusted authorities into the credentials structure by using gnutls_certificate_set_x509_trust_file or gnutls_certificate_set_openpgp_keyring_file for openpgp keys. Note however that the peer's certificate is not automatically verified, you should call gnutls_certificate_verify_peers , after a successful handshake, to verify the signatures of the certificate. An alternative way, which reports a more detailed verification output, is to use gnutls_certificate_get_peers to obtain the raw certificate of the peer and verify it using the functions discussed in section 4.1 on page [*].

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 in figure are available in certificate authentication.

Note that the DHE key exchange methods are generally slower3.1 than plain RSA and require Diffie Hellman parameters to be generated and associated with a credentials structure. The RSA-EXPORT method also requires 512 bit RSA parameters, that should also be generated and associated with the credentials structure. See the functions:

Figure 3.1: Key exchange algorithms for OpenPGP and X.509 certificates.
\begin{figure}\index{Key exchange algorithms}
\begin{tabular}{\vert l\vert p{9cm...
...nds for Digital Signature
Standard.
\\
\hline
\end{tabular}\par\par\end{figure}


Anonymous authentication

The anonymous key exchange perform 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 in figure.

Note that the key exchange methods for anonymous authentication require Diffie Hellman parameters to be generated and associated with an anonymous credentials structure.

Figure 3.2: Supported anonymous key exchange algorithms
\begin{figure}\begin{tabular}{\vert l\vert p{9cm}\vert}
\par\hline
ANON\_DH & Th...
...changes Diffie Hellman parameters.
\\
\hline
\end{tabular}\par\par\end{figure}


Authentication using SRP

Authentication using the SRP3.2protocol is actually password authentication. 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 schemas, 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 ``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. See [18] 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 [17]. The available key exchange methods are shown in figure.

Figure 3.3: Supported SRP key exchange algorithms
\begin{figure}\begin{tabular}{\vert l\vert p{9cm}\vert}
\par\hline
SRP & Authent...
... a certificate with RSA parameters.
\\
\hline
\end{tabular}\par\par\end{figure}

If clients supporting SRP know the username and password before the connection, should initialize the client credentials and call the function gnutls_srp_set_client_credentials . Alternatively they could specify a callback function by using the function 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 gnutls_srp_set_server_credentials_file . If a different password file format is to be used, then the function gnutls_srp_set_server_credentials_function , should be called, in order to set an appropriate callback.

Some helper functions such as

are included in GnuTLS, and may be used to generate, and maintain SRP verifiers, and password files. A program to manipulate the required parameters for SRP authentication is also included. See section 7.1 on page [*] for more information.

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 gnutls_credentials_set . A mapping is shown in figure.

Figure 3.4: Key exchange algorithms and the corresponding credential types
\begin{figure}\begin{tabular}{\vert l\vert l\vert p{4.5cm}\vert}
\par\hline
\bf ...
...X\_ANON\_DH & CRD\_ANON & CRD\_ANON
\\
\hline
\end{tabular}\par\par\end{figure}

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 and gnutls_rsa_params, and functions like gnutls_certificate_set_dh_params and 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 gnutls_certificate_set_params_function . An example is shown below.

#include <gnutls.h>

gnutls_rsa_params rsa_params;
gnutls_dh_params 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 session, gnutls_params_type 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 cert_cred;

   initialize_params();

   /* ...
    */

   gnutls_certificate_set_params_function( cert_cred, get_params);

}


More on certificate authentication


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.

Figure 4.1: X.509 certification
\includegraphics[height=9.5cm,width=7cm]{x509-1}

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 figure 4.1 for a typical example. The API for handling X.509 certificates is described at section 8.2 on page [*]. Some examples are listed below.

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 [8] 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.
[gray]0.9 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.
CRL distribution points 2.5.29.31 This extension is set by the CA, in order to inform about the issued CRLs.


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 6.5.2 on page [*].

Verifying X.509 certificate paths

Verifying certificate paths is important in X.509 authentication. For this purpose the function gnutls_x509_crt_verify is provided. The output of this function is the bitwise OR of the elements of the ``gnutls_certificate_status'' enumeration. A detailed description of these elements can be found in figure 4.2. The function gnutls_certificate_verify_peers is equivalent to the previous one, and will verify the peer's certificate in a TLS session.

Figure 4.2: X.509 certificate verification
\begin{figure}\begin{tabular}{\vert l\vert p{7cm}\vert}
\par\hline
CERT\_INVALID...
...ND & The certificate's issuer is not known.
\\
\hline
\end{tabular}\end{figure}

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. See [15] and section 6.3.3 on page [*] for an example.


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 [14]. Other certificate request's format such as PKIX's RFC2511 [13] 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 6.5.3 on page [*].


PKCS #12 structures

A PKCS #12 structure [10] 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 6.5.4 on page [*].


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.

\includegraphics[height=9cm,width=11cm]{pgp-fig1}

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.

OpenPGP keys

In GnuTLS the OpenPGP key structures [3] are handled using the gnutls_openpgp_key_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.

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 GPGME4.1is recommended.

There are two verification functions in GnuTLS, The gnutls_openpgp_key_verify_ring and the gnutls_openpgp_key_verify_trustdb . The first one 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 figure 4.3.
The latter function checks a GnuPG trust database for the given key. This function does not check the key signatures, only checks for disabled and revoked keys.

Figure 4.3: OpenPGP key verification
\begin{figure}\begin{tabular}{\vert l\vert p{7cm}\vert}
\par\hline
CERT\_INVALID...
...& The key was not signed by a known signer.
\\
\hline
\end{tabular}\end{figure}


How to use TLS in application protocols

Introduction

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.

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 HTTPS5.1 protocol [15].

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 work5.2. 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.

Upward negotiation

Other application protocols5.3use 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 [9] 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 file5.4, or anything else!


How to use GnuTLS in applications

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.

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.

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 gnutls_check_version

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`

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.

Client examples

This section contains examples of TLS and SSL clients, using GnuTLS. Note that these examples contain little or no error checking.

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.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <gnutls/gnutls.h>

/* A very basic TLS client.
 */

#define MAX_BUF 1024
#define CAFILE "ca.pem"
#define SA struct sockaddr
#define MSG "GET / HTTP/1.0\r\n\r\n"

/* Connects to the peer and returns a socket
 * descriptor.
 */
int tcp_connect( void)
{
   const char *PORT = "443";
   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.
 */
void tcp_close( int sd) 
{
   shutdown(sd, SHUT_RDWR);     /* no more receptions */
   close(sd);
}

int main()
{
   int ret, sd, ii;
   gnutls_session session;
   char buffer[MAX_BUF + 1];
   gnutls_certificate_credentials xcred;
   /* Allow connections to servers that have OpenPGP keys as well.
    */
   const int cert_type_priority[3] = { GNUTLS_CRT_X509, 
      GNUTLS_CRT_OPENPGP, 0 };

   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 */
   gnutls_set_default_priority(session);
   gnutls_certificate_type_set_priority(session, cert_type_priority);

   /* 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)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;
}

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 gnutls_handshake

#include <stdio.h>
#include <stdlib.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>

extern void print_x509_certificate_info(gnutls_session);

/* This function will print some details of the
 * given session.
 */
int print_info(gnutls_session session)
{
   const char *tmp;
   gnutls_credentials_type cred;
   gnutls_kx_algorithm 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_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;
}

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. The following function is an example on how to verify the peer's certificate chain. This is an advanced case. Things in a TLS session may be simplified by using gnutls_certificate_verify_peers2 .

#include <stdio.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>

/* All the available CRLs
 */
extern gnutls_x509_crl* crl_list;
extern int crl_list_size;

/* All the available trusted CAs
 */
extern gnutls_x509_crt* ca_list;
extern int ca_list_size;

static void verify_cert2(gnutls_x509_crt crt,
   gnutls_x509_crt issuer, gnutls_x509_crl * crl_list, int crl_list_size);
static void verify_last_cert(gnutls_x509_crt crt,
   gnutls_x509_crt *ca_list, int ca_list_size,
   gnutls_x509_crl * 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 session, const char* hostname,
   const gnutls_datum* cert_chain, int cert_chain_length)
{
   int i, ret;
   gnutls_x509_crt 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);
   }

   /* 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 crt,
   gnutls_x509_crt issuer, gnutls_x509_crl * 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 the trusted CA list.
 * Also checks the crl_list if the certificate is revoked.
 */
static void verify_last_cert(gnutls_x509_crt crt,
   gnutls_x509_crt *ca_list, int ca_list_size,
   gnutls_x509_crl * 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, 0, &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");
   }
}

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.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>

/* A TLS client that loads the certificate and key.
 */

#define MAX_BUF 1024
#define SA struct sockaddr
#define MSG "GET / HTTP/1.0\r\n\r\n"

#define CERT_FILE "cert.pem"
#define KEY_FILE "key.pem"
#define CAFILE "ca.pem"

static int cert_callback(gnutls_session session,
   const gnutls_datum* req_ca_rdn, int nreqs,
   const gnutls_pk_algorithm* sign_algos, int sign_algos_length,
   gnutls_retr_st * st);

gnutls_x509_crt crt;
gnutls_x509_privkey key;

/* Helper functions to load a certificate and key
 * files into memory. They use mmap for simplicity.
 */
static gnutls_datum mmap_file( const char* file)
{
int fd;
gnutls_datum mmaped_file = { NULL, 0 };
struct stat stat_st;
void* ptr;

   fd = open( file, 0);
   if (fd==-1) return mmaped_file;
   
   fstat( fd, &stat_st);
   
   if ((ptr=mmap( NULL, stat_st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
      return mmaped_file;
   
   mmaped_file.data = ptr;
   mmaped_file.size = stat_st.st_size;
   
   return mmaped_file;
}

static void munmap_file( gnutls_datum data)
{
   munmap( data.data, data.size);
}

/* Load the certificate and the private key.
 */
static void load_keys( void)
{
int ret;
gnutls_datum data;

   data = mmap_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);
   }

   munmap_file( data);

   data = mmap_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);
   }

   munmap_file( data);
   
}

int main()
{
   int ret, sd, ii;
   gnutls_session session;
   char buffer[MAX_BUF + 1];
   gnutls_certificate_credentials xcred;
   /* Allow connections to servers that have OpenPGP keys as well.
    */

   gnutls_global_init();

   load_keys();

   /* X509 stuff */
   gnutls_certificate_allocate_credentials(&xcred);

   /* 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_set_default_priority(session);

   /* 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)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