This is ./gnutls.info, produced by makeinfo version 4.8 from
./gnutls.texi.

This manual is last updated 7 January 2012 for version 2.12.23 of
GnuTLS.

Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
2010 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.3 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".

INFO-DIR-SECTION Software libraries
START-INFO-DIR-ENTRY
* GnuTLS: (gnutls).		GNU Transport Layer Security Library.
END-INFO-DIR-ENTRY

INFO-DIR-SECTION System Administration
START-INFO-DIR-ENTRY
* certtool: (gnutls)Invoking certtool.	Manipulate certificates and keys.
* gnutls-serv: (gnutls)Invoking gnutls-serv.	GnuTLS test server.
* gnutls-cli: (gnutls)Invoking gnutls-cli.	GnuTLS test client.
* gnutls-cli-debug: (gnutls)Invoking gnutls-cli-debug.	GnuTLS debug client.
* psktool: (gnutls)Invoking psktool.	Simple TLS-Pre-Shared-Keys manager.
* srptool: (gnutls)Invoking srptool.	Simple SRP password tool.
END-INFO-DIR-ENTRY


File: gnutls.info,  Node: Top,  Next: Preface,  Up: (dir)

GnuTLS
******

This manual is last updated 7 January 2012 for version 2.12.23 of
GnuTLS.

Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
2010 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.3 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".

* Menu:

* Preface::
* The Library::
* Introduction to TLS::
* Authentication methods::
* More on certificate authentication::
* How to use TLS in application protocols::
* How to use GnuTLS in applications::
* Included programs::
* Function reference::
* All the supported ciphersuites in GnuTLS::
* Guile Bindings::
* Internal architecture of GnuTLS::
* Copying Information::
* Concept Index::
* Function and Data Index::
* Bibliography::


File: gnutls.info,  Node: Preface,  Next: The Library,  Prev: Top,  Up: Top

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

* Menu:

* Getting help::
* Commercial Support::
* Downloading and Installing::
* Bug Reports::
* Contributing::


File: gnutls.info,  Node: Getting help,  Next: Commercial Support,  Up: Preface

1.1 Getting Help
================

A mailing list where users may help each other exists, and you can
reach it by sending e-mail to <help-gnutls@gnu.org>.  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 <bug-gnutls@gnu.org>, see *Note Bug
Reports::.


File: gnutls.info,  Node: Commercial Support,  Next: Downloading and Installing,  Prev: Getting help,  Up: Preface

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 provides support related to GnuTLS and would like to be
mentioned here, contact the author (*note Bug Reports::).


File: gnutls.info,  Node: Downloading and Installing,  Next: Bug Reports,  Prev: Commercial Support,  Up: Preface

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.12.23.tar.gz'
where the `2.12.23' 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/'.

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 uses a stripped down version of OpenCDK for
parsing OpenPGP packets.  It is included GnuTLS.  Use parameter
`--disable-openpgp-authentication' to disable the OpenPGP functionality
in GnuTLS.  Unfortunately, we didn't have resources to maintain the
code in a separate library.

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


File: gnutls.info,  Node: Bug Reports,  Next: Contributing,  Prev: Downloading and Installing,  Up: Preface

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'


File: gnutls.info,  Node: Contributing,  Prev: Bug Reports,  Up: Preface

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.

     If you normally code using another coding standard, there is no
     problem, but you should use `indent' to reformat the code 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.



File: gnutls.info,  Node: The Library,  Next: Introduction to TLS,  Prev: Preface,  Up: Top

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 protocols ranging from SSL 3.0 to TLS 1.2 (*Note Introduction to
TLS::, for a more detailed description of the protocols), accompanied
with the required framework for authentication and public key
infrastructure.  Important features of the GnuTLS library include:

   * Support for TLS 1.2, TLS 1.1, TLS 1.0 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(1) library, to ease integration with existing applications.

GnuTLS consists of three independent parts, namely the "TLS protocol
part", the "Certificate part", and the "Cryptographic 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(2), a
library which offers ASN.1 parsing capabilities, is used for the X.509
certificate parsing functions.  A smaller version of OpenCDK(3) is used
for the OpenPGP key support in GnuTLS.  The "Cryptographic backend" is
provided by the Libgcrypt(4) library(5).

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.

* Menu:

* General Idea::
* Error handling::
* Memory handling::
* Callback functions::

---------- Footnotes ----------

(1) `http://www.openssl.org/'

(2) `ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/libtasn1/'

(3) `ftp://ftp.gnupg.org/gcrypt/alpha/gnutls/opencdk/'

(4) `ftp://ftp.gnupg.org/gcrypt/alpha/libgcrypt/'

(5) On current versions of GnuTLS it is possible to override the
default crypto backend. Check *note Cryptographic Backend:: for details


File: gnutls.info,  Node: General Idea,  Next: Error handling,  Up: The Library

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

 [image src="gnutls-internals.png" ]

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


File: gnutls.info,  Node: Error handling,  Next: Memory handling,  Prev: General Idea,  Up: The Library

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.


File: gnutls.info,  Node: Memory handling,  Next: Callback functions,  Prev: Error handling,  Up: The Library

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.


File: gnutls.info,  Node: Callback functions,  Prev: Memory handling,  Up: The Library

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



File: gnutls.info,  Node: Introduction to TLS,  Next: Authentication methods,  Prev: The Library,  Up: Top

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 4346 and also in [RESCORLA] (*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.  GnuTLS also supports X.509
and OpenPGP [RFC4880] (*note Bibliography::).

* Menu:

* TLS layers::
* The transport layer::
* The TLS record protocol::
* The TLS Alert Protocol::
* The TLS Handshake Protocol::
* TLS Extensions::
* Selecting cryptographic key sizes::
* On SSL 2 and older protocols::

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


File: gnutls.info,  Node: TLS layers,  Next: The transport layer,  Up: Introduction to TLS

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.

 [image src="gnutls-layers.png" ]


File: gnutls.info,  Node: The transport layer,  Next: The TLS record protocol,  Prev: TLS layers,  Up: Introduction to TLS

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


File: gnutls.info,  Node: The TLS record protocol,  Next: The TLS Alert Protocol,  Prev: The transport layer,  Up: Introduction to TLS

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.

* Menu:

* Encryption algorithms used in the record layer::
* Compression algorithms used in the record layer::
* Weaknesses and countermeasures::
* On Record Padding::


File: gnutls.info,  Node: Encryption algorithms used in the record layer,  Next: Compression algorithms used in the record layer,  Up: The TLS record protocol

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.

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.


File: gnutls.info,  Node: Compression algorithms used in the record layer,  Next: Weaknesses and countermeasures,  Prev: Encryption algorithms used in the record layer,  Up: The TLS record protocol

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, and if GnuTLS was built with LZO
     support.


---------- Footnotes ----------

(1) You should use *Note gnutls_handshake_set_private_extensions:: to
enable private extensions.


File: gnutls.info,  Node: Weaknesses and countermeasures,  Next: On Record Padding,  Prev: Compression algorithms used in the record layer,  Up: The TLS record protocol

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


File: gnutls.info,  Node: On Record Padding,  Prev: Weaknesses and countermeasures,  Up: The TLS record protocol

3.3.4 On Record Padding
-----------------------

The TLS protocol allows for random padding of records, to make it more
difficult to perform analysis on the length of exchanged messages (RFC
5246 6.2.3.2).  GnuTLS appears to be one of few implementation that
take advantage of this text, and pad records by a random length.

The TLS implementation in the Symbian operating system, frequently used
by Nokia and Sony-Ericsson mobile phones, cannot handle non-minimal
record padding.  What happens when one of these clients handshake with
a GnuTLS server is that the client will fail to compute the correct MAC
for the record.  The client sends a TLS alert (`bad_record_mac') and
disconnects.  Typically this will result in error messages such as 'A
TLS fatal alert has been received', 'Bad record MAC', or both, on the
GnuTLS server side.

GnuTLS implements a work around for this problem.  However, it has to
be enabled specifically.  It can be enabled by using *Note
gnutls_record_disable_padding::, or *Note gnutls_priority_set:: with
the `%COMPAT' priority string.

If you implement an application that have a configuration file, we
recommend that you make it possible for users or administrators to
specify a GnuTLS protocol priority string, which is used by your
application via *Note gnutls_priority_set::.  To allow the best
flexibility, make it possible to have a different priority string for
different incoming IP addresses.

To enable the workaround in the `gnutls-cli' client or the
`gnutls-serv' server, for testing of other implementations, use the
following parameter: `--priority "NORMAL:%COMPAT"'.


File: gnutls.info,  Node: The TLS Alert Protocol,  Next: The TLS Handshake Protocol,  Prev: The TLS record protocol,  Up: Introduction to TLS

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.



File: gnutls.info,  Node: The TLS Handshake Protocol,  Next: TLS Extensions,  Prev: The TLS Alert Protocol,  Up: Introduction to TLS

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.

* Menu:

* TLS Cipher Suites::           TLS session parameters.
* Priority Strings::            Defining how parameters are negotiated.
* Client Authentication::       Requesting a certificate from the client.
* Resuming Sessions::           Reusing previously established keys.
* Resuming Internals::          More information on reusing previously established keys.
* Interoperability::            About interoperability with other implementations.


File: gnutls.info,  Node: TLS Cipher Suites,  Next: Priority Strings,  Up: The TLS Handshake Protocol

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.

All the supported ciphersuites are shown in *Note ciphersuites::.

---------- Footnotes ----------

(1) MAC stands for Message Authentication Code. It can be described as
a keyed hash algorithm. See RFC2104.


File: gnutls.info,  Node: Priority Strings,  Next: Client Authentication,  Prev: TLS Cipher Suites,  Up: The TLS Handshake Protocol

3.5.2 Priority Strings
----------------------

In order to specify cipher suite preferences, the previously shown
priority functions accept a string that specifies the algorithms to be
enabled in a TLS handshake.  That string may contain some high level
keyword such as:

PERFORMANCE:
     All the "secure" ciphersuites are enabled, limited to 128 bit
     ciphers and sorted by terms of speed performance.

NORMAL:
     Means all "secure" ciphersuites. The 256-bit ciphers are included
     as a fallback only.  The ciphers are sorted by security margin.

SECURE128:
     Means all "secure" ciphersuites with ciphers up to 128 bits,
     sorted by security margin.

SECURE256:
     Means all "secure" ciphersuites including the 256 bit ciphers,
     sorted by security margin.

EXPORT:
     Means all ciphersuites are enabled, including the low-security 40
     bit ciphers.

NONE:
     Means nothing is enabled.  This disables even protocols and
     compression methods. It should be followed by the algorithms to be
     enabled.


or it might contain special keywords, that will be explained later on.

Unless the first keyword is "NONE" the defaults (in preference order)
are for TLS protocols TLS 1.2, TLS1.1, TLS1.0, SSL3.0; for compression
NULL; for certificate types X.509, OpenPGP.  For key exchange
algorithms when in NORMAL or SECURE levels the perfect forward secrecy
algorithms take precedence of the other protocols.  In all cases all
the supported key exchange algorithms  are enabled (except for the
RSA-EXPORT which is only enabled in EXPORT level).

The NONE keyword is followed by the algorithms to be enabled, and is
used to provide the exact list of requested algorithms(1). The order
with which every algorithm is specified is significant. Similar
algorithms specified before others will take precedence.

Keywords prepended to individual algorithms:
'!' or '-'
     appended with an algorithm will remove this algorithm.

"+"
     appended with an algorithm will add this algorithm.


Individual algorithms:
Ciphers:
     AES-128-CBC, AES-256-CBC, CAMELLIA-128-CBC, CAMELLIA-256-CBC,
     ARCFOUR-128, 3DES-CBC ARCFOUR-40. Catch all name is CIPHER-ALL
     which will add all the algorithms from NORMAL priority.

Key exchange:
     RSA, DHE-RSA, DHE-DSS, SRP, SRP-RSA, SRP-DSS, PSK, DHE-PSK,
     ANON-DH, RSA-EXPORT. The key exchange methods do not have a catch
     all.

MAC:
     MD5, SHA1, SHA256. All algorithms from NORMAL priority can be
     accessed with MAC-ALL.

Compression algorithms:
     COMP-NULL, COMP-DEFLATE. Catch all is COMP-ALL.

TLS versions:
     VERS-SSL3.0, VERS-TLS1.0, VERS-TLS1.1, VERS-TLS1.2. Catch all is
     VERS-TLS-ALL.

Signature algorithms:
     SIGN-RSA-SHA1, SIGN-RSA-SHA224, SIGN-RSA-SHA256, SIGN-RSA-SHA384,
     SIGN-RSA-SHA512, SIGN-DSA-SHA1, SIGN-DSA-SHA224, SIGN-DSA-SHA256,
     SIGN-RSA-MD5. Catch all is SIGN-ALL. This is only valid for TLS
     1.2 and later.


Special keywords:
%COMPAT:
     will enable compatibility mode. It might mean that violations of
     the protocols are allowed as long as maximum compatibility with
     problematic clients and servers is achieved.

%DISABLE_SAFE_RENEGOTIATION:
     will disable safe renegotiation completely.  Do not use unless you
     know what you are doing.  Testing purposes only.

%UNSAFE_RENEGOTIATION:
     will allow handshakes and rehandshakes without the safe
     renegotiation extension.  Note that for clients this mode is
     insecure (you may be under attack), and for servers it will allow
     insecure clients to connect (which could be fooled by an
     attacker).  Do not use unless you know what you are doing and want
     maximum compatibility.

%PARTIAL_RENEGOTIATION:
     will allow initial handshakes to proceed, but not rehandshakes.
     This leaves the client vulnerable to attack, and servers will be
     compatible with non-upgraded clients for initial handshakes.  This
     is currently the default for clients and servers, for
     compatibility reasons.

%SAFE_RENEGOTIATION:
     will enforce safe renegotiation.  Clients and servers will refuse
     to talk to an insecure peer.  Currently this causes operability
     problems, but is required for full protection.

%SSL3_RECORD_VERSION:
     will use SSL3.0 record version in client hello.  This is the
     default.

%LATEST_RECORD_VERSION:
     will use the latest TLS version record version in client hello.

%VERIFY_ALLOW_SIGN_RSA_MD5:
     will allow RSA-MD5 signatures in certificate chains.

%VERIFY_ALLOW_X509_V1_CA_CRT:
     will allow V1 CAs in chains.


---------- Footnotes ----------

(1) To avoid collisions in order to specify a compression algorithm in
this string you have to prefix it with "COMP-", protocol versions with
"VERS-", signature algorithms with "SIGN-" and certificate types with
"CTYPE-". All other algorithms don't need a prefix.


File: gnutls.info,  Node: Client Authentication,  Next: Resuming Sessions,  Prev: Priority Strings,  Up: The TLS Handshake Protocol

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


File: gnutls.info,  Node: Resuming Sessions,  Next: Resuming Internals,  Prev: Client Authentication,  Up: The TLS Handshake Protocol

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


File: gnutls.info,  Node: Resuming Internals,  Next: Interoperability,  Prev: Resuming Sessions,  Up: The TLS Handshake Protocol

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


File: gnutls.info,  Node: Interoperability,  Prev: Resuming Internals,  Up: The TLS Handshake Protocol

3.5.6 Interoperability
----------------------

The TLS handshake is a complex procedure that negotiates all required
parameters for a secure session. GnuTLS supports several TLS
extensions, as well as the latest TLS protocol version 1.2. However few
implementations are not able to properly interoperate once faced with
extensions or version protocols they do not support and understand. The
TLS protocol allows for a graceful downgrade to the commonly supported
options, but practice shows it is not always implemented correctly.

Because there is no way to achieve maximum interoperability with broken
peers without sacrificing security, GnuTLS ignores such peers by
default.  This might not be acceptable in cases where maximum
compatibility is required. Thus we allow enabling compatibility with
broken peers using priority strings (see *Note Priority Strings::). An
example priority string that is known to provide wide compatibility
even with broken peers is shown below:
     NORMAL:-VERS-TLS-ALL:+VERS-TLS1.0:+VERS-SSL3.0:%COMPAT
This priority string will only enable SSL 3.0 and TLS 1.0 as protocols
and will disable, via the `%COMPAT' keyword, several TLS protocol
options that are known to cause compatibility problems.  We suggest
however only to use this mode if compatibility issues occur.


File: gnutls.info,  Node: TLS Extensions,  Next: Selecting cryptographic key sizes,  Prev: The TLS Handshake Protocol,  Up: Introduction to TLS

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

   * Session tickets

   * Safe Renegotiation

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.6.3 Session Tickets
---------------------

To resume a TLS session the server normally store some state.  This
complicates deployment, and typical situations the client can cache
information and send it to the server instead.  The Session Ticket
extension implements this idea, and it is documented in RFC 5077
[TLSTKT] (*note Bibliography::).

Clients can enable support for TLS tickets with *Note
gnutls_session_ticket_enable_client:: and servers use *Note
gnutls_session_ticket_key_generate:: to generate a key and *Note
gnutls_session_ticket_enable_server:: to enable the extension.  Clients
resume sessions using the ticket using the normal session resume
functions, *Note resume::.

3.6.4 Safe Renegotiation
------------------------

TLS gives the option to two communicating parties to renegotiate and
update their security parameters. One useful example of this feature
was for a client to initially connect using anonymous negotiation to a
server, and the renegotiate using some authenticated ciphersuite. This
occured to avoid having the client sending its credentials in the clear.

However this renegotiation, as initially designed would not ensure that
the party one is renegotiating is the same as the one in the initial
negotiation.  For example one server could forward all renegotiation
traffic to an other server who will see this traffic as an initial
negotiation attempt.

This might be seen as a valid design decision, but it seems it was not
widely known or understood, thus today some application protocols the
TLS renegotiation feature in a manner that enables a malicious server
to insert content of his choice in the beginning of a TLS session.

The most prominent vulnerability was with HTTPS. There servers request
a renegotiation to enforce an anonymous user to use a certificate in
order to access certain parts of a web site.  The attack works by
having the attacker simulate a client and connect to a server, with
server-only authentication, and send some data intended to cause harm.
The server will then require renegotiation from him in order to perform
the request.  When the proper client attempts to contact the server,
the attacker hijacks that connection and forwards traffic to the
initial server that requested renegotiation.  The attacker will not be
able to read the data exchanged between the client and the server.
However, the server will (incorrectly) assume that the initial request
sent by the attacker was sent by the now authenticated client.  The
result is a prefix plain-text injection attack.

The above is just one example.  Other vulnerabilities exists that do
not rely on the TLS renegotiation to change the client's authenticated
status (either TLS or application layer).

While fixing these application protocols and implementations would be
one natural reaction, an extension to TLS has been designed that
cryptographically binds together any renegotiated handshakes with the
initial negotiation.  When the extension is used, the attack is
detected and the session can be terminated.  The extension is specified
in [RFC5746] (*note Bibliography::).

GnuTLS supports the safe renegotiation extension.  The default behavior
is as follows.  Clients will attempt to negotiate the safe
renegotiation extension when talking to servers.  Servers will accept
the extension when presented by clients.  Clients and servers will
permit an initial handshake to complete even when the other side does
not support the safe renegotiation extension.  Clients and servers will
refuse renegotiation attempts when the extension has not been
negotiated.

Note that permitting clients to connect to servers when the safe
renegotiation extension is not enabled, is open up for attacks.
Changing this default behaviour would prevent interoperability against
the majority of deployed servers out there.  We will reconsider this
default behaviour in the future when more servers have been upgraded.
Note that it is easy to configure clients to always require the safe
renegotiation extension from servers (see below on the
`%SAFE_RENEGOTIATION' priority string).

To modify the default behaviour, we have introduced some new priority
strings.  The priority strings can be used by applications (*note
gnutls_priority_set::) and end users (e.g., `--priority' parameter to
`gnutls-cli' and `gnutls-serv').

The `%UNSAFE_RENEGOTIATION' priority string permits (re-)handshakes
even when the safe renegotiation extension was not negotiated. The
default behavior is `%PARTIAL_RENEGOTIATION' that will prevent
renegotiation with clients and servers not supporting the extension.
This is secure for servers but leaves clients vulnerable to some
attacks, but this is a tradeoff between security and compatibility with
old servers. The `%SAFE_RENEGOTIATION' priority string makes clients
and servers require the extension for every handshake. The latter is
the most secure option for clients, at the cost of not being able to
connect to legacy servers. Servers will also deny clients that do not
support the extension from connecting.

It is possible to disable use of the extension completely, in both
clients and servers, by using the `%DISABLE_SAFE_RENEGOTIATION'
priority string however we strongly recommend you to only do this for
debugging and test purposes.

The default values if the flags above are not specified are:
`Server:'
     %PARTIAL_RENEGOTIATION

`Client:'
     %PARTIAL_RENEGOTIATION


For applications we have introduced a new API related to safe
renegotiation.  The *Note gnutls_safe_renegotiation_status:: function is
used to check if the extension has been negotiated on a session, and
can be used both by clients and servers.


File: gnutls.info,  Node: Selecting cryptographic key sizes,  Next: On SSL 2 and older protocols,  Prev: TLS Extensions,  Up: Introduction to TLS

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 "ECRYPT II Yearly Report on
Algorithms and Keysizes (2009-2010)" in [ECRYPT] (*note
Bibliography::).  Those can be used to generate certificates with
appropriate key sizes as well as parameters for Diffie-Hellman and SRP
authentication.

SecurityRSA, DH     ECC     `gnutls_sec_param_t'Description
bits    and SRP     key                    
        parameter   size                   
        size                               
64      816         128     `WEAK'         Very short term
                                           protection against small
                                           organizations
80      1248        160     `LOW'          Very short term
                                           protection against
                                           agencies
112     2432        224     `NORMAL'       Medium-term protection
128     3248        256     `HIGH'         Long term protection
256     15424       512     `ULTRA'        Foreseeable future

The first column provides a security parameter in a number of bits. This
gives an indication of the number of combinations to be tried by an
adversary to brute force a key. For example to test all possible keys
in a 112 bit security parameter 2^112 combinations have to be tried.
For today's technology this is infeasible.  The next two columns
correlate the security parameter with actual bit sizes of parameters
for DH, RSA, SRP and ECC algorithms.  A mapping to `gnutls_sec_param_t'
value is given for each security parameter, on the next column, and
finally a brief description of the level.

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.

NIST publication SP 800-57 [NISTSP80057] (*note Bibliography::)
contains a similar table.

When using GnuTLS and a decision on bit sizes for a public key
algorithm is required, use of the following functions is recommended:
   * *Note gnutls_pk_bits_to_sec_param::

   * *Note gnutls_sec_param_to_pk_bits::

Those functions will convert a human understandable security parameter
of `gnutls_sec_param_t' type, to a number of bits suitable for a public
key algorithm.


File: gnutls.info,  Node: On SSL 2 and older protocols,  Prev: Selecting cryptographic key sizes,  Up: Introduction to TLS

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.


File: gnutls.info,  Node: Authentication methods,  Next: More on certificate authentication,  Prev: Introduction to TLS,  Up: Top

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


* Menu:

* Certificate authentication::
* Anonymous authentication::
* Authentication using SRP::
* Authentication using PSK::
* Authentication and credentials::
* Parameters stored in credentials::


File: gnutls.info,  Node: Certificate authentication,  Next: Anonymous authentication,  Up: Authentication methods

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


Clients and servers that will select certificates using callback
functions should select a certificate according the peer's signature
algorithm preferences. To get those preferences use *Note
gnutls_sign_algorithm_get_requested::.

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


File: gnutls.info,  Node: Anonymous authentication,  Next: Authentication using SRP,  Prev: Certificate authentication,  Up: Authentication methods

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.



File: gnutls.info,  Node: Authentication using SRP,  Next: Authentication using PSK,  Prev: Anonymous authentication,  Up: Authentication methods

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


File: gnutls.info,  Node: Authentication using PSK,  Next: Authentication and credentials,  Prev: Authentication using SRP,  Up: Authentication methods

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.

The server can help the client chose a suitable username and password,
by sending a hint.  In the server, specify the hint by calling *Note
gnutls_psk_set_server_credentials_hint::.  The client can retrieve the
hint, for example in the callback function, using *Note
gnutls_psk_client_get_hint::.

There is no mechanism to derive a PSK key from a password specified by
the TLS PSK document(1).  For password-based authentication check *Note
Authentication using SRP::.

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.

---------- Footnotes ----------

(1) GnuTLS used to provide `gnutls_psk_netconf_derive_key' which
follows the algorithm specified in `draft-ietf-netconf-tls-02.txt'.
This method is deprecated and might be removed in later versions of
GnuTLS.


File: gnutls.info,  Node: Authentication and credentials,  Next: Parameters stored in credentials,  Prev: Authentication using PSK,  Up: Authentication methods

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'


File: gnutls.info,  Node: Parameters stored in credentials,  Prev: Authentication and credentials,  Up: Authentication methods

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

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


File: gnutls.info,  Node: More on certificate authentication,  Next: How to use TLS in application protocols,  Prev: Authentication methods,  Up: Top

5 More on Certificate Authentication
************************************

* Menu:

* The X.509 trust model::
* The OpenPGP trust model::
* PKCS #11 tokens::
* Abstract data types::
* Digital signatures::


File: gnutls.info,  Node: The X.509 trust model,  Next: The OpenPGP trust model,  Up: 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.

 [image src="gnutls-x509.png" ]

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.

* Menu:

* X.509 certificates::
* Verifying X.509 certificate paths::
* PKCS #10 certificate requests::
* PKCS #12 structures::


File: gnutls.info,  Node: X.509 certificates,  Next: Verifying X.509 certificate paths,  Up: The X.509 trust model

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 [PKIX] (*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::.


File: gnutls.info,  Node: Verifying X.509 certificate paths,  Next: PKCS #10 certificate requests,  Prev: X.509 certificates,  Up: The X.509 trust model

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.

`GNUTLS_CERT_INVALID:'
     The certificate is not signed by one of the known authorities, or
     the signature is invalid.

`GNUTLS_CERT_REVOKED:'
     The certificate has been revoked by its CA.

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


File: gnutls.info,  Node: PKCS #10 certificate requests,  Next: PKCS #12 structures,  Prev: Verifying X.509 certificate paths,  Up: The X.509 trust model

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


File: gnutls.info,  Node: PKCS #12 structures,  Prev: PKCS #10 certificate requests,  Up: The X.509 trust model

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


File: gnutls.info,  Node: The OpenPGP trust model,  Next: PKCS #11 tokens,  Prev: The X.509 trust model,  Up: More on certificate authentication

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.

 [image src="gnutls-pgp.png" ]

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.



File: gnutls.info,  Node: PKCS #11 tokens,  Next: Abstract data types,  Prev: The OpenPGP trust model,  Up: More on certificate authentication

5.3 PKCS #11 tokens
===================

5.3.1 Introduction
------------------

This section copes with the PKCS #11 [PKCS11] (*note Bibliography::)
support in GnuTLS.  PKCS #11 is plugin API allowing applications to
access cryptographic operations on a token, as well as to objects
residing on the token. A token can be a real hardware token such as a
smart card, or it can be a software component such as Gnome Keyring.
The objects residing on such token can be certificates, public keys,
private keys or even plain data or  secret keys. Of those certificates
and public/private key pairs can be used with GnuTLS. Its main
advantage is that it allows operations on private key objects such as
decryption and signing without accessing the key itself.

Moreover it can be used to allow all applications in the same operating
system to access shared cryptographic keys and certificates in a
uniform way, as in the following picture.

 [image src="pkcs11-vision.png" ]

5.3.2 Initialization
--------------------

To allow all the  GnuTLS applications to access PKCS #11 tokens you can
use a configuration per module, such as
`/etc/pkcs11/modules/mymodule.conf'.  This file has the following
format:

     module: /usr/lib/opensc-pkcs11.so

If you use this file, then there is no need for other initialization in
GnuTLS, except for the PIN and token functions. Those allow retrieving
a PIN when accessing a protected object, such as a private key, as well
as probe the user to insert the token. All the initialization functions
are below.

   * *Note gnutls_pkcs11_init::: Global initialization

   * *Note gnutls_pkcs11_deinit::: Global deinitialization

   * *Note gnutls_pkcs11_set_token_function::: Sets the token insertion
     function

   * *Note gnutls_pkcs11_set_pin_function::: Sets the PIN request
     function

   * *Note gnutls_pkcs11_add_provider::: Adds an additional PKCS #11
     provider


Note that due to limitations of PKCS #11 there might be issues when
multiple libraries are sharing a module. If this is the case we suggest
to use p11-kit(1) that provides an intermediate module to control
access to resources over the multiple users.

5.3.3 Reading Objects
---------------------

All PKCS #11 objects are referenced by GnuTLS functions by URLs as
described in `draft-pechanec-pkcs11uri-03'. For example a public key on
a smart card may be referenced as:

     pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315; \
     manufacturer=EnterSafe;object=test1;objecttype=public;\
     id=32:f1:53:f3:e3:79:90:b0:86:24:14:10:77:ca:5d:ec:2d:15:fa:ed

while the smart card itself can be referenced as:
     pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315;manufacturer=EnterSafe

Objects can be accessed with the following functions
   * *Note gnutls_pkcs11_obj_init::: Initializes an object

   * *Note gnutls_pkcs11_obj_import_url::: To import an object from a
     url

   * *Note gnutls_pkcs11_obj_export_url::: To export the URL of the
     object

   * *Note gnutls_pkcs11_obj_deinit::: To deinitialize an object

   * *Note gnutls_pkcs11_obj_export::: To export data associated with
     object

   * *Note gnutls_pkcs11_obj_get_info::: To obtain information about an
     object

   * *Note gnutls_pkcs11_obj_list_import_url::: To mass load of objects

   * *Note gnutls_x509_crt_import_pkcs11::: Import a certificate object

   * *Note gnutls_x509_crt_import_pkcs11_url::: Helper function to
     directly import a URL into a certificate

   * *Note gnutls_x509_crt_list_import_pkcs11::: Mass import of
     certificates


Functions that relate to token handling are shown below
   * *Note gnutls_pkcs11_token_init::: Initializes a token

   * *Note gnutls_pkcs11_token_set_pin::: Sets the token user's PIN

   * *Note gnutls_pkcs11_token_get_url::: Returns the URL of a token

   * *Note gnutls_pkcs11_token_get_info::: Obtain information about a
     token

   * *Note gnutls_pkcs11_token_get_flags::: Returns flags about a token
     (i.e. hardware or software)


The following example will list all tokens.

int i;
char* url;

gnutls_global_init();

for (i=0;;i++) {
	ret = gnutls_pkcs11_token_get_url(i, &url);
	if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
		break;

	if (ret < 0)
		exit(1);

	fprintf(stdout, "Token[%d]: URL: %s\n", i, url);
	gnutls_free(url);
}
gnutls_global_deinit();

The next one will list all certificates in a token, that have a
corresponding private key:

gnutls_pkcs11_obj_t *obj_list;
unsigned int obj_list_size = 0;
gnutls_datum_t cinfo;
int i;

obj_list_size = 0;
ret = gnutls_pkcs11_obj_list_import_url( obj_list, NULL, url, \
			GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY);
if (ret < 0 && ret != GNUTLS_E_SHORT_MEMORY_BUFFER)
	exit(1);

/* no error checking from now on */
obj_list = malloc(sizeof(*obj_list)*obj_list_size);

gnutls_pkcs11_obj_list_import_url( obj_list, &obj_list_size, url, flags);

/* now all certificates are in obj_list */
for (i=0;i<obj_list_size;i++) {

	gnutls_x509_crt_init(&xcrt);

	gnutls_x509_crt_import_pkcs11(xcrt, obj_list[i]);

	gnutls_x509_crt_print (xcrt, GNUTLS_CRT_PRINT_FULL, &cinfo);

	fprintf(stdout, "cert[%d]:\n %s\n\n", cinfo.data);

	gnutls_free(cinfo.data);
	gnutls_x509_crt_deinit(&xcrt);
}

5.3.4 Writing Objects
---------------------

With GnuTLS you can copy existing private keys and certificates to a
token. This can be achieved with the following functions

   * *Note gnutls_pkcs11_delete_url::: To delete an object

   * *Note gnutls_pkcs11_copy_x509_privkey::: To copy a private key to
     a token

   * *Note gnutls_pkcs11_copy_x509_crt::: To copy a certificate to a
     token


5.3.5 Using a PKCS #11 token with TLS
-------------------------------------

It is possible to use a PKCS #11 token to a TLS session, as shown in
*Note ex:pkcs11-client::. In addition the following functions can be
used to load PKCS #11 key and certificates.

   * *Note gnutls_certificate_set_x509_trust_file::: If given a PKCS
     #11 URL will load the trusted certificates from it.

   * *Note gnutls_certificate_set_x509_key_file::: Will also load PKCS
     #11 URLs for keys and certificates.


---------- Footnotes ----------

(1) http://p11-glue.freedesktop.org/


File: gnutls.info,  Node: Abstract data types,  Next: Digital signatures,  Prev: PKCS #11 tokens,  Up: More on certificate authentication

5.4 Abstract data types
=======================

Since there are many forms of a public or private keys supported by
GnuTLS such as X.509, OpenPGP, or PKCS #11 it is desirable to allow
common operations on them. For these reasons the abstract
`gnutls_privkey_t' and `gnutls_pubkey_t' were introduced in
`gnutls/abstract.h' header. Those types are initialized using a
specific type of key and then can be used to perform operations in an
abstract way. For example in order for someone to sign an X.509
certificate with a key that resides in a smart he has to follow the
steps below:


#inlude <gnutls/abstract.h>
#inlude <gnutls/pkcs11.h>

void sign_cert( gnutls_x509_crt_t to_be_signed)
{
gnutls_pkcs11_privkey_t ca_key;
gnutls_x509_crt_t ca_cert;
gnutls_privkey_t abs_key;

	/* load the PKCS #11 key and certificates */
	gnutls_pkcs11_privkey_init(&ca_key);
	gnutls_pkcs11_privkey_import_url(ca_key, key_url);

	gnutls_x509_crt_init(&ca_cert);
	gnutls_x509_crt_import_pkcs11_url(&ca_cert, cert_url);

	/* initialize the abstract key */
	gnutls_privkey_init(&abs_key);
	gnutls_privkey_import_pkcs11(abs_key, ca_key);

	/* sign the certificate to be signed */
	gnutls_x509_crt_privkey_sign(to_be_signed, ca_cert, ca_key, GNUTLS_DIG_SHA1, 0);
}


File: gnutls.info,  Node: Digital signatures,  Prev: Abstract data types,  Up: More on certificate authentication

5.5 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 euros 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.5.1 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.


File: gnutls.info,  Node: How to use TLS in application protocols,  Next: How to use GnuTLS in applications,  Prev: More on certificate authentication,  Up: Top

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.

* Menu:

* Separate ports::
* Upward negotiation::


File: gnutls.info,  Node: Separate ports,  Next: Upward negotiation,  Up: How to use TLS in application protocols

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


File: gnutls.info,  Node: Upward negotiation,  Prev: Separate ports,  Up: How to use TLS in application protocols

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


File: gnutls.info,  Node: How to use GnuTLS in applications,  Next: Included programs,  Prev: How to use TLS in application protocols,  Up: Top

7 How To Use GnuTLS in Applications
***********************************

* Menu:

* Preparation::
* Multi-threaded applications::
* Client examples::
* Server examples::
* Miscellaneous examples::
* Parameter generation::
* Keying Material Exporters::
* Channel Bindings::
* Compatibility with the OpenSSL library::


File: gnutls.info,  Node: Preparation,  Next: Multi-threaded applications,  Up: 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.

* Menu:

* Headers::
* Initialization::
* Version check::
* Debugging::
* Building the source::


File: gnutls.info,  Node: Headers,  Next: Initialization,  Up: Preparation

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.


File: gnutls.info,  Node: Initialization,  Next: Version check,  Prev: Headers,  Up: Preparation

7.1.2 Initialization
--------------------

GnuTLS must be initialized before it can be used.  The library is
initialized by calling *Note gnutls_global_init::.  The resources
allocated by the initialization process can be released if the
application no longer has a need to call GnuTLS functions, this is done
by calling *Note gnutls_global_deinit::.

The extra functionality of the GnuTLS-extra library is available after
calling *Note gnutls_global_init_extra::.

In order to take advantage of the internationalisation features in
GnuTLS, such as translated error messages, the application must set the
current locale using `setlocale' before initializing GnuTLS.


File: gnutls.info,  Node: Version check,  Next: Debugging,  Prev: Initialization,  Up: Preparation

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


File: gnutls.info,  Node: Debugging,  Next: Building the source,  Prev: Version check,  Up: Preparation

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


File: gnutls.info,  Node: Building the source,  Prev: Debugging,  Up: Preparation

7.1.5 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, the library uses the
external package `pkg-config' that knows 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 `pkg-config gnutls'.  The following example shows how it can
be used at the command line:

     gcc -c foo.c `pkg-config gnutls --cflags`

Adding the output of `pkg-config gnutls --cflags' to the compilers
command line will ensure that the compiler can find the
`gnutls/gnutls.h' 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
`pkg-config gnutls' can be used.  For convenience, this option also
outputs all other options that are required to link the program with
the libarary (for instance, the `-ltasn1' option).  The example shows
how to link `foo.o' with the library to a program `foo'.

     gcc -o foo foo.o `pkg-config gnutls --libs`

Of course you can also combine both examples to a single command by
specifying both options to `pkg-config':

     gcc -o foo foo.c `pkg-config gnutls --cflags --libs`


File: gnutls.info,  Node: Multi-threaded applications,  Next: Client examples,  Prev: Preparation,  Up: How to use GnuTLS in applications

7.2 Multi-Threaded Applications
===============================

Although the GnuTLS library is thread safe by design, some parts of the
cryptographic backend, such as the random generator, are not.
Applications can either call *Note gnutls_global_init:: and use the
default operating system provided locks (i.e. `pthreads' on GNU/Linux),
or specify manualy the locking system using the function *Note
gnutls_global_set_mutex:: before calling *Note gnutls_global_init::.
Setting manually mutexes is recommended only to applications that have
full control of the underlying libraries. If this is not the case, the
use of the operating system defaults is recommended.

There are helper macros to help you properly initialize the libraries.
Examples are shown below.

   * POSIX threads in GNU/Linux
          #include <gnutls.h>
          #include <errno.h>
          #include <pthread.h>

          int main()
          {
             gnutls_global_init();
          }

   * Other thread packages

          int main()
          {
             gnutls_global_mutex_set (mutex_init, mutex_deinit, mutex_lock, mutex_unlock);
             gnutls_global_init();
          }


File: gnutls.info,  Node: Client examples,  Next: Server examples,  Prev: Multi-threaded applications,  Up: How to use GnuTLS in applications

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.

* Menu:

* Simple client example with anonymous authentication::
* Simple client example with X.509 certificate support::
* Obtaining session information::
* Verifying peer's certificate::
* Using a callback to select the certificate to use::
* Client using a PKCS #11 token with TLS::
* Client with Resume capability example::
* Simple client example with SRP authentication::
* Simple client example in C++::
* Helper function for TCP connections::


File: gnutls.info,  Node: Simple client example with anonymous authentication,  Next: Simple client example with X.509 certificate support,  Up: Client examples

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.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <gnutls/gnutls.h>

/* A very basic TLS client, with anonymous authentication.
 */

#define MAX_BUF 1024
#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;
}


File: gnutls.info,  Node: Simple client example with X.509 certificate support,  Next: Obtaining session information,  Prev: Simple client example with anonymous authentication,  Up: Client examples

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.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <gnutls/gnutls.h>

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


File: gnutls.info,  Node: Obtaining session information,  Next: Verifying peer's certificate,  Prev: Simple client example with X.509 certificate support,  Up: Client examples

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

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "examples.h"

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


#ifdef ENABLE_SRP
    case GNUTLS_CRD_SRP:
      printf ("- SRP session with username %s\n",
              gnutls_srp_server_get_username (session));
      break;
#endif

    case GNUTLS_CRD_PSK:
      /* This returns NULL in server side.
       */
      if (gnutls_psk_client_get_hint (session) != NULL)
        printf ("- PSK authentication. PSK hint '%s'\n",
                gnutls_psk_client_get_hint (session));
      /* This returns NULL in client side.
       */
      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;
}


File: gnutls.info,  Node: Verifying peer's certificate,  Next: Using a callback to select the certificate to use,  Prev: Obtaining session information,  Up: Client examples

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.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include "examples.h"

/* A very basic TLS client, with X.509 authentication and server certificate
 * verification.
 */

#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);

/* This function will try to verify the peer's certificate, and
 * also check if the hostname matches, and the activation, expiration dates.
 */
static int
verify_certificate_callback (gnutls_session_t session)
{
  unsigned int status;
  const gnutls_datum_t *cert_list;
  unsigned int cert_list_size;
  int ret;
  gnutls_x509_crt_t cert;
  const char *hostname;

  /* read hostname */
  hostname = gnutls_session_get_ptr (session);

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

  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");

  if (status & GNUTLS_CERT_EXPIRED)
    printf ("The certificate has expired\n");

  if (status & GNUTLS_CERT_NOT_ACTIVATED)
    printf ("The certificate is not yet activated\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 GNUTLS_E_CERTIFICATE_ERROR;

  if (gnutls_x509_crt_init (&cert) < 0)
    {
      printf ("error in initialization\n");
      return GNUTLS_E_CERTIFICATE_ERROR;
    }

  cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
  if (cert_list == NULL)
    {
      printf ("No certificate was found!\n");
      return GNUTLS_E_CERTIFICATE_ERROR;
    }

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


  if (!gnutls_x509_crt_check_hostname (cert, hostname))
    {
      printf ("The certificate's owner does not match hostname '%s'\n",
              hostname);
      return GNUTLS_E_CERTIFICATE_ERROR;
    }

  gnutls_x509_crt_deinit (cert);

  /* notify gnutls to continue handshake normally */
  return 0;
}


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);
  gnutls_certificate_set_verify_function (xcred, verify_certificate_callback);
  gnutls_certificate_set_verify_flags (xcred,
                                       GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);

  /* Initialize TLS session
   */
  gnutls_init (&session, GNUTLS_CLIENT);

  gnutls_session_set_ptr (session, (void *) "my_host_name");

  /* 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;
}
 Another example is listed below which provides more detailed
verification output, for applications that need it.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "examples.h"

/* 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;
  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");
      if (output & GNUTLS_CERT_NOT_ACTIVATED)
        fprintf (stderr, ": not yet activated\n");
      if (output & GNUTLS_CERT_EXPIRED)
        fprintf (stderr, ": expired\n");

      fprintf (stderr, "\n");
    }
  else
    fprintf (stderr, "Trusted\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;
  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");
      if (output & GNUTLS_CERT_NOT_ACTIVATED)
        fprintf (stderr, ": Not yet activated\n");
      if (output & GNUTLS_CERT_EXPIRED)
        fprintf (stderr, ": Expired\n");
      fprintf (stderr, "\n");
    }
  else
    fprintf (stderr, "Trusted\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");
    }
}


File: gnutls.info,  Node: Using a callback to select the certificate to use,  Next: Client using a PKCS #11 token with TLS,  Prev: Verifying peer's certificate,  Up: Client examples

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.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

/* 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_retr2_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_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_retr2_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)
    {
      /* check if the certificate we are sending is signed
       * with an algorithm that the server accepts */
      gnutls_sign_algorithm_t cert_algo, req_algo;
      int i, match = 0;

      ret = gnutls_x509_crt_get_signature_algorithm (crt);
      if (ret < 0)
        {
          /* error reading signature algorithm
           */
          return -1;
        }
      cert_algo = ret;

      i = 0;
      do
        {
          ret = gnutls_sign_algorithm_get_requested (session, i, &req_algo);
          if (ret >= 0 && cert_algo == req_algo)
            {
              match = 1;
              break;
            }

          /* server has not requested anything specific */
          if (i == 0 && ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
            {
              match = 1;
              break;
            }
          i++;
        }
      while (ret >= 0);

      if (match == 0)
        {
          printf
            ("- Could not find a suitable certificate to send to server\n");
          return -1;
        }

      st->cert_type = type;
      st->ncerts = 1;

      st->cert.x509 = &crt;
      st->key.x509 = key;
      st->key_type = GNUTLS_PRIVKEY_X509;

      st->deinit_all = 0;
    }
  else
    {
      return -1;
    }

  return 0;

}


File: gnutls.info,  Node: Client using a PKCS #11 token with TLS,  Next: Client with Resume capability example,  Prev: Using a callback to select the certificate to use,  Up: Client examples

7.3.6 Using a PKCS #11 token with TLS
-------------------------------------

This example will demonstrate how to load keys and certificates from a
PKCS #11 token, and use it with a TLS connection.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <getpass.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/pkcs11.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

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

#define MAX_BUF 1024
#define MSG "GET / HTTP/1.0\r\n\r\n"
#define MIN(x,y) (((x)<(y))?(x):(y))

#define CAFILE "ca.pem"
#define KEY_URL "pkcs11:manufacturer=SomeManufacturer;object=Private%20Key" \
  ";objecttype=private;id=db:5b:3e:b5:72:33"
#define CERT_URL "pkcs11:manufacturer=SomeManufacturer;object=Certificate;" \
  "objecttype=cert;id=db:5b:3e:b5:72:33"

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_retr2_st * st);

gnutls_x509_crt_t crt;
gnutls_pkcs11_privkey_t key;

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

  gnutls_x509_crt_init (&crt);

  ret = gnutls_x509_crt_import_pkcs11_url (crt, CERT_URL, 0);

  /* some tokens require login to read data */
  if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
    ret = gnutls_x509_crt_import_pkcs11_url (crt, CERT_URL,
                                             GNUTLS_PKCS11_OBJ_FLAG_LOGIN);

  if (ret < 0)
    {
      fprintf (stderr, "*** Error loading key file: %s\n",
               gnutls_strerror (ret));
      exit (1);
    }

  gnutls_pkcs11_privkey_init (&key);

  ret = gnutls_pkcs11_privkey_import_url (key, KEY_URL, 0);
  if (ret < 0)
    {
      fprintf (stderr, "*** Error loading key file: %s\n",
               gnutls_strerror (ret));
      exit (1);
    }

}

static int
pin_callback (void *user, int attempt, const char *token_url,
              const char *token_label, unsigned int flags, char *pin,
              size_t pin_max)
{
  const char *password;
  int len;

  printf ("PIN required for token '%s' with URL '%s'\n", token_label,
          token_url);
  if (flags & GNUTLS_PKCS11_PIN_FINAL_TRY)
    printf ("*** This is the final try before locking!\n");
  if (flags & GNUTLS_PKCS11_PIN_COUNT_LOW)
    printf ("*** Only few tries left before locking!\n");

  password = getpass ("Enter pin: ");
  if (password == NULL || password[0] == 0)
    {
      fprintf (stderr, "No password given\n");
      exit (1);
    }

  len = MIN (pin_max, strlen (password));
  memcpy (pin, password, len);
  pin[len] = 0;

  return 0;
}

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 ();
  /* PKCS11 private key operations might require PIN.
   * Register a callback.
   */
  gnutls_pkcs11_set_pin_function (pin_callback, NULL);

  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_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_retr2_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)
    {
      /* check if the certificate we are sending is signed
       * with an algorithm that the server accepts */
      gnutls_sign_algorithm_t cert_algo, req_algo;
      int i, match = 0;

      ret = gnutls_x509_crt_get_signature_algorithm (crt);
      if (ret < 0)
        {
          /* error reading signature algorithm
           */
          return -1;
        }
      cert_algo = ret;

      i = 0;
      do
        {
          ret = gnutls_sign_algorithm_get_requested (session, i, &req_algo);
          if (ret >= 0 && cert_algo == req_algo)
            {
              match = 1;
              break;
            }

          /* server has not requested anything specific */
          if (i == 0 && ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
            {
              match = 1;
              break;
            }
          i++;
        }
      while (ret >= 0);

      if (match == 0)
        {
          printf
            ("- Could not find a suitable certificate to send to server\n");
          return -1;
        }

      st->cert_type = type;
      st->ncerts = 1;

      st->cert.x509 = &crt;
      st->key.pkcs11 = key;
      st->key_type = GNUTLS_PRIVKEY_PKCS11;

      st->deinit_all = 0;
    }
  else
    {
      return -1;
    }

  return 0;

}


File: gnutls.info,  Node: Client with Resume capability example,  Next: Simple client example with SRP authentication,  Prev: Client using a PKCS #11 token with TLS,  Up: Client examples

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

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

/* 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 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 = NULL;
  size_t session_data_size = 0;

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


File: gnutls.info,  Node: Simple client example with SRP authentication,  Next: Simple client example in C++,  Prev: Client with Resume capability example,  Up: Client examples

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

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gnutls/gnutls.h>
#include <gnutls/extra.h>

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


File: gnutls.info,  Node: Simple client example in C++,  Next: Helper function for TCP connections,  Prev: Simple client example with SRP authentication,  Up: Client examples

7.3.9 Simple Client Example using the C++ API
---------------------------------------------

The following client is a simple example of a client client utilizing
the GnuTLS C++ API.

#include <iostream>
#include <stdexcept>
#include <gnutls/gnutls.h>
#include <gnutls/gnutlsxx.h>
#include <cstring> /* for strlen */

/* A very basic TLS client, with anonymous authentication.
 * written by Eduardo Villanueva Che.
 */

#define MAX_BUF 1024
#define SA struct sockaddr

#define CAFILE "ca.pem"
#define MSG "GET / HTTP/1.0\r\n\r\n"

extern "C"
{
    int tcp_connect(void);
    void tcp_close(int sd);
}


int main(void)
{
    int sd = -1;
    gnutls_global_init();

    try
    {

        /* Allow connections to servers that have OpenPGP keys as well.
         */
        gnutls::client_session session;

        /* X509 stuff */
        gnutls::certificate_credentials credentials;


        /* sets the trusted cas file
         */
        credentials.set_x509_trust_file(CAFILE, GNUTLS_X509_FMT_PEM);
        /* put the x509 credentials to the current session
         */
        session.set_credentials(credentials);

        /* Use default priorities */
        session.set_priority ("NORMAL", NULL);

        /* connect to the peer
         */
        sd = tcp_connect();
        session.set_transport_ptr((gnutls_transport_ptr_t) sd);

        /* Perform the TLS handshake
         */
        int ret = session.handshake();
        if (ret < 0)
        {
            throw std::runtime_error("Handshake failed");
        }
        else
        {
            std::cout << "- Handshake was completed" << std::endl;
        }

        session.send(MSG, strlen(MSG));
        char buffer[MAX_BUF + 1];
        ret = session.recv(buffer, MAX_BUF);
        if (ret == 0)
        {
            throw std::runtime_error("Peer has closed the TLS connection");
        }
        else if (ret < 0)
        {
            throw std::runtime_error(gnutls_strerror(ret));
        }

        std::cout << "- Received " << ret << " bytes:" << std::endl;
        std::cout.write(buffer, ret);
        std::cout << std::endl;

        session.bye(GNUTLS_SHUT_RDWR);
    }
    catch (std::exception &ex)
    {
        std::cerr << "Exception caught: " << ex.what() << std::endl;
    }

    if (sd != -1)
        tcp_close(sd);

    gnutls_global_deinit();

    return 0;
}


File: gnutls.info,  Node: Helper function for TCP connections,  Prev: Simple client example in C++,  Up: Client examples

7.3.10 Helper Function for TCP Connections
------------------------------------------

This helper function abstracts away TCP connection handling from the
other examples.  It is required to build some examples.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#define SA struct sockaddr

/* tcp.c */
int tcp_connect (void);
void tcp_close (int sd);

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


File: gnutls.info,  Node: Server examples,  Next: Miscellaneous examples,  Prev: Client examples,  Up: How to use GnuTLS in applications

7.4 Server Examples
===================

This section contains examples of TLS and SSL servers, using GnuTLS.

* Menu:

* Echo Server with X.509 authentication::
* Echo Server with OpenPGP authentication::
* Echo Server with SRP authentication::
* Echo Server with anonymous authentication::


File: gnutls.info,  Node: Echo Server with X.509 authentication,  Next: Echo Server with OpenPGP authentication,  Up: Server examples

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.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

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

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

  /* 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, (void *) &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); */

      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;

}


File: gnutls.info,  Node: Echo Server with OpenPGP authentication,  Next: Echo Server with SRP authentication,  Prev: Echo Server with X.509 authentication,  Up: Server examples

7.4.2 Echo Server with OpenPGP Authentication
---------------------------------------------

The following example is an echo server which supports OpenPGP key
authentication. You can easily combine this functionality --that is
have a server that supports both X.509 and OpenPGP certificates-- but
we separated them to keep these examples as simple as possible.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <gnutls/gnutls.h>
#include <gnutls/openpgp.h>

#define KEYFILE "secret.asc"
#define CERTFILE "public.asc"
#define RINGFILE "ring.gpg"

/* This is a sample TLS 1.0-OpenPGP echo server.
 */


#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 cred;
gnutls_dh_params_t dh_params;

static int
generate_dh_params (void)
{

  /* Generate Diffie-Hellman parameters - for use with DHE
   * kx algorithms. These should be discarded and regenerated
   * once a day, once a week or once a month. Depending on the
   * security requirements.
   */
  gnutls_dh_params_init (&dh_params);
  gnutls_dh_params_generate2 (dh_params, DH_BITS);

  return 0;
}

static gnutls_session_t
initialize_tls_session (void)
{
  gnutls_session_t session;

  gnutls_init (&session, GNUTLS_SERVER);

  gnutls_priority_set_direct (session, "NORMAL", NULL);

  /* request client certificate if any.
   */
  gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUEST);

  gnutls_dh_set_prime_bits (session, DH_BITS);

  return session;
}

int
main (void)
{
  int err, listen_sd;
  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");

  /* this must be called once in the program
   */
  gnutls_global_init ();

  gnutls_certificate_allocate_credentials (&cred);
  gnutls_certificate_set_openpgp_keyring_file (cred, RINGFILE,
                                               GNUTLS_OPENPGP_FMT_BASE64);

  gnutls_certificate_set_openpgp_key_file (cred, CERTFILE, KEYFILE,
                                           GNUTLS_OPENPGP_FMT_BASE64);

  generate_dh_params ();

  gnutls_certificate_set_dh_params (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, (void *) &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");

      /* see the Getting peer's information example */
      /* print_info(session); */

      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 (cred);

  gnutls_global_deinit ();

  return 0;

}


File: gnutls.info,  Node: Echo Server with SRP authentication,  Next: Echo Server with anonymous authentication,  Prev: Echo Server with OpenPGP authentication,  Up: Server examples

7.4.3 Echo Server with SRP Authentication
-----------------------------------------

This is a server which supports SRP authentication. It is also possible
to combine this functionality with a certificate server. Here it is
separate for simplicity.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <gnutls/gnutls.h>
#include <gnutls/extra.h>

#define SRP_PASSWD "tpasswd"
#define SRP_PASSWD_CONF "tpasswd.conf"

#define KEYFILE "key.pem"
#define CERTFILE "cert.pem"
#define CAFILE "ca.pem"

/* This is a sample TLS-SRP echo server.
 */

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

/* These are global */
gnutls_srp_server_credentials_t srp_cred;
gnutls_certificate_credentials_t cert_cred;

static gnutls_session_t
initialize_tls_session (void)
{
  gnutls_session_t session;

  gnutls_init (&session, GNUTLS_SERVER);

  gnutls_priority_set_direct (session, "NORMAL:+SRP:+SRP-DSS:+SRP-RSA", NULL);

  gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred);
  /* for the certificate authenticated ciphersuites.
   */
  gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, cert_cred);

  /* request client certificate if any.
   */
  gnutls_certificate_server_set_request (session, GNUTLS_CERT_IGNORE);

  return session;
}

int
main (void)
{
  int err, listen_sd;
  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");

  /* these must be called once in the program
   */
  gnutls_global_init ();
  gnutls_global_init_extra ();  /* for SRP */

  /* SRP_PASSWD a password file (created with the included srptool utility)
   */
  gnutls_srp_allocate_server_credentials (&srp_cred);
  gnutls_srp_set_server_credentials_file (srp_cred, SRP_PASSWD,
                                          SRP_PASSWD_CONF);

  gnutls_certificate_allocate_credentials (&cert_cred);
  gnutls_certificate_set_x509_trust_file (cert_cred, CAFILE,
                                          GNUTLS_X509_FMT_PEM);
  gnutls_certificate_set_x509_key_file (cert_cred, CERTFILE, KEYFILE,
                                        GNUTLS_X509_FMT_PEM);

  /* TCP 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, (void *) &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); */

      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_srp_free_server_credentials (srp_cred);
  gnutls_certificate_free_credentials (cert_cred);

  gnutls_global_deinit ();

  return 0;

}


File: gnutls.info,  Node: Echo Server with anonymous authentication,  Prev: Echo Server with SRP authentication,  Up: Server examples

7.4.4 Echo Server with Anonymous Authentication
-----------------------------------------------

This example server support anonymous authentication, and could be used
to serve the example client for anonymous authentication.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

/* This is a sample TLS 1.0 echo server, for anonymous authentication only.
 */


#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_anon_server_credentials_t anoncred;

static gnutls_session_t
initialize_tls_session (void)
{
  gnutls_session_t session;

  gnutls_init (&session, GNUTLS_SERVER);

  gnutls_priority_set_direct (session, "NORMAL:+ANON-DH", NULL);

  gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred);

  gnutls_dh_set_prime_bits (session, DH_BITS);

  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. These should be discarded and regenerated
   * once a day, once a week or once a month. Depending on the
   * security requirements.
   */
  gnutls_dh_params_init (&dh_params);
  gnutls_dh_params_generate2 (dh_params, DH_BITS);

  return 0;
}

int
main (void)
{
  int err, listen_sd;
  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;

  /* this must be called once in the program
   */
  gnutls_global_init ();

  gnutls_anon_allocate_server_credentials (&anoncred);

  generate_dh_params ();

  gnutls_anon_set_server_dh_params (anoncred, 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, (void *) &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); */

      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_anon_free_server_credentials (anoncred);

  gnutls_global_deinit ();

  return 0;

}


File: gnutls.info,  Node: Miscellaneous examples,  Next: Parameter generation,  Prev: Server examples,  Up: How to use GnuTLS in applications

7.5 Miscellaneous Examples
==========================

* Menu:

* Checking for an alert::
* X.509 certificate parsing example::
* Certificate request generation::
* PKCS #12 structure generation::


File: gnutls.info,  Node: Checking for an alert,  Next: X.509 certificate parsing example,  Up: Miscellaneous examples

7.5.1 Checking for an Alert
---------------------------

This is a function that checks if an alert has been received in the
current session.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "examples.h"

/* This function will check whether the given return code from
 * a gnutls function (recv/send), is an alert, and will print
 * that alert.
 */
void
check_alert (gnutls_session_t session, int ret)
{
  int last_alert;

  if (ret == GNUTLS_E_WARNING_ALERT_RECEIVED
      || ret == GNUTLS_E_FATAL_ALERT_RECEIVED)
    {
      last_alert = gnutls_alert_get (session);

      /* The check for renegotiation is only useful if we are
       * a server, and we had requested a rehandshake.
       */
      if (last_alert == GNUTLS_A_NO_RENEGOTIATION &&
          ret == GNUTLS_E_WARNING_ALERT_RECEIVED)
        printf ("* Received NO_RENEGOTIATION alert. "
                "Client Does not support renegotiation.\n");
      else
        printf ("* Received alert '%d': %s.\n", last_alert,
                gnutls_alert_get_name (last_alert));
    }
}


File: gnutls.info,  Node: X.509 certificate parsing example,  Next: Certificate request generation,  Prev: Checking for an alert,  Up: Miscellaneous examples

7.5.2 X.509 Certificate Parsing Example
---------------------------------------

To demonstrate the X.509 parsing capabilities an example program is
listed below.  That program reads the peer's certificate, and prints
information about it.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "examples.h"

static const char *
bin2hex (const void *bin, size_t bin_size)
{
  static char printable[110];
  const unsigned char *_bin = bin;
  char *print;
  size_t i;

  if (bin_size > 50)
    bin_size = 50;

  print = printable;
  for (i = 0; i < bin_size; i++)
    {
      sprintf (print, "%.2x ", _bin[i]);
      print += 2;
    }

  return printable;
}

/* This function will print information about this session's peer
 * certificate.
 */
void
print_x509_certificate_info (gnutls_session_t session)
{
  char serial[40];
  char dn[256];
  size_t size;
  unsigned int algo, bits;
  time_t expiration_time, activation_time;
  const gnutls_datum_t *cert_list;
  unsigned int cert_list_size = 0;
  gnutls_x509_crt_t cert;
  gnutls_datum_t cinfo;

  /* This function only works for X.509 certificates.
   */
  if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509)
    return;

  cert_list = gnutls_certificate_get_peers (session, &cert_list_size);

  printf ("Peer provided %d certificates.\n", cert_list_size);

  if (cert_list_size > 0)
    {
      int ret;

      /* we only print information about the first certificate.
       */
      gnutls_x509_crt_init (&cert);

      gnutls_x509_crt_import (cert, &cert_list[0], GNUTLS_X509_FMT_DER);

      printf ("Certificate info:\n");

      /* This is the preferred way of printing short information about
         a certificate. */

      ret = gnutls_x509_crt_print (cert, GNUTLS_CRT_PRINT_ONELINE, &cinfo);
      if (ret == 0)
        {
          printf ("\t%s\n", cinfo.data);
          gnutls_free (cinfo.data);
        }

      /* If you want to extract fields manually for some other reason,
         below are popular example calls. */

      expiration_time = gnutls_x509_crt_get_expiration_time (cert);
      activation_time = gnutls_x509_crt_get_activation_time (cert);

      printf ("\tCertificate is valid since: %s", ctime (&activation_time));
      printf ("\tCertificate expires: %s", ctime (&expiration_time));

      /* Print the serial number of the certificate.
       */
      size = sizeof (serial);
      gnutls_x509_crt_get_serial (cert, serial, &size);

      printf ("\tCertificate serial number: %s\n", bin2hex (serial, size));

      /* Extract some of the public key algorithm's parameters
       */
      algo = gnutls_x509_crt_get_pk_algorithm (cert, &bits);

      printf ("Certificate public key: %s",
              gnutls_pk_algorithm_get_name (algo));

      /* Print the version of the X.509
       * certificate.
       */
      printf ("\tCertificate version: #%d\n",
              gnutls_x509_crt_get_version (cert));

      size = sizeof (dn);
      gnutls_x509_crt_get_dn (cert, dn, &size);
      printf ("\tDN: %s\n", dn);

      size = sizeof (dn);
      gnutls_x509_crt_get_issuer_dn (cert, dn, &size);
      printf ("\tIssuer's DN: %s\n", dn);

      gnutls_x509_crt_deinit (cert);

    }
}


File: gnutls.info,  Node: Certificate request generation,  Next: PKCS #12 structure generation,  Prev: X.509 certificate parsing example,  Up: Miscellaneous examples

7.5.3 Certificate Request Generation
------------------------------------

The following example is about generating a certificate request, and a
private key. A certificate request can be later be processed by a CA,
which should return a signed certificate.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/abstract.h>
#include <time.h>

/* This example will generate a private key and a certificate
 * request.
 */

int
main (void)
{
  gnutls_x509_crq_t crq;
  gnutls_x509_privkey_t key;
  gnutls_privkey_t pkey; /* object used for signing */
  unsigned char buffer[10 * 1024];
  size_t buffer_size = sizeof (buffer);
  unsigned int bits;

  gnutls_global_init ();

  /* Initialize an empty certificate request, and
   * an empty private key.
   */
  gnutls_x509_crq_init (&crq);

  gnutls_x509_privkey_init (&key);
  gnutls_privkey_init (&pkey);

  /* Generate an RSA key of moderate security.
   */
  bits = gnutls_sec_param_to_pk_bits (GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_NORMAL);
  gnutls_x509_privkey_generate (key, GNUTLS_PK_RSA, bits, 0);

  /* Add stuff to the distinguished name
   */
  gnutls_x509_crq_set_dn_by_oid (crq, GNUTLS_OID_X520_COUNTRY_NAME,
                                 0, "GR", 2);

  gnutls_x509_crq_set_dn_by_oid (crq, GNUTLS_OID_X520_COMMON_NAME,
                                 0, "Nikos", strlen ("Nikos"));

  /* Set the request version.
   */
  gnutls_x509_crq_set_version (crq, 1);

  /* Set a challenge password.
   */
  gnutls_x509_crq_set_challenge_password (crq, "something to remember here");

  /* Associate the request with the private key
   */
  gnutls_x509_crq_set_key (crq, key);

  /* Self sign the certificate request.
   */
  gnutls_privkey_import_x509( pkey, key, 0);
  gnutls_x509_crq_privkey_sign (crq, pkey, GNUTLS_DIG_SHA1, 0);

  /* Export the PEM encoded certificate request, and
   * display it.
   */
  gnutls_x509_crq_export (crq, GNUTLS_X509_FMT_PEM, buffer, &buffer_size);

  printf ("Certificate Request: \n%s", buffer);


  /* Export the PEM encoded private key, and
   * display it.
   */
  buffer_size = sizeof (buffer);
  gnutls_x509_privkey_export (key, GNUTLS_X509_FMT_PEM, buffer, &buffer_size);

  printf ("\n\nPrivate key: \n%s", buffer);

  gnutls_x509_crq_deinit (crq);
  gnutls_x509_privkey_deinit (key);

  return 0;

}


File: gnutls.info,  Node: PKCS #12 structure generation,  Prev: Certificate request generation,  Up: Miscellaneous examples

7.5.4 PKCS #12 Structure Generation
-----------------------------------

The following example is about generating a PKCS #12 structure.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "examples.h"

#define OUTFILE "out.p12"

/* This function will write a pkcs12 structure into a file.
 * cert: is a DER encoded certificate
 * pkcs8_key: is a PKCS #8 encrypted key (note that this must be
 *  encrypted using a PKCS #12 cipher, or some browsers will crash)
 * password: is the password used to encrypt the PKCS #12 packet.
 */
int
write_pkcs12 (const gnutls_datum_t * cert,
              const gnutls_datum_t * pkcs8_key, const char *password)
{
  gnutls_pkcs12_t pkcs12;
  int ret, bag_index;
  gnutls_pkcs12_bag_t bag, key_bag;
  char pkcs12_struct[10 * 1024];
  size_t pkcs12_struct_size;
  FILE *fd;

  /* A good idea might be to use gnutls_x509_privkey_get_key_id()
   * to obtain a unique ID.
   */
  gnutls_datum_t key_id = { (char *) "\x00\x00\x07", 3 };

  gnutls_global_init ();

  /* Firstly we create two helper bags, which hold the certificate,
   * and the (encrypted) key.
   */

  gnutls_pkcs12_bag_init (&bag);
  gnutls_pkcs12_bag_init (&key_bag);

  ret = gnutls_pkcs12_bag_set_data (bag, GNUTLS_BAG_CERTIFICATE, cert);
  if (ret < 0)
    {
      fprintf (stderr, "ret: %s\n", gnutls_strerror (ret));
      return 1;
    }

  /* ret now holds the bag's index.
   */
  bag_index = ret;

  /* Associate a friendly name with the given certificate. Used
   * by browsers.
   */
  gnutls_pkcs12_bag_set_friendly_name (bag, bag_index, "My name");

  /* Associate the certificate with the key using a unique key
   * ID.
   */
  gnutls_pkcs12_bag_set_key_id (bag, bag_index, &key_id);

  /* use weak encryption for the certificate.
   */
  gnutls_pkcs12_bag_encrypt (bag, password, GNUTLS_PKCS_USE_PKCS12_RC2_40);

  /* Now the key.
   */

  ret = gnutls_pkcs12_bag_set_data (key_bag,
                                    GNUTLS_BAG_PKCS8_ENCRYPTED_KEY,
                                    pkcs8_key);
  if (ret < 0)
    {
      fprintf (stderr, "ret: %s\n", gnutls_strerror (ret));
      return 1;
    }

  /* Note that since the PKCS #8 key is already encrypted we don't
   * bother encrypting that bag.
   */
  bag_index = ret;

  gnutls_pkcs12_bag_set_friendly_name (key_bag, bag_index, "My name");

  gnutls_pkcs12_bag_set_key_id (key_bag, bag_index, &key_id);


  /* The bags were filled. Now create the PKCS #12 structure.
   */
  gnutls_pkcs12_init (&pkcs12);

  /* Insert the two bags in the PKCS #12 structure.
   */

  gnutls_pkcs12_set_bag (pkcs12, bag);
  gnutls_pkcs12_set_bag (pkcs12, key_bag);


  /* Generate a message authentication code for the PKCS #12
   * structure.
   */
  gnutls_pkcs12_generate_mac (pkcs12, password);

  pkcs12_struct_size = sizeof (pkcs12_struct);
  ret =
    gnutls_pkcs12_export (pkcs12, GNUTLS_X509_FMT_DER, pkcs12_struct,
                          &pkcs12_struct_size);
  if (ret < 0)
    {
      fprintf (stderr, "ret: %s\n", gnutls_strerror (ret));
      return 1;
    }

  fd = fopen (OUTFILE, "w");
  if (fd == NULL)
    {
      fprintf (stderr, "cannot open file\n");
      return 1;
    }
  fwrite (pkcs12_struct, 1, pkcs12_struct_size, fd);
  fclose (fd);

  gnutls_pkcs12_bag_deinit (bag);
  gnutls_pkcs12_bag_deinit (key_bag);
  gnutls_pkcs12_deinit (pkcs12);

  return 0;
}


File: gnutls.info,  Node: Parameter generation,  Next: Keying Material Exporters,  Prev: Miscellaneous examples,  Up: How to use GnuTLS in applications

7.6 Parameter generation
========================

Several TLS ciphersuites require additional parameters that need to be
generated or provided by the application. The Diffie-Hellman based
ciphersuites (ANON-DH or DHE), require the group information to be
provided. This information can be either be generated on the fly using
*Note gnutls_dh_params_generate2:: or imported from some pregenerated
value using *Note gnutls_dh_params_import_pkcs3::.  The parameters can
be used in a session by calling *Note
gnutls_certificate_set_dh_params:: or *Note
gnutls_anon_set_server_dh_params:: for anonymous sessions.

Due to the time-consuming calculations required for the generation of
Diffie-Hellman parameters we suggest against performing generation of
them within an application. The `certtool' tool can be used to generate
or export known safe values that can be stored in code or in a
configuration file to provide the ability to replace. We also recommend
the usage of *Note gnutls_sec_param_to_pk_bits:: to determine the bit
size of the parameters to be generated.

The ciphersuites that involve the RSA-EXPORT key exchange require
additional parameters. Those ciphersuites are rarely used today because
they are by design insecure, thus if you have no requirement for them,
this section should be skipped. The RSA-EXPORT key exchange requires
512-bit RSA keys to be generated. It is recommended those parameters to
be refreshed (regenerated) in short intervals. The following functions
can be used for these parameters.

   * *Note gnutls_rsa_params_generate2::

   * *Note gnutls_certificate_set_rsa_export_params::

   * *Note gnutls_rsa_params_import_pkcs1::

   * *Note gnutls_rsa_params_export_pkcs1::



File: gnutls.info,  Node: Keying Material Exporters,  Next: Channel Bindings,  Prev: Parameter generation,  Up: How to use GnuTLS in applications

7.7 Keying Material Exporters
=============================

The TLS PRF can be used by other protocols to derive data.  The API to
use is *Note gnutls_prf::.  The function needs to be provided with the
label in the parameter `label', and the extra data to mix in the
`extra' parameter.  Depending on whether you want to mix in the client
or server random data first, you can set the `server_random_first'
parameter.

For example, after establishing a TLS session using *Note
gnutls_handshake::, you can invoke the TLS PRF with this call:

     #define MYLABEL "EXPORTER-FOO"
     #define MYCONTEXT "some context data"
     char out[32];
     rc = gnutls_prf (session, strlen (MYLABEL), MYLABEL, 0,
                      strlen (MYCONTEXT), MYCONTEXT, 32, out);

If you don't want to mix in the client/server random, there is a more
low-level TLS PRF interface called *Note gnutls_prf_raw::.


File: gnutls.info,  Node: Channel Bindings,  Next: Compatibility with the OpenSSL library,  Prev: Keying Material Exporters,  Up: How to use GnuTLS in applications

7.8 Channel Bindings
====================

In user authentication protocols (e.g., EAP or SASL mechanisms) it is
useful to have a unique string that identifies the secure channel that
is used, to bind together the user authentication with the secure
channel.  This can protect against man-in-the-middle attacks in some
situations.  The unique strings is a "channel bindings".  For
background and more discussion see [RFC5056] (*note Bibliography::).

You can extract a channel bindings using the *Note
gnutls_session_channel_binding:: function.  Currently only the
`GNUTLS_CB_TLS_UNIQUE' type is supported, which corresponds to the
`tls-unique' channel bindings for TLS defined in [RFC5929] (*note
Bibliography::).

The following example describes how to print the channel binding data.
Note that it must be run after a successful TLS handshake.

     {
       gnutls_datum cb;
       int rc;

       rc = gnutls_session_channel_binding (session,
                                            GNUTLS_CB_TLS_UNIQUE,
                                            &cb);
       if (rc)
         fprintf (stderr, "Channel binding error: %s\n",
                  gnutls_strerror (rc));
       else
         {
           size_t i;
           printf ("- Channel binding 'tls-unique': ");
           for (i = 0; i < cb.size; i++)
             printf ("%02x", cb.data[i]);
           printf ("\n");
         }
     }


File: gnutls.info,  Node: Compatibility with the OpenSSL library,  Prev: Channel Bindings,  Up: How to use GnuTLS in applications

7.9 Compatibility with the OpenSSL Library
==========================================

To ease GnuTLS' integration with existing applications, a compatibility
layer with the widely used OpenSSL library is included in the
`gnutls-openssl' library. This compatibility layer is not complete and
it is not intended to completely reimplement the OpenSSL API with
GnuTLS.  It only provides source-level compatibility. There is
currently no attempt to make it binary-compatible with OpenSSL.

The prototypes for the compatibility functions are in the
`gnutls/openssl.h' header file.

Current limitations imposed by the compatibility layer include:

   * Error handling is not thread safe.



File: gnutls.info,  Node: Included programs,  Next: Function reference,  Prev: How to use GnuTLS in applications,  Up: Top

8 Included Programs
*******************

Included with GnuTLS are also a few command line tools that let you use
the library for common tasks without writing an application.  The
applications are discussed in this chapter.

* Menu:

* Invoking certtool::
* Invoking gnutls-cli::
* Invoking gnutls-cli-debug::
* Invoking gnutls-serv::
* Invoking psktool::
* Invoking srptool::
* Invoking p11tool::


File: gnutls.info,  Node: Invoking certtool,  Next: Invoking gnutls-cli,  Up: Included programs

8.1 Invoking certtool
=====================

This is a program to generate X.509 certificates, certificate requests,
CRLs and private keys.


Certtool help
Usage: certtool [options]
     -s, --generate-self-signed
                              Generate a self-signed certificate.
     -c, --generate-certificate
                              Generate a signed certificate.
     --generate-proxy         Generate a proxy certificate.
     --generate-crl           Generate a CRL.
     -u, --update-certificate
                              Update a signed certificate.
     -p, --generate-privkey   Generate a private key.
     -q, --generate-request   Generate a PKCS #10 certificate
                              request.
     -e, --verify-chain       Verify a PEM encoded certificate chain.
                              The last certificate in the chain must
                              be a self signed one.
     --verify-crl             Verify a CRL.
     --generate-dh-params     Generate PKCS #3 encoded Diffie-Hellman
                              parameters.
     --get-dh-params          Get the included PKCS #3 encoded Diffie
                              Hellman parameters.
     --load-privkey FILE      Private key file to use.
     --load-request FILE      Certificate request file to use.
     --load-certificate FILE
                              Certificate file to use.
     --load-ca-privkey FILE   Certificate authority's private key
                              file to use.
     --load-ca-certificate FILE
                              Certificate authority's certificate
                              file to use.
     --password PASSWORD      Password to use.
     -i, --certificate-info   Print information on a certificate.
     -l, --crl-info           Print information on a CRL.
     --p12-info               Print information on a PKCS #12
                              structure.
     --p7-info                Print information on a PKCS #7
                              structure.
     --smime-to-p7            Convert S/MIME to PKCS #7 structure.
     -k, --key-info           Print information on a private key.
     --fix-key                Regenerate the parameters in a private
                              key.
     --to-p12                 Generate a PKCS #12 structure.
     -8, --pkcs8              Use PKCS #8 format for private keys.
     --dsa                    Use DSA keys.
     --hash STR               Hash algorithm to use for signing
                              (MD5,SHA1,RMD160).
     --export-ciphers         Use weak encryption algorithms.
     --inder                  Use DER format for input certificates
                              and private keys.
     --outder                 Use DER format for output certificates
                              and private keys.
     --bits BITS              specify the number of bits for key
                              generation.
     --outfile FILE           Output file.
     --infile FILE            Input file.
     --template FILE          Template file to use for non
                              interactive operation.
     -d, --debug LEVEL        specify the debug level. Default is 1.
     -h, --help               shows this help text
     -v, --version            shows the program's version

The program can be used interactively or non interactively by
specifying the `--template' command line option. See below for an
example of a template file.

How to use certtool interactively:

   * To generate parameters for Diffie-Hellman key exchange, use the
     command:
          $ certtool --generate-dh-params --outfile dh.pem

   * To generate parameters for the RSA-EXPORT key exchange, use the
     command:
          $ certtool --generate-privkey --bits 512 --outfile rsa.pem


   * To create a self signed certificate, use the command:
          $ certtool --generate-privkey --outfile ca-key.pem
          $ certtool --generate-self-signed --load-privkey ca-key.pem \
             --outfile ca-cert.pem

     Note that a self-signed certificate usually belongs to a
     certificate authority, that signs other certificates.

   * To create a private key (RSA by default), run:

          $ certtool --generate-privkey --outfile key.pem

     To create a DSA private key, run:

          $ certtool --dsa --generate-privkey --outfile key-dsa.pem

   * To generate a certificate using the private key, use the command:

          $ certtool --generate-certificate --load-privkey key.pem \
             --outfile cert.pem --load-ca-certificate ca-cert.pem \
             --load-ca-privkey ca-key.pem

   * To create a certificate request (needed when the certificate is
     issued by another party), run:

          $ certtool --generate-request --load-privkey key.pem \
            --outfile request.pem

   * To generate a certificate using the previous request, use the
     command:

          $ certtool --generate-certificate --load-request request.pem \
             --outfile cert.pem \
             --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem

   * To view the certificate information, use:

          $ certtool --certificate-info --infile cert.pem

   * To generate a PKCS #12 structure using the previous key and
     certificate, use the command:

          $ certtool --load-certificate cert.pem --load-privkey key.pem \
            --to-p12 --outder --outfile key.p12

     Some tools (reportedly web browsers) have problems with that file
     because it does not contain the CA certificate for the certificate.
     To work around that problem in the tool, you can use the
     `--load-ca-certificate' parameter as follows:

          $ certtool --load-ca-certificate ca.pem \
            --load-certificate cert.pem --load-privkey key.pem \
            --to-p12 --outder --outfile key.p12

   * Proxy certificate can be used to delegate your credential to a
     temporary, typically short-lived, certificate.  To create one from
     the previously created certificate, first create a temporary key
     and then generate a proxy certificate for it, using the commands:

          $ certtool --generate-privkey > proxy-key.pem
          $ certtool --generate-proxy --load-ca-privkey key.pem \
            --load-privkey proxy-key.pem --load-certificate cert.pem \
            --outfile proxy-cert.pem

   * To create an empty Certificate Revocation List (CRL) do:

          $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem --load-ca-certificate x509-ca.pem

     To create a CRL that contains some revoked certificates, place the
     certificates in a file and use `--load-certificate' as follows:

          $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem --load-ca-certificate x509-ca.pem --load-certificate revoked-certs.pem

   * To verify a Certificate Revocation List (CRL) do:

          $ certtool --verify-crl --load-ca-certificate x509-ca.pem < crl.pem


Certtool's template file format:

   * Firstly create a file named 'cert.cfg' that contains the
     information about the certificate. An example file is listed below.

   * Then execute:

          $ certtool --generate-certificate cert.pem --load-privkey key.pem  \
             --template cert.cfg \
             --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem


An example certtool template file:

     # X.509 Certificate options
     #
     # DN options

     # The organization of the subject.
     organization = "Koko inc."

     # The organizational unit of the subject.
     unit = "sleeping dept."

     # The locality of the subject.
     # locality =

     # The state of the certificate owner.
     state = "Attiki"

     # The country of the subject. Two letter code.
     country = GR

     # The common name of the certificate owner.
     cn = "Cindy Lauper"

     # A user id of the certificate owner.
     #uid = "clauper"

     # If the supported DN OIDs are not adequate you can set
     # any OID here.
     # For example set the X.520 Title and the X.520 Pseudonym
     # by using OID and string pairs.
     #dn_oid = "2.5.4.12" "Dr." "2.5.4.65" "jackal"

     # This is deprecated and should not be used in new
     # certificates.
     # pkcs9_email = "none@none.org"

     # The serial number of the certificate
     serial = 007

     # In how many days, counting from today, this certificate will expire.
     expiration_days = 700

     # X.509 v3 extensions

     # A dnsname in case of a WWW server.
     #dns_name = "www.none.org"
     #dns_name = "www.morethanone.org"

     # An IP address in case of a server.
     #ip_address = "192.168.1.1"

     # An email in case of a person
     email = "none@none.org"

     # An URL that has CRLs (certificate revocation lists)
     # available. Needed in CA certificates.
     #crl_dist_points = "http://www.getcrl.crl/getcrl/"

     # Whether this is a CA certificate or not
     #ca

     # Whether this certificate will be used for a TLS client
     #tls_www_client

     # Whether this certificate will be used for a TLS server
     #tls_www_server

     # Whether this certificate will be used to sign data (needed
     # in TLS DHE ciphersuites).
     signing_key

     # Whether this certificate will be used to encrypt data (needed
     # in TLS RSA ciphersuites). Note that it is preferred to use different
     # keys for encryption and signing.
     #encryption_key

     # Whether this key will be used to sign other certificates.
     #cert_signing_key

     # Whether this key will be used to sign CRLs.
     #crl_signing_key

     # Whether this key will be used to sign code.
     #code_signing_key

     # Whether this key will be used to sign OCSP data.
     #ocsp_signing_key

     # Whether this key will be used for time stamping.
     #time_stamping_key

     # Whether this key will be used for IPsec IKE operations.
     #ipsec_ike_key


File: gnutls.info,  Node: Invoking gnutls-cli,  Next: Invoking gnutls-cli-debug,  Prev: Invoking certtool,  Up: Included programs

8.2 Invoking gnutls-cli
=======================

Simple client program to set up a TLS connection to some other
computer.  It sets up a TLS connection and forwards data from the
standard input to the secured socket and vice versa.


GnuTLS test client
Usage:  gnutls-cli [options] hostname

     -d, --debug integer      Enable debugging
     -r, --resume             Connect, establish a session. Connect
                              again and resume this session.
     -s, --starttls           Connect, establish a plain session and
                              start TLS when EOF or a SIGALRM is
                              received.
     --crlf                   Send CR LF instead of LF.
     --x509fmtder             Use DER format for certificates to read
                              from.
     -f, --fingerprint        Send the openpgp fingerprint, instead
                              of the key.
     --disable-extensions     Disable all the TLS extensions.
     --print-cert             Print the certificate in PEM format.
     --recordsize integer     The maximum record size to advertize.
     -V, --verbose            More verbose output.
     --ciphers cipher1 cipher2...
                              Ciphers to enable.
     --protocols protocol1 protocol2...
                              Protocols to enable.
     --comp comp1 comp2...    Compression methods to enable.
     --macs mac1 mac2...      MACs to enable.
     --kx kx1 kx2...          Key exchange methods to enable.
     --ctypes certType1 certType2...
                              Certificate types to enable.
     --priority PRIORITY STRING
                              Priorities string.
     --x509cafile FILE        Certificate file to use.
     --x509crlfile FILE       CRL file to use.
     --pgpkeyfile FILE        PGP Key file to use.
     --pgpkeyring FILE        PGP Key ring file to use.
     --pgpcertfile FILE       PGP Public Key (certificate) file to
                              use.
     --pgpsubkey HEX|auto     PGP subkey to use.
     --x509keyfile FILE       X.509 key file to use.
     --x509certfile FILE      X.509 Certificate file to use.
     --srpusername NAME       SRP username to use.
     --srppasswd PASSWD       SRP password to use.
     --pskusername NAME       PSK username to use.
     --pskkey KEY             PSK key (in hex) to use.
     --opaque-prf-input DATA
                              Use Opaque PRF Input DATA.
     -p, --port PORT          The port to connect to.
     --insecure               Don't abort program if server
                              certificate can't be validated.
     -l, --list               Print a list of the supported
                              algorithms and modes.
     -h, --help               prints this help
     -v, --version            prints the program's version number

To connect to a server using PSK authentication, you may use something
like:

     $ gnutls-cli -p 5556 test.gnutls.org --pskusername jas --pskkey 9e32cf7786321a828ef7668f09fb35db --priority NORMAL:+DHE-PSK:+PSK:-RSA:-DHE-RSA -d 4711

* Menu:

* Example client PSK connection::


File: gnutls.info,  Node: Example client PSK connection,  Up: Invoking gnutls-cli

8.2.1 Example client PSK connection
-----------------------------------

If your server only supports the PSK ciphersuite, connecting to it
should be as simple as connecting to the server:

     $ ./gnutls-cli -p 5556 localhost
     Resolving 'localhost'...
     Connecting to '127.0.0.1:5556'...
     - PSK client callback.
     Enter PSK identity: psk_identity
     Enter password:
     - PSK authentication.
     - Version: TLS1.1
     - Key Exchange: PSK
     - Cipher: AES-128-CBC
     - MAC: SHA1
     - Compression: NULL
     - Handshake was completed

     - Simple Client Mode:

If the server supports several cipher suites, you may need to force it
to chose PSK by using a cipher priority parameter such as `--priority
NORMAL:+PSK:-RSA:-DHE-RSA:-DHE-PSK'.

Instead of using the Netconf-way to derive the PSK key from a password,
you can also give the PSK username and key directly on the command line:

     $ ./gnutls-cli -p 5556 localhost --pskusername psk_identity --pskkey 88f3824b3e5659f52d00e959bacab954b6540344  --priority NORMAL:+DHE-PSK:+PSK
     Resolving 'localhost'...
     Connecting to '127.0.0.1:5556'...
     - PSK authentication.
     - Version: TLS1.1
     - Key Exchange: PSK
     - Cipher: AES-128-CBC
     - MAC: SHA1
     - Compression: NULL
     - Handshake was completed

     - Simple Client Mode:

By keeping the `--pskusername' parameter and removing the `--pskkey'
parameter, it will query only for the password during the handshake.


File: gnutls.info,  Node: Invoking gnutls-cli-debug,  Next: Invoking gnutls-serv,  Prev: Invoking gnutls-cli,  Up: Included programs

8.3 Invoking gnutls-cli-debug
=============================

This program was created to assist in debugging GnuTLS, but it might be
useful to extract a TLS server's capabilities.  It's purpose is to
connect onto a TLS server, perform some tests and print the server's
capabilities. If called with the `-v' parameter a more checks will be
performed. An example output is:

     crystal:/cvs/gnutls/src$ ./gnutls-cli-debug localhost -p 5556
     Resolving 'localhost'...
     Connecting to '127.0.0.1:5556'...
     Checking for TLS 1.1 support... yes
     Checking fallback from TLS 1.1 to... N/A
     Checking for TLS 1.0 support... yes
     Checking for SSL 3.0 support... yes
     Checking for version rollback bug in RSA PMS... no
     Checking for version rollback bug in Client Hello... no
     Checking whether we need to disable TLS 1.0... N/A
     Checking whether the server ignores the RSA PMS version... no
     Checking whether the server can accept Hello Extensions... yes
     Checking whether the server can accept cipher suites not in SSL 3.0 spec... yes
     Checking whether the server can accept a bogus TLS record version in the client hello... yes
     Checking for certificate information... N/A
     Checking for trusted CAs... N/A
     Checking whether the server understands TLS closure alerts... yes
     Checking whether the server supports session resumption... yes
     Checking for export-grade ciphersuite support... no
     Checking RSA-export ciphersuite info... N/A
     Checking for anonymous authentication support... no
     Checking anonymous Diffie-Hellman group info... N/A
     Checking for ephemeral Diffie-Hellman support... no
     Checking ephemeral Diffie-Hellman group info... N/A
     Checking for AES cipher support (TLS extension)... yes
     Checking for 3DES cipher support... yes
     Checking for ARCFOUR 128 cipher support... yes
     Checking for ARCFOUR 40 cipher support... no
     Checking for MD5 MAC support... yes
     Checking for SHA1 MAC support... yes
     Checking for ZLIB compression support (TLS extension)... yes
     Checking for LZO compression support (GnuTLS extension)... yes
     Checking for max record size (TLS extension)... yes
     Checking for SRP authentication support (TLS extension)... yes
     Checking for OpenPGP authentication support (TLS extension)... no


File: gnutls.info,  Node: Invoking gnutls-serv,  Next: Invoking psktool,  Prev: Invoking gnutls-cli-debug,  Up: Included programs

8.4 Invoking gnutls-serv
========================

Simple server program that listens to incoming TLS connections.


GnuTLS test server
Usage: gnutls-serv [options]

     -d, --debug integer      Enable debugging
     -g, --generate           Generate Diffie-Hellman Parameters.
     -p, --port integer       The port to connect to.
     -q, --quiet              Suppress some messages.
     --nodb                   Does not use the resume database.
     --http                   Act as an HTTP Server.
     --echo                   Act as an Echo Server.
     --dhparams FILE          DH params file to use.
     --x509fmtder             Use DER format for certificates
     --x509cafile FILE        Certificate file to use.
     --x509crlfile FILE       CRL file to use.
     --pgpkeyring FILE        PGP Key ring file to use.
     --pgpkeyfile FILE        PGP Key file to use.
     --pgpcertfile FILE       PGP Public Key (certificate) file to
                              use.
     --pgpsubkey HEX|auto     PGP subkey to use.
     --x509keyfile FILE       X.509 key file to use.
     --x509certfile FILE      X.509 Certificate file to use.
     --x509dsakeyfile FILE    Alternative X.509 key file to use.
     --x509dsacertfile FILE   Alternative X.509 certificate file to
                              use.
     -r, --require-cert       Require a valid certificate.
     -a, --disable-client-cert
                              Disable request for a client
                              certificate.
     --pskpasswd FILE         PSK password file to use.
     --pskhint HINT           PSK identity hint to use.
     --srppasswd FILE         SRP password file to use.
     --srppasswdconf FILE     SRP password conf file to use.
     --opaque-prf-input DATA
                              Use Opaque PRF Input DATA.
     --ciphers cipher1 cipher2...
                              Ciphers to enable.
     --protocols protocol1 protocol2...
                              Protocols to enable.
     --comp comp1 comp2...    Compression methods to enable.
     --macs mac1 mac2...      MACs to enable.
     --kx kx1 kx2...          Key exchange methods to enable.
     --ctypes certType1 certType2...
                              Certificate types to enable.
     --priority PRIORITY STRING
                              Priorities string.
     -l, --list               Print a list of the supported
                              algorithms  and modes.
     -h, --help               prints this help
     -v, --version            prints the program's version number

8.4.1 Setting Up a Test HTTPS Server
------------------------------------

Running your own TLS server based on GnuTLS can be useful when
debugging clients and/or GnuTLS itself.  This section describes how to
use `gnutls-serv' as a simple HTTPS server.

The most basic server can be started as:

     gnutls-serv --http

It will only support anonymous ciphersuites, which many TLS clients
refuse to use.

The next step is to add support for X.509.  First we generate a CA:

     certtool --generate-privkey > x509-ca-key.pem
     echo 'cn = GnuTLS test CA' > ca.tmpl
     echo 'ca' >> ca.tmpl
     echo 'cert_signing_key' >> ca.tmpl
     certtool --generate-self-signed --load-privkey x509-ca-key.pem \
       --template ca.tmpl --outfile x509-ca.pem
     ...

Then generate a server certificate.  Remember to change the dns_name
value to the name of your server host, or skip that command to avoid
the field.

     certtool --generate-privkey > x509-server-key.pem
     echo 'organization = GnuTLS test server' > server.tmpl
     echo 'cn = test.gnutls.org' >> server.tmpl
     echo 'tls_www_server' >> server.tmpl
     echo 'encryption_key' >> server.tmpl
     echo 'signing_key' >> server.tmpl
     echo 'dns_name = test.gnutls.org' >> server.tmpl
     certtool --generate-certificate --load-privkey x509-server-key.pem \
       --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
       --template server.tmpl --outfile x509-server.pem
     ...

For use in the client, you may want to generate a client certificate as
well.

     certtool --generate-privkey > x509-client-key.pem
     echo 'cn = GnuTLS test client' > client.tmpl
     echo 'tls_www_client' >> client.tmpl
     echo 'encryption_key' >> client.tmpl
     echo 'signing_key' >> client.tmpl
     certtool --generate-certificate --load-privkey x509-client-key.pem \
       --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
       --template client.tmpl --outfile x509-client.pem
     ...

To be able to import the client key/certificate into some applications,
you will need to convert them into a PKCS#12 structure.  This also
encrypts the security sensitive key with a password.

     certtool --to-p12 --load-ca-certificate x509-ca.pem --load-privkey x509-client-key.pem --load-certificate x509-client.pem --outder --outfile x509-client.p12

For icing, we'll create a proxy certificate for the client too.

     certtool --generate-privkey > x509-proxy-key.pem
     echo 'cn = GnuTLS test client proxy' > proxy.tmpl
     certtool --generate-proxy --load-privkey x509-proxy-key.pem \
       --load-ca-certificate x509-client.pem --load-ca-privkey x509-client-key.pem \
       --load-certificate x509-client.pem --template proxy.tmpl \
       --outfile x509-proxy.pem
     ...

Then start the server again:

     gnutls-serv --http \
                 --x509cafile x509-ca.pem \
                 --x509keyfile x509-server-key.pem \
                 --x509certfile x509-server.pem

Try connecting to the server using your web browser.  Note that the
server listens to port 5556 by default.

While you are at it, to allow connections using DSA, you can also
create a DSA key and certificate for the server.  These credentials
will be used in the final example below.

     certtool --generate-privkey --dsa > x509-server-key-dsa.pem
     certtool --generate-certificate --load-privkey x509-server-key-dsa.pem \
       --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
       --template server.tmpl --outfile x509-server-dsa.pem
     ...

The next step is to create OpenPGP credentials for the server.

     gpg --gen-key
     ...enter whatever details you want, use 'test.gnutls.org' as name...

Make a note of the OpenPGP key identifier of the newly generated key,
here it was `5D1D14D8'.  You will need to export the key for GnuTLS to
be able to use it.

     gpg -a --export 5D1D14D8 > openpgp-server.txt
     gpg --export 5D1D14D8 > openpgp-server.bin
     gpg --export-secret-keys 5D1D14D8 > openpgp-server-key.bin
     gpg -a --export-secret-keys 5D1D14D8 > openpgp-server-key.txt

Let's start the server with support for OpenPGP credentials:

     gnutls-serv --http \
                 --pgpkeyfile openpgp-server-key.txt \
                 --pgpcertfile openpgp-server.txt

The next step is to add support for SRP authentication.

     srptool --create-conf srp-tpasswd.conf
     srptool --passwd-conf srp-tpasswd.conf --username jas --passwd srp-passwd.txt
     Enter password: [TYPE "foo"]

Start the server with SRP support:

     gnutls-serv --http \
                 --srppasswdconf srp-tpasswd.conf \
                 --srppasswd srp-passwd.txt

Let's also add support for PSK.

     $ psktool --passwd psk-passwd.txt

Start the server with PSK support:

     gnutls-serv --http \
                 --pskpasswd psk-passwd.txt

Finally, we start the server with all the earlier parameters and you
get this command:

     gnutls-serv --http \
                 --x509cafile x509-ca.pem \
                 --x509keyfile x509-server-key.pem \
                 --x509certfile x509-server.pem \
                 --x509dsakeyfile x509-server-key-dsa.pem \
                 --x509dsacertfile x509-server-dsa.pem \
                 --pgpkeyfile openpgp-server-key.txt \
                 --pgpcertfile openpgp-server.txt \
                 --srppasswdconf srp-tpasswd.conf \
                 --srppasswd srp-passwd.txt \
                 --pskpasswd psk-passwd.txt

* Menu:

* Example server PSK connection::


File: gnutls.info,  Node: Example server PSK connection,  Up: Invoking gnutls-serv

8.4.2 Example server PSK connection
-----------------------------------

To set up a PSK server with `gnutls-serv' you need to create PSK
password file (*note Invoking psktool::).  In the example below, I type
`password' at the prompt.

     $ ./psktool -u psk_identity -p psks.txt
     Enter password:
     Key stored to psks.txt
     $ cat psks.txt
     psk_identity:88f3824b3e5659f52d00e959bacab954b6540344
     $

After this, start the server pointing to the password file.  We disable
DHE-PSK.

     $ ./gnutls-serv --pskpasswd psks.txt  --pskhint psk_identity_hint --priority NORMAL:-DHE-PSK
     Set static Diffie-Hellman parameters, consider --dhparams.
     Echo Server ready. Listening to port '5556'.

You can now connect to the server using a PSK client (*note Example
client PSK connection::).


File: gnutls.info,  Node: Invoking psktool,  Next: Invoking srptool,  Prev: Invoking gnutls-serv,  Up: Included programs

8.5 Invoking psktool
====================

This is a program to manage PSK username and keys.


PSKtool help
Usage : psktool [options]
     -u, --username username
                              specify username.
     -p, --passwd FILE        specify a password file.
     -n, --netconf-hint HINT
                              derive key from Netconf password, using
                              HINT as the psk_identity_hint.
     -s, --keysize SIZE       specify the key size in bytes.
     -v, --version            prints the program's version number
     -h, --help               shows this help text

Normally the file will generate random keys for the indicate username.
You may also derive PSK keys from passwords, using the algorithm
specified in `draft-ietf-netconf-tls-02.txt'.  The algorithm needs a
PSK identity hint, which you specify using `--netconf-hint'.  To derive
a PSK key from a password with an empty PSK identity hint, using
`--netconf-hint ""'.


File: gnutls.info,  Node: Invoking srptool,  Next: Invoking p11tool,  Prev: Invoking psktool,  Up: Included programs

8.6 Invoking srptool
====================

The `srptool' is a very simple program that emulates the programs in
the _Stanford SRP libraries_, see `http://srp.stanford.edu/'.  It is
intended for use in places where you don't expect SRP authentication to
be the used for system users.

Traditionally _libsrp_ used two files. One called `tpasswd' which holds
usernames and verifiers, and `tpasswd.conf' which holds generators and
primes.

How to use srptool:

   * To create tpasswd.conf which holds the g and n values for SRP
     protocol (generator and a large prime), run:

          $ srptool --create-conf /etc/tpasswd.conf

   * This command will create /etc/tpasswd and will add user 'test' (you
     will also be prompted for a password).  Verifiers are stored by
     default in the way libsrp expects.

          $ srptool --passwd /etc/tpasswd \
              --passwd-conf /etc/tpasswd.conf -u test

   * This command will check against a password.  If the password
     matches the one in /etc/tpasswd you will get an ok.

          $ srptool --passwd /etc/tpasswd \
              --passwd-conf /etc/tpasswd.conf --verify -u test



File: gnutls.info,  Node: Invoking p11tool,  Prev: Invoking srptool,  Up: Included programs

8.7 Invoking p11tool
====================

The `p11tool' is a program that helps with accessing tokens and
security modules that support the PKCS #11 API. It requires the
individual PKCS #11 modules to be loaded either with the `--provider'
option, or by setting up the GnuTLS configuration file for PKCS #11 as
in *Note sec:pkcs11::.


p11tool help
Usage: p11tool [options]

     --export URL             Export an object specified by a pkcs11
                              URL
     --list-tokens            List all available tokens
     --list-mechanisms URL    List all available mechanisms in token.
     --list-all               List all objects specified by a PKCS#11
                              URL
     --list-all-certs         List all certificates specified by a
                              PKCS#11 URL
     --list-certs             List certificates that have a private
                              key specified by a PKCS#11 URL
     --list-privkeys          List private keys specified by a
                              PKCS#11 URL
     --list-trusted           List certificates marked as trusted,
                              specified by a PKCS#11 URL
     --initialize URL         Initializes a PKCS11 token.
     --write URL              Writes loaded certificates, private or
                              secret keys to a PKCS11 token.
     --delete URL             Deletes objects matching the URL.
     --label label            Sets a label for the write operation.
     --trusted                Marks the certificate to be imported as
                              trusted.
     --login                  Force login to token
     --detailed-url           Export detailed URLs.
     --no-detailed-url        Export less detailed URLs.
     --secret-key HEX_KEY     Provide a hex encoded secret key.
     --load-privkey FILE      Private key file to use.
     --load-pubkey FILE       Private key file to use.
     --load-certificate FILE
                              Certificate file to use.
     -8, --pkcs8              Use PKCS #8 format for private keys.
     --inder                  Use DER format for input certificates
                              and private keys.
     --inraw                  Use RAW/DER format for input
                              certificates and private keys.
     --provider Library       Specify the pkcs11 provider library
     --outfile FILE           Output file.
     -d, --debug LEVEL        specify the debug level. Default is 1.
     -h, --help               shows this help text

After being provided the available PKCS #11 modules, it can list all
tokens available in your system, the objects on the tokens, and perform
operations on them.

Some examples on how to use p11tool:

   * List all tokens
          $ p11tool --list-tokens

   * List all objects
          $ p11tool --login --list-all

   * To export an object
          $ p11tool --login --export pkcs11:(OBJECT URL)

   * To copy an object to a token
          $ p11tool --login --write pkcs11:(TOKEN URL) --load-certificate (certificate file) --label "my_cert"


Note that typically PKCS #11 private key objects are not allowed to be
extracted from the token.


File: gnutls.info,  Node: Function reference,  Next: All the supported ciphersuites in GnuTLS,  Prev: Included programs,  Up: Top

9 Function Reference
********************

* Menu:

* Core functions::
* X.509 certificate functions::
* GnuTLS-extra functions::
* OpenPGP functions::
* TLS Inner Application (TLS/IA) functions::
* Error codes and descriptions::


File: gnutls.info,  Node: Core functions,  Next: X.509 certificate functions,  Up: Function reference

9.1 Core Functions
==================

The prototypes for the following functions lie in `gnutls/gnutls.h'.

gnutls_alert_get_name
---------------------

 -- Function: const char * gnutls_alert_get_name
          (gnutls_alert_description_t ALERT)
     ALERT: is an alert number `gnutls_session_t' structure.

     This function will return a string that describes the given alert
     number, or `NULL'.  See `gnutls_alert_get()'.

     *Returns:* string corresponding to `gnutls_alert_description_t'
     value.

gnutls_alert_get
----------------

 -- Function: gnutls_alert_description_t gnutls_alert_get
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function will return the last alert number received.  This
     function should be called if `GNUTLS_E_WARNING_ALERT_RECEIVED' or
     `GNUTLS_E_FATAL_ALERT_RECEIVED' has been returned by a gnutls
     function.  The peer may send alerts if he thinks some things were
     not right. Check gnutls.h for the available alert descriptions.

     If no alert has been received the returned value is undefined.

     *Returns:* returns the last alert received, a
     `gnutls_alert_description_t' value.

gnutls_alert_send_appropriate
-----------------------------

 -- Function: int gnutls_alert_send_appropriate (gnutls_session_t
          SESSION, int ERR)
     SESSION: is a `gnutls_session_t' structure.

     ERR: is an integer

     Sends an alert to the peer depending on the error code returned by
     a gnutls function. This function will call
     `gnutls_error_to_alert()' to determine the appropriate alert to
     send.

     This function may also return `GNUTLS_E_AGAIN', or
     `GNUTLS_E_INTERRUPTED'.

     If the return value is `GNUTLS_E_INVALID_REQUEST', then no alert
     has been sent to the peer.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_alert_send
-----------------

 -- Function: int gnutls_alert_send (gnutls_session_t SESSION,
          gnutls_alert_level_t LEVEL, gnutls_alert_description_t DESC)
     SESSION: is a `gnutls_session_t' structure.

     LEVEL: is the level of the alert

     DESC: is the alert description

     This function will send an alert to the peer in order to inform
     him of something important (eg. his Certificate could not be
     verified).  If the alert level is Fatal then the peer is expected
     to close the connection, otherwise he may ignore the alert and
     continue.

     The error code of the underlying record send function will be
     returned, so you may also receive `GNUTLS_E_INTERRUPTED' or
     `GNUTLS_E_AGAIN' as well.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_anon_allocate_client_credentials
---------------------------------------

 -- Function: int gnutls_anon_allocate_client_credentials
          (gnutls_anon_client_credentials_t * SC)
     SC: is a pointer to a `gnutls_anon_client_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to allocate it.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_anon_allocate_server_credentials
---------------------------------------

 -- Function: int gnutls_anon_allocate_server_credentials
          (gnutls_anon_server_credentials_t * SC)
     SC: is a pointer to a `gnutls_anon_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to allocate it.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_anon_free_client_credentials
-----------------------------------

 -- Function: void gnutls_anon_free_client_credentials
          (gnutls_anon_client_credentials_t SC)
     SC: is a `gnutls_anon_client_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to free (deallocate) it.

gnutls_anon_free_server_credentials
-----------------------------------

 -- Function: void gnutls_anon_free_server_credentials
          (gnutls_anon_server_credentials_t SC)
     SC: is a `gnutls_anon_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to free (deallocate) it.

gnutls_anon_set_params_function
-------------------------------

 -- Function: void gnutls_anon_set_params_function
          (gnutls_anon_server_credentials_t RES, gnutls_params_function
          * FUNC)
     RES: is a gnutls_anon_server_credentials_t structure

     FUNC: is the function to be called

     This function will set a callback in order for the server to get
     the Diffie-Hellman or RSA parameters for anonymous authentication.
     The callback should return zero on success.

gnutls_anon_set_server_dh_params
--------------------------------

 -- Function: void gnutls_anon_set_server_dh_params
          (gnutls_anon_server_credentials_t RES, gnutls_dh_params_t
          DH_PARAMS)
     RES: is a gnutls_anon_server_credentials_t structure

     DH_PARAMS: is a structure that holds Diffie-Hellman parameters.

     This function will set the Diffie-Hellman parameters for an
     anonymous server to use.  These parameters will be used in
     Anonymous Diffie-Hellman cipher suites.

gnutls_anon_set_server_params_function
--------------------------------------

 -- Function: void gnutls_anon_set_server_params_function
          (gnutls_anon_server_credentials_t RES, gnutls_params_function
          * FUNC)
     RES: is a gnutls_certificate_credentials_t structure

     FUNC: is the function to be called

     This function will set a callback in order for the server to get
     the Diffie-Hellman parameters for anonymous authentication.  The
     callback should return zero on success.

gnutls_auth_client_get_type
---------------------------

 -- Function: gnutls_credentials_type_t gnutls_auth_client_get_type
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Returns the type of credentials that were used for client
     authentication.  The returned information is to be used to
     distinguish the function used to access authentication data.

     *Returns:* The type of credentials for the client authentication
     schema, a `gnutls_credentials_type_t' type.

gnutls_auth_get_type
--------------------

 -- Function: gnutls_credentials_type_t gnutls_auth_get_type
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Returns type of credentials for the current authentication schema.
     The returned information is to be used to distinguish the function
     used to access authentication data.

     Eg. for CERTIFICATE ciphersuites (key exchange algorithms:
     `GNUTLS_KX_RSA', `GNUTLS_KX_DHE_RSA'), the same function are to be
     used to access the authentication data.

     *Returns:* The type of credentials for the current authentication
     schema, a `gnutls_credentials_type_t' type.

gnutls_auth_server_get_type
---------------------------

 -- Function: gnutls_credentials_type_t gnutls_auth_server_get_type
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Returns the type of credentials that were used for server
     authentication.  The returned information is to be used to
     distinguish the function used to access authentication data.

     *Returns:* The type of credentials for the server authentication
     schema, a `gnutls_credentials_type_t' type.

gnutls_bye
----------

 -- Function: int gnutls_bye (gnutls_session_t SESSION,
          gnutls_close_request_t HOW)
     SESSION: is a `gnutls_session_t' structure.

     HOW: is an integer

     Terminates the current TLS/SSL connection. The connection should
     have been initiated using `gnutls_handshake()'.  `how' should be
     one of `GNUTLS_SHUT_RDWR', `GNUTLS_SHUT_WR'.

     In case of `GNUTLS_SHUT_RDWR' then the TLS connection gets
     terminated and further receives and sends will be disallowed.  If
     the return value is zero you may continue using the connection.
     `GNUTLS_SHUT_RDWR' actually sends an alert containing a close
     request and waits for the peer to reply with the same message.

     In case of `GNUTLS_SHUT_WR' then the TLS connection gets terminated
     and further sends will be disallowed. In order to reuse the
     connection you should wait for an EOF from the peer.
     `GNUTLS_SHUT_WR' sends an alert containing a close request.

     Note that not all implementations will properly terminate a TLS
     connection.  Some of them, usually for performance reasons, will
     terminate only the underlying transport layer, thus causing a
     transmission error to the peer.  This error cannot be
     distinguished from a malicious party prematurely terminating the
     session, thus this behavior is not recommended.

     This function may also return `GNUTLS_E_AGAIN' or
     `GNUTLS_E_INTERRUPTED'; cf.  `gnutls_record_get_direction()'.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code, see
     function documentation for entire semantics.

gnutls_certificate_activation_time_peers
----------------------------------------

 -- Function: time_t gnutls_certificate_activation_time_peers
          (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     This function will return the peer's certificate activation time.
     This is the creation time for openpgp keys.

     *Returns:* (time_t)-1 on error.

     *Deprecated:* `gnutls_certificate_verify_peers2()' now verifies
     activation times.

gnutls_certificate_allocate_credentials
---------------------------------------

 -- Function: int gnutls_certificate_allocate_credentials
          (gnutls_certificate_credentials_t * RES)
     RES: is a pointer to a `gnutls_certificate_credentials_t'
     structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to allocate it.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_certificate_client_get_request_status
--------------------------------------------

 -- Function: int gnutls_certificate_client_get_request_status
          (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     Get whether client certificate is requested or not.

     *Returns:* 0 if the peer (server) did not request client
     authentication or 1 otherwise, or a negative value in case of
     error.

gnutls_certificate_client_set_retrieve_function
-----------------------------------------------

 -- Function: void gnutls_certificate_client_set_retrieve_function
          (gnutls_certificate_credentials_t CRED,
          gnutls_certificate_client_retrieve_function * FUNC)
     CRED: is a `gnutls_certificate_credentials_t' structure.

     FUNC: is the callback function

     This function sets a callback to be called in order to retrieve the
     certificate to be used in the handshake.

     The callback's function prototype is: int
     (*callback)(gnutls_session_t, const gnutls_datum_t* req_ca_dn, int
     nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length,
     gnutls_retr_st* st);

     `req_ca_cert' is only used in X.509 certificates.  Contains a list
     with the CA names that the server considers trusted.  Normally we
     should send a certificate that is signed by one of these CAs.
     These names are DER encoded. To get a more meaningful value use
     the function `gnutls_x509_rdn_get()'.

     `pk_algos' contains a list with server's acceptable signature
     algorithms.  The certificate returned should support the server's
     given algorithms.

     `st' should contain the certificates and private keys.

     If the callback function is provided then gnutls will call it, in
     the handshake, after the certificate request message has been
     received.

     The callback function should set the certificate list to be sent,
     and return 0 on success. If no certificate was selected then the
     number of certificates should be set to zero. The value (-1)
     indicates error and the handshake will be terminated.

gnutls_certificate_expiration_time_peers
----------------------------------------

 -- Function: time_t gnutls_certificate_expiration_time_peers
          (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     This function will return the peer's certificate expiration time.

     *Returns:* (time_t)-1 on error.

     *Deprecated:* `gnutls_certificate_verify_peers2()' now verifies
     expiration times.

gnutls_certificate_free_ca_names
--------------------------------

 -- Function: void gnutls_certificate_free_ca_names
          (gnutls_certificate_credentials_t SC)
     SC: is a `gnutls_certificate_credentials_t' structure.

     This function will delete all the CA name in the given
     credentials. Clients may call this to save some memory since in
     client side the CA names are not used. Servers might want to use
     this function if a large list of trusted CAs is present and
     sending the names of it would just consume bandwidth without
     providing information to client.

     CA names are used by servers to advertize the CAs they support to
     clients.

gnutls_certificate_free_cas
---------------------------

 -- Function: void gnutls_certificate_free_cas
          (gnutls_certificate_credentials_t SC)
     SC: is a `gnutls_certificate_credentials_t' structure.

     This function will delete all the CAs associated with the given
     credentials. Servers that do not use
     `gnutls_certificate_verify_peers2()' may call this to save some
     memory.

gnutls_certificate_free_credentials
-----------------------------------

 -- Function: void gnutls_certificate_free_credentials
          (gnutls_certificate_credentials_t SC)
     SC: is a `gnutls_certificate_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to free (deallocate) it.

     This function does not free any temporary parameters associated
     with this structure (ie RSA and DH parameters are not freed by this
     function).

gnutls_certificate_free_crls
----------------------------

 -- Function: void gnutls_certificate_free_crls
          (gnutls_certificate_credentials_t SC)
     SC: is a `gnutls_certificate_credentials_t' structure.

     This function will delete all the CRLs associated with the given
     credentials.

gnutls_certificate_free_keys
----------------------------

 -- Function: void gnutls_certificate_free_keys
          (gnutls_certificate_credentials_t SC)
     SC: is a `gnutls_certificate_credentials_t' structure.

     This function will delete all the keys and the certificates
     associated with the given credentials. This function must not be
     called when a TLS negotiation that uses the credentials is in
     progress.

gnutls_certificate_get_issuer
-----------------------------

 -- Function: int gnutls_certificate_get_issuer
          (gnutls_certificate_credentials_t SC, gnutls_x509_crt_t CERT,
          gnutls_x509_crt_t* ISSUER, unsigned int FLAGS)
     SC: is a `gnutls_certificate_credentials_t' structure.

     CERT: is the certificate to find issuer for

     ISSUER: Will hold the issuer if any. Should be treated as constant.

     FLAGS: Use zero.

     This function will return the issuer of a given certificate.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_certificate_get_openpgp_keyring
--------------------------------------

 -- Function: void gnutls_certificate_get_openpgp_keyring
          (gnutls_certificate_credentials_t SC,
          gnutls_openpgp_keyring_t * KEYRING)
     SC: is a `gnutls_certificate_credentials_t' structure.

     KEYRING: the exported keyring. Should be treated as constant

     This function will export the OpenPGP keyring associated with the
     given credentials.

     *Since:* 2.4.0

gnutls_certificate_get_ours
---------------------------

 -- Function: const gnutls_datum_t * gnutls_certificate_get_ours
          (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     Get the certificate as sent to the peer, in the last handshake.
     These certificates are in raw format.  In X.509 this is a
     certificate list. In OpenPGP this is a single certificate.

     *Returns:* return a pointer to a `gnutls_datum_t' containing our
     certificates, or `NULL' in case of an error or if no certificate
     was used.

gnutls_certificate_get_peers
----------------------------

 -- Function: const gnutls_datum_t * gnutls_certificate_get_peers
          (gnutls_session_t SESSION, unsigned int * LIST_SIZE)
     SESSION: is a gnutls session

     LIST_SIZE: is the length of the certificate list

     Get the peer's raw certificate (chain) as sent by the peer.  These
     certificates are in raw format (DER encoded for X.509).  In case of
     a X.509 then a certificate list may be present.  The first
     certificate in the list is the peer's certificate, following the
     issuer's certificate, then the issuer's issuer etc.

     In case of OpenPGP keys a single key will be returned in raw
     format.

     *Returns:* return a pointer to a `gnutls_datum_t' containing our
     certificates, or `NULL' in case of an error or if no certificate
     was used.

gnutls_certificate_get_x509_cas
-------------------------------

 -- Function: void gnutls_certificate_get_x509_cas
          (gnutls_certificate_credentials_t SC, gnutls_x509_crt_t **
          X509_CA_LIST, unsigned int * NCAS)
     SC: is a `gnutls_certificate_credentials_t' structure.

     X509_CA_LIST: will point to the CA list. Should be treated as
     constant

     NCAS: the number of CAs

     This function will export all the CAs associated with the given
     credentials.

     *Since:* 2.4.0

gnutls_certificate_get_x509_crls
--------------------------------

 -- Function: void gnutls_certificate_get_x509_crls
          (gnutls_certificate_credentials_t SC, gnutls_x509_crl_t **
          X509_CRL_LIST, unsigned int * NCRLS)
     SC: is a `gnutls_certificate_credentials_t' structure.

     X509_CRL_LIST: the exported CRL list. Should be treated as constant

     NCRLS: the number of exported CRLs

     This function will export all the CRLs associated with the given
     credentials.

     *Since:* 2.4.0

gnutls_certificate_send_x509_rdn_sequence
-----------------------------------------

 -- Function: void gnutls_certificate_send_x509_rdn_sequence
          (gnutls_session_t SESSION, int STATUS)
     SESSION: is a pointer to a `gnutls_session_t' structure.

     STATUS: is 0 or 1

     If status is non zero, this function will order gnutls not to send
     the rdnSequence in the certificate request message. That is the
     server will not advertize it's trusted CAs to the peer. If status
     is zero then the default behaviour will take effect, which is to
     advertize the server's trusted CAs.

     This function has no effect in clients, and in authentication
     methods other than certificate with X.509 certificates.

gnutls_certificate_server_set_request
-------------------------------------

 -- Function: void gnutls_certificate_server_set_request
          (gnutls_session_t SESSION, gnutls_certificate_request_t REQ)
     SESSION: is a `gnutls_session_t' structure.

     REQ: is one of GNUTLS_CERT_REQUEST, GNUTLS_CERT_REQUIRE

     This function specifies if we (in case of a server) are going to
     send a certificate request message to the client. If `req' is
     GNUTLS_CERT_REQUIRE then the server will return an error if the
     peer does not provide a certificate. If you do not call this
     function then the client will not be asked to send a certificate.

gnutls_certificate_server_set_retrieve_function
-----------------------------------------------

 -- Function: void gnutls_certificate_server_set_retrieve_function
          (gnutls_certificate_credentials_t CRED,
          gnutls_certificate_server_retrieve_function * FUNC)
     CRED: is a `gnutls_certificate_credentials_t' structure.

     FUNC: is the callback function

     This function sets a callback to be called in order to retrieve the
     certificate to be used in the handshake.

     The callback's function prototype is: int
     (*callback)(gnutls_session_t, gnutls_retr_st* st);

     `st' should contain the certificates and private keys.

     If the callback function is provided then gnutls will call it, in
     the handshake, after the certificate request message has been
     received.

     The callback function should set the certificate list to be sent,
     and return 0 on success.  The value (-1) indicates error and the
     handshake will be terminated.

gnutls_certificate_set_dh_params
--------------------------------

 -- Function: void gnutls_certificate_set_dh_params
          (gnutls_certificate_credentials_t RES, gnutls_dh_params_t
          DH_PARAMS)
     RES: is a gnutls_certificate_credentials_t structure

     DH_PARAMS: is a structure that holds Diffie-Hellman parameters.

     This function will set the Diffie-Hellman parameters for a
     certificate server to use. These parameters will be used in
     Ephemeral Diffie-Hellman cipher suites.  Note that only a pointer
     to the parameters are stored in the certificate handle, so if you
     deallocate the parameters before the certificate is deallocated,
     you must change the parameters stored in the certificate first.

gnutls_certificate_set_params_function
--------------------------------------

 -- Function: void gnutls_certificate_set_params_function
          (gnutls_certificate_credentials_t RES, gnutls_params_function
          * FUNC)
     RES: is a gnutls_certificate_credentials_t structure

     FUNC: is the function to be called

     This function will set a callback in order for the server to get
     the Diffie-Hellman or RSA parameters for certificate
     authentication.  The callback should return zero on success.

gnutls_certificate_set_retrieve_function
----------------------------------------

 -- Function: void gnutls_certificate_set_retrieve_function
          (gnutls_certificate_credentials_t CRED,
          gnutls_certificate_retrieve_function * FUNC)
     CRED: is a `gnutls_certificate_credentials_t' structure.

     FUNC: is the callback function

     This function sets a callback to be called in order to retrieve the
     certificate to be used in the handshake.

     The callback's function prototype is: int
     (*callback)(gnutls_session_t, const gnutls_datum_t* req_ca_dn, int
     nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length,
     gnutls_retr2_st* st);

     `req_ca_cert' is only used in X.509 certificates.  Contains a list
     with the CA names that the server considers trusted.  Normally we
     should send a certificate that is signed by one of these CAs.
     These names are DER encoded. To get a more meaningful value use
     the function `gnutls_x509_rdn_get()'.

     `pk_algos' contains a list with server's acceptable signature
     algorithms.  The certificate returned should support the server's
     given algorithms.

     `st' should contain the certificates and private keys.

     If the callback function is provided then gnutls will call it, in
     the handshake, after the certificate request message has been
     received.

     In server side pk_algos and req_ca_dn are NULL.

     The callback function should set the certificate list to be sent,
     and return 0 on success. If no certificate was selected then the
     number of certificates should be set to zero. The value (-1)
     indicates error and the handshake will be terminated.

gnutls_certificate_set_rsa_export_params
----------------------------------------

 -- Function: void gnutls_certificate_set_rsa_export_params
          (gnutls_certificate_credentials_t RES, gnutls_rsa_params_t
          RSA_PARAMS)
     RES: is a gnutls_certificate_credentials_t structure

     RSA_PARAMS: is a structure that holds temporary RSA parameters.

     This function will set the temporary RSA parameters for a
     certificate server to use.  These parameters will be used in
     RSA-EXPORT cipher suites.

gnutls_certificate_set_verify_flags
-----------------------------------

 -- Function: void gnutls_certificate_set_verify_flags
          (gnutls_certificate_credentials_t RES, unsigned int FLAGS)
     RES: is a gnutls_certificate_credentials_t structure

     FLAGS: are the flags

     This function will set the flags to be used at verification of the
     certificates.  Flags must be OR of the
     `gnutls_certificate_verify_flags' enumerations.

gnutls_certificate_set_verify_function
--------------------------------------

 -- Function: void gnutls_certificate_set_verify_function
          (gnutls_certificate_credentials_t CRED,
          gnutls_certificate_verify_function * FUNC)
     CRED: is a `gnutls_certificate_credentials_t' structure.

     FUNC: is the callback function

     This function sets a callback to be called when peer's certificate
     has been received in order to verify it on receipt rather than
     doing after the handshake is completed.

     The callback's function prototype is: int
     (*callback)(gnutls_session_t);

     If the callback function is provided then gnutls will call it, in
     the handshake, just after the certificate message has been
     received.  To verify or obtain the certificate the
     `gnutls_certificate_verify_peers2()',
     `gnutls_certificate_type_get()', `gnutls_certificate_get_peers()'
     functions can be used.

     The callback function should return 0 for the handshake to continue
     or non-zero to terminate.

     *Since:* 2.10.0

gnutls_certificate_set_verify_limits
------------------------------------

 -- Function: void gnutls_certificate_set_verify_limits
          (gnutls_certificate_credentials_t RES, unsigned int MAX_BITS,
          unsigned int MAX_DEPTH)
     RES: is a gnutls_certificate_credentials structure

     MAX_BITS: is the number of bits of an acceptable certificate
     (default 8200)

     MAX_DEPTH: is maximum depth of the verification of a certificate
     chain (default 5)

     This function will set some upper limits for the default
     verification function, `gnutls_certificate_verify_peers2()', to
     avoid denial of service attacks.  You can set them to zero to
     disable limits.

gnutls_certificate_set_x509_crl_file
------------------------------------

 -- Function: int gnutls_certificate_set_x509_crl_file
          (gnutls_certificate_credentials_t RES, const char * CRLFILE,
          gnutls_x509_crt_fmt_t TYPE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CRLFILE: is a file containing the list of verified CRLs (DER or
     PEM list)

     TYPE: is PEM or DER

     This function adds the trusted CRLs in order to verify client or
     server certificates.  In case of a client this is not required to
     be called if the certificates are not verified using
     `gnutls_certificate_verify_peers2()'.  This function may be called
     multiple times.

     *Returns:* number of CRLs processed or a negative value on error.

gnutls_certificate_set_x509_crl_mem
-----------------------------------

 -- Function: int gnutls_certificate_set_x509_crl_mem
          (gnutls_certificate_credentials_t RES, const gnutls_datum_t *
          CRL, gnutls_x509_crt_fmt_t TYPE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CRL: is a list of trusted CRLs. They should have been verified
     before.

     TYPE: is DER or PEM

     This function adds the trusted CRLs in order to verify client or
     server certificates.  In case of a client this is not required to
     be called if the certificates are not verified using
     `gnutls_certificate_verify_peers2()'.  This function may be called
     multiple times.

     *Returns:* number of CRLs processed, or a negative value on error.

gnutls_certificate_set_x509_crl
-------------------------------

 -- Function: int gnutls_certificate_set_x509_crl
          (gnutls_certificate_credentials_t RES, gnutls_x509_crl_t *
          CRL_LIST, int CRL_LIST_SIZE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CRL_LIST: is a list of trusted CRLs. They should have been
     verified before.

     CRL_LIST_SIZE: holds the size of the crl_list

     This function adds the trusted CRLs in order to verify client or
     server certificates.  In case of a client this is not required to
     be called if the certificates are not verified using
     `gnutls_certificate_verify_peers2()'.  This function may be called
     multiple times.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

     *Since:* 2.4.0

gnutls_certificate_set_x509_key_file
------------------------------------

 -- Function: int gnutls_certificate_set_x509_key_file
          (gnutls_certificate_credentials_t RES, const char * CERTFILE,
          const char * KEYFILE, gnutls_x509_crt_fmt_t TYPE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CERTFILE: is a file that containing the certificate list (path) for
     the specified private key, in PKCS7 format, or a list of
     certificates

     KEYFILE: is a file that contains the private key

     TYPE: is PEM or DER

     This function sets a certificate/private key pair in the
     gnutls_certificate_credentials_t structure.  This function may be
     called more than once (in case multiple keys/certificates exist for
     the server).  For clients that wants to send more than its own end
     entity certificate (e.g., also an intermediate CA cert) then put
     the certificate chain in `certfile'.

     Currently only PKCS-1 encoded RSA and DSA private keys are
     accepted by this function.

     This function can also accept PKCS `11' URLs. In that case it will
     import the private key and certificate indicated by the urls.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_certificate_set_x509_key_mem
-----------------------------------

 -- Function: int gnutls_certificate_set_x509_key_mem
          (gnutls_certificate_credentials_t RES, const gnutls_datum_t *
          CERT, const gnutls_datum_t * KEY, gnutls_x509_crt_fmt_t TYPE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CERT: contains a certificate list (path) for the specified private
     key

     KEY: is the private key, or `NULL'

     TYPE: is PEM or DER

     This function sets a certificate/private key pair in the
     gnutls_certificate_credentials_t structure. This function may be
     called more than once (in case multiple keys/certificates exist
     for the server).

     *Currently are supported:* RSA PKCS-1 encoded private keys, DSA
     private keys.

     DSA private keys are encoded the OpenSSL way, which is an ASN.1
     DER sequence of 6 INTEGERs - version, p, q, g, pub, priv.

     Note that the keyUsage (2.5.29.15) PKIX extension in X.509
     certificates is supported. This means that certificates intended
     for signing cannot be used for ciphersuites that require
     encryption.

     If the certificate and the private key are given in PEM encoding
     then the strings that hold their values must be null terminated.

     The `key' may be `NULL' if you are using a sign callback, see
     `gnutls_sign_callback_set()'.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_certificate_set_x509_key
-------------------------------

 -- Function: int gnutls_certificate_set_x509_key
          (gnutls_certificate_credentials_t RES, gnutls_x509_crt_t *
          CERT_LIST, int CERT_LIST_SIZE, gnutls_x509_privkey_t KEY)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CERT_LIST: contains a certificate list (path) for the specified
     private key

     CERT_LIST_SIZE: holds the size of the certificate list

     KEY: is a gnutls_x509_privkey_t key

     This function sets a certificate/private key pair in the
     gnutls_certificate_credentials_t structure.  This function may be
     called more than once (in case multiple keys/certificates exist for
     the server).  For clients that wants to send more than its own end
     entity certificate (e.g., also an intermediate CA cert) then put
     the certificate chain in `cert_list'.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

     *Since:* 2.4.0

gnutls_certificate_set_x509_simple_pkcs12_file
----------------------------------------------

 -- Function: int gnutls_certificate_set_x509_simple_pkcs12_file
          (gnutls_certificate_credentials_t RES, const char *
          PKCS12FILE, gnutls_x509_crt_fmt_t TYPE, const char * PASSWORD)
     RES: is a `gnutls_certificate_credentials_t' structure.

     PKCS12FILE: filename of file containing PKCS`12' blob.

     TYPE: is PEM or DER of the `pkcs12file'.

     PASSWORD: optional password used to decrypt PKCS`12' file, bags
     and keys.

     This function sets a certificate/private key pair and/or a CRL in
     the gnutls_certificate_credentials_t structure.  This function may
     be called more than once (in case multiple keys/certificates exist
     for the server).

     *MAC:* ed PKCS`12' files are supported.  Encrypted PKCS`12' bags
     are supported.  Encrypted PKCS`8' private keys are supported.
     However, only password based security, and the same password for
     all operations, are supported.

     The private keys may be RSA PKCS`1' or DSA private keys encoded in
     the OpenSSL way.

     PKCS`12' file may contain many keys and/or certificates, and there
     is no way to identify which key/certificate pair you want.  You
     should make sure the PKCS`12' file only contain one key/certificate
     pair and/or one CRL.

     It is believed that the limitations of this function is acceptable
     for most usage, and that any more flexibility would introduce
     complexity that would make it harder to use this functionality at
     all.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_certificate_set_x509_simple_pkcs12_mem
---------------------------------------------

 -- Function: int gnutls_certificate_set_x509_simple_pkcs12_mem
          (gnutls_certificate_credentials_t RES, const gnutls_datum_t *
          P12BLOB, gnutls_x509_crt_fmt_t TYPE, const char * PASSWORD)
     RES: is a `gnutls_certificate_credentials_t' structure.

     P12BLOB: the PKCS`12' blob.

     TYPE: is PEM or DER of the `pkcs12file'.

     PASSWORD: optional password used to decrypt PKCS`12' file, bags
     and keys.

     This function sets a certificate/private key pair and/or a CRL in
     the gnutls_certificate_credentials_t structure.  This function may
     be called more than once (in case multiple keys/certificates exist
     for the server).

     *MAC:* ed PKCS`12' files are supported.  Encrypted PKCS`12' bags
     are supported.  Encrypted PKCS`8' private keys are supported.
     However, only password based security, and the same password for
     all operations, are supported.

     The private keys may be RSA PKCS`1' or DSA private keys encoded in
     the OpenSSL way.

     PKCS`12' file may contain many keys and/or certificates, and there
     is no way to identify which key/certificate pair you want.  You
     should make sure the PKCS`12' file only contain one key/certificate
     pair and/or one CRL.

     It is believed that the limitations of this function is acceptable
     for most usage, and that any more flexibility would introduce
     complexity that would make it harder to use this functionality at
     all.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

     *Since:* 2.8.0

gnutls_certificate_set_x509_trust_file
--------------------------------------

 -- Function: int gnutls_certificate_set_x509_trust_file
          (gnutls_certificate_credentials_t RES, const char * CAFILE,
          gnutls_x509_crt_fmt_t TYPE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CAFILE: is a file containing the list of trusted CAs (DER or PEM
     list)

     TYPE: is PEM or DER

     This function adds the trusted CAs in order to verify client or
     server certificates. In case of a client this is not required to
     be called if the certificates are not verified using
     `gnutls_certificate_verify_peers2()'.  This function may be called
     multiple times.

     In case of a server the names of the CAs set here will be sent to
     the client if a certificate request is sent. This can be disabled
     using `gnutls_certificate_send_x509_rdn_sequence()'.

     This function can also accept PKCS `11' URLs. In that case it will
     import all certificates that are marked as trusted.

     *Returns:* number of certificates processed, or a negative value on
     error.

gnutls_certificate_set_x509_trust_mem
-------------------------------------

 -- Function: int gnutls_certificate_set_x509_trust_mem
          (gnutls_certificate_credentials_t RES, const gnutls_datum_t *
          CA, gnutls_x509_crt_fmt_t TYPE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CA: is a list of trusted CAs or a DER certificate

     TYPE: is DER or PEM

     This function adds the trusted CAs in order to verify client or
     server certificates. In case of a client this is not required to be
     called if the certificates are not verified using
     `gnutls_certificate_verify_peers2()'.  This function may be called
     multiple times.

     In case of a server the CAs set here will be sent to the client if
     a certificate request is sent. This can be disabled using
     `gnutls_certificate_send_x509_rdn_sequence()'.

     *Returns:* the number of certificates processed or a negative value
     on error.

gnutls_certificate_set_x509_trust
---------------------------------

 -- Function: int gnutls_certificate_set_x509_trust
          (gnutls_certificate_credentials_t RES, gnutls_x509_crt_t *
          CA_LIST, int CA_LIST_SIZE)
     RES: is a `gnutls_certificate_credentials_t' structure.

     CA_LIST: is a list of trusted CAs

     CA_LIST_SIZE: holds the size of the CA list

     This function adds the trusted CAs in order to verify client or
     server certificates. In case of a client this is not required to
     be called if the certificates are not verified using
     `gnutls_certificate_verify_peers2()'.  This function may be called
     multiple times.

     In case of a server the CAs set here will be sent to the client if
     a certificate request is sent. This can be disabled using
     `gnutls_certificate_send_x509_rdn_sequence()'.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

     *Since:* 2.4.0

gnutls_certificate_type_get_id
------------------------------

 -- Function: gnutls_certificate_type_t gnutls_certificate_type_get_id
          (const char * NAME)
     NAME: is a certificate type name

     The names are compared in a case insensitive way.

     *Returns:* a `gnutls_certificate_type_t' for the specified in a
     string certificate type, or `GNUTLS_CRT_UNKNOWN' on error.

gnutls_certificate_type_get_name
--------------------------------

 -- Function: const char * gnutls_certificate_type_get_name
          (gnutls_certificate_type_t TYPE)
     TYPE: is a certificate type

     Convert a `gnutls_certificate_type_t' type to a string.

     *Returns:* a string that contains the name of the specified
     certificate type, or `NULL' in case of unknown types.

gnutls_certificate_type_get
---------------------------

 -- Function: gnutls_certificate_type_t gnutls_certificate_type_get
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     The certificate type is by default X.509, unless it is negotiated
     as a TLS extension.

     *Returns:* the currently used `gnutls_certificate_type_t'
     certificate type.

gnutls_certificate_type_list
----------------------------

 -- Function: const gnutls_certificate_type_t *
gnutls_certificate_type_list ( VOID)
     Get a list of certificate types.  Note that to be able to use
     OpenPGP certificates, you must link to libgnutls-extra and call
     `gnutls_global_init_extra()'.

     *Returns:* a zero-terminated list of `gnutls_certificate_type_t'
     integers indicating the available certificate types.

gnutls_certificate_type_set_priority
------------------------------------

 -- Function: int gnutls_certificate_type_set_priority
          (gnutls_session_t SESSION, const int * LIST)
     SESSION: is a `gnutls_session_t' structure.

     LIST: is a 0 terminated list of gnutls_certificate_type_t elements.

     Sets the priority on the certificate types supported by gnutls.
     Priority is higher for elements specified before others.  After
     specifying the types you want, you must append a 0.  Note that the
     certificate type priority is set on the client.  The server does
     not use the cert type priority except for disabling types that
     were not specified.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_certificate_verify_peers2
--------------------------------

 -- Function: int gnutls_certificate_verify_peers2 (gnutls_session_t
          SESSION, unsigned int * STATUS)
     SESSION: is a gnutls session

     STATUS: is the output of the verification

     This function will try to verify the peer's certificate and return
     its status (trusted, invalid etc.).  The value of `status' should
     be one or more of the gnutls_certificate_status_t enumerated
     elements bitwise or'd. To avoid denial of service attacks some
     default upper limits regarding the certificate key size and chain
     size are set. To override them use
     `gnutls_certificate_set_verify_limits()'.

     Note that you must also check the peer's name in order to check if
     the verified certificate belongs to the actual peer.

     This function uses `gnutls_x509_crt_list_verify()' with the CAs in
     the credentials as trusted CAs.

     *Returns:* a negative error code on error and zero on success.

gnutls_certificate_verify_peers
-------------------------------

 -- Function: int gnutls_certificate_verify_peers (gnutls_session_t
          SESSION)
     SESSION: is a gnutls session

     This function will try to verify the peer's certificate and return
     its status (trusted, invalid etc.).  However you must also check
     the peer's name in order to check if the verified certificate
     belongs to the actual peer.

     This function uses `gnutls_x509_crt_list_verify()'.

     *Returns:* one or more of the `gnutls_certificate_status_t'
     enumerated elements bitwise or'd, or a negative value on error.

     *Deprecated:* Use `gnutls_certificate_verify_peers2()' instead.

gnutls_check_version
--------------------

 -- Function: const char * gnutls_check_version (const char *
          REQ_VERSION)
     REQ_VERSION: version string to compare with, or `NULL'.

     Check GnuTLS Library version.

     See `GNUTLS_VERSION' for a suitable `req_version' string.

     *Return value:* Check that the version of the library is at
     minimum the one given as a string in `req_version' and return the
     actual version string of the library; return `NULL' if the
     condition is not met.  If `NULL' is passed to this function no
     check is done and only the version string is returned.

gnutls_cipher_decrypt2
----------------------

 -- Function: int gnutls_cipher_decrypt2 (gnutls_cipher_hd_t HANDLE,
          const void * CIPHERTEXT, size_t CIPHERTEXTLEN, void * TEXT,
          size_t TEXTLEN)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     CIPHERTEXT: the data to encrypt

     CIPHERTEXTLEN: The length of data to encrypt

     TEXT: the decrypted data

     TEXTLEN: The available length for decrypted data

     This function will decrypt the given data using the algorithm
     specified by the context.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_cipher_decrypt
---------------------

 -- Function: int gnutls_cipher_decrypt (gnutls_cipher_hd_t HANDLE,
          void * CIPHERTEXT, size_t CIPHERTEXTLEN)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     CIPHERTEXT: the data to encrypt

     CIPHERTEXTLEN: The length of data to encrypt

     This function will decrypt the given data using the algorithm
     specified by the context.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_cipher_deinit
--------------------

 -- Function: void gnutls_cipher_deinit (gnutls_cipher_hd_t HANDLE)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     This function will deinitialize all resources occupied by the given
     encryption context.

     *Since:* 2.10.0

gnutls_cipher_encrypt2
----------------------

 -- Function: int gnutls_cipher_encrypt2 (gnutls_cipher_hd_t HANDLE,
          void * TEXT, size_t TEXTLEN, void * CIPHERTEXT, size_t
          CIPHERTEXTLEN)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     TEXT: the data to encrypt

     TEXTLEN: The length of data to encrypt

     CIPHERTEXT: the encrypted data

     CIPHERTEXTLEN: The available length for encrypted data

     This function will encrypt the given data using the algorithm
     specified by the context.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_cipher_encrypt
---------------------

 -- Function: int gnutls_cipher_encrypt (gnutls_cipher_hd_t HANDLE,
          void * TEXT, size_t TEXTLEN)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     TEXT: the data to encrypt

     TEXTLEN: The length of data to encrypt

     This function will encrypt the given data using the algorithm
     specified by the context.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_cipher_get_block_size
----------------------------

 -- Function: int gnutls_cipher_get_block_size
          (gnutls_cipher_algorithm_t ALGORITHM)
     ALGORITHM: is an encryption algorithm

     Get block size for encryption algorithm.

     *Returns:* block size for encryption algorithm.

     *Since:* 2.10.0

gnutls_cipher_get_id
--------------------

 -- Function: gnutls_cipher_algorithm_t gnutls_cipher_get_id (const
          char * NAME)
     NAME: is a MAC algorithm name

     The names are compared in a case insensitive way.

     *Returns:* return a `gnutls_cipher_algorithm_t' value
     corresponding to the specified cipher, or `GNUTLS_CIPHER_UNKNOWN'
     on error.

gnutls_cipher_get_key_size
--------------------------

 -- Function: size_t gnutls_cipher_get_key_size
          (gnutls_cipher_algorithm_t ALGORITHM)
     ALGORITHM: is an encryption algorithm

     Get key size for cipher.

     *Returns:* length (in bytes) of the given cipher's key size, or 0
     if the given cipher is invalid.

gnutls_cipher_get_name
----------------------

 -- Function: const char * gnutls_cipher_get_name
          (gnutls_cipher_algorithm_t ALGORITHM)
     ALGORITHM: is an encryption algorithm

     Convert a `gnutls_cipher_algorithm_t' type to a string.

     *Returns:* a pointer to a string that contains the name of the
     specified cipher, or `NULL'.

gnutls_cipher_get
-----------------

 -- Function: gnutls_cipher_algorithm_t gnutls_cipher_get
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get currently used cipher.

     *Returns:* the currently used cipher, a `gnutls_cipher_algorithm_t'
     type.

gnutls_cipher_init
------------------

 -- Function: int gnutls_cipher_init (gnutls_cipher_hd_t * HANDLE,
          gnutls_cipher_algorithm_t CIPHER, const gnutls_datum_t * KEY,
          const gnutls_datum_t * IV)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     CIPHER: the encryption algorithm to use

     KEY: The key to be used for encryption

     IV: The IV to use (if not applicable set NULL)

     This function will initialize an context that can be used for
     encryption/decryption of data. This will effectively use the
     current crypto backend in use by gnutls or the cryptographic
     accelerator in use.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_cipher_list
------------------

 -- Function: const gnutls_cipher_algorithm_t * gnutls_cipher_list (
          VOID)
     Get a list of supported cipher algorithms.  Note that not
     necessarily all ciphers are supported as TLS cipher suites.  For
     example, DES is not supported as a cipher suite, but is supported
     for other purposes (e.g., PKCS`8' or similar).

     *Returns:* a zero-terminated list of `gnutls_cipher_algorithm_t'
     integers indicating the available ciphers.

gnutls_cipher_set_priority
--------------------------

 -- Function: int gnutls_cipher_set_priority (gnutls_session_t SESSION,
          const int * LIST)
     SESSION: is a `gnutls_session_t' structure.

     LIST: is a 0 terminated list of gnutls_cipher_algorithm_t elements.

     Sets the priority on the ciphers supported by gnutls.  Priority is
     higher for elements specified before others.  After specifying the
     ciphers you want, you must append a 0.  Note that the priority is
     set on the client. The server does not use the algorithm's
     priority except for disabling algorithms that were not specified.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_cipher_suite_get_name
----------------------------

 -- Function: const char * gnutls_cipher_suite_get_name
          (gnutls_kx_algorithm_t KX_ALGORITHM,
          gnutls_cipher_algorithm_t CIPHER_ALGORITHM,
          gnutls_mac_algorithm_t MAC_ALGORITHM)
     KX_ALGORITHM: is a Key exchange algorithm

     CIPHER_ALGORITHM: is a cipher algorithm

     MAC_ALGORITHM: is a MAC algorithm

     Note that the full cipher suite name must be prepended by TLS or
     SSL depending of the protocol in use.

     *Returns:* a string that contains the name of a TLS cipher suite,
     specified by the given algorithms, or `NULL'.

gnutls_cipher_suite_info
------------------------

 -- Function: const char * gnutls_cipher_suite_info (size_t IDX, char *
          CS_ID, gnutls_kx_algorithm_t * KX, gnutls_cipher_algorithm_t
          * CIPHER, gnutls_mac_algorithm_t * MAC, gnutls_protocol_t *
          MIN_VERSION)
     IDX: index of cipher suite to get information about, starts on 0.

     CS_ID: output buffer with room for 2 bytes, indicating cipher
     suite value

     KX: output variable indicating key exchange algorithm, or `NULL'.

     CIPHER: output variable indicating cipher, or `NULL'.

     MAC: output variable indicating MAC algorithm, or `NULL'.

     Get information about supported cipher suites.  Use the function
     iteratively to get information about all supported cipher suites.
     Call with idx=0 to get information about first cipher suite, then
     idx=1 and so on until the function returns NULL.

     *Returns:* the name of `idx' cipher suite, and set the information
     about the cipher suite in the output variables.  If `idx' is out of
     bounds, `NULL' is returned.

gnutls_compression_get_id
-------------------------

 -- Function: gnutls_compression_method_t gnutls_compression_get_id
          (const char * NAME)
     NAME: is a compression method name

     The names are compared in a case insensitive way.

     *Returns:* an id of the specified in a string compression method,
     or `GNUTLS_COMP_UNKNOWN' on error.

gnutls_compression_get_name
---------------------------

 -- Function: const char * gnutls_compression_get_name
          (gnutls_compression_method_t ALGORITHM)
     ALGORITHM: is a Compression algorithm

     Convert a `gnutls_compression_method_t' value to a string.

     *Returns:* a pointer to a string that contains the name of the
     specified compression algorithm, or `NULL'.

gnutls_compression_get
----------------------

 -- Function: gnutls_compression_method_t gnutls_compression_get
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get currently used compression algorithm.

     *Returns:* the currently used compression method, a
     `gnutls_compression_method_t' value.

gnutls_compression_list
-----------------------

 -- Function: const gnutls_compression_method_t *
gnutls_compression_list ( VOID)
     Get a list of compression methods.  Note that to be able to use LZO
     compression, you must link to libgnutls-extra and call
     `gnutls_global_init_extra()'.

     *Returns:* a zero-terminated list of `gnutls_compression_method_t'
     integers indicating the available compression methods.

gnutls_compression_set_priority
-------------------------------

 -- Function: int gnutls_compression_set_priority (gnutls_session_t
          SESSION, const int * LIST)
     SESSION: is a `gnutls_session_t' structure.

     LIST: is a 0 terminated list of gnutls_compression_method_t
     elements.

     Sets the priority on the compression algorithms supported by
     gnutls.  Priority is higher for elements specified before others.
     After specifying the algorithms you want, you must append a 0.
     Note that the priority is set on the client. The server does not
     use the algorithm's priority except for disabling algorithms that
     were not specified.

     TLS 1.0 does not define any compression algorithms except NULL.
     Other compression algorithms are to be considered as gnutls
     extensions.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_credentials_clear
------------------------

 -- Function: void gnutls_credentials_clear (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Clears all the credentials previously set in this session.

gnutls_credentials_set
----------------------

 -- Function: int gnutls_credentials_set (gnutls_session_t SESSION,
          gnutls_credentials_type_t TYPE, void * CRED)
     SESSION: is a `gnutls_session_t' structure.

     TYPE: is the type of the credentials

     CRED: is a pointer to a structure.

     Sets the needed credentials for the specified type.  Eg username,
     password - or public and private keys etc.  The `cred' parameter is
     a structure that depends on the specified type and on the current
     session (client or server).

     In order to minimize memory usage, and share credentials between
     several threads gnutls keeps a pointer to cred, and not the whole
     cred structure.  Thus you will have to keep the structure allocated
     until you call `gnutls_deinit()'.

     For `GNUTLS_CRD_ANON', `cred' should be
     `gnutls_anon_client_credentials_t' in case of a client.  In case of
     a server it should be `gnutls_anon_server_credentials_t'.

     For `GNUTLS_CRD_SRP', `cred' should be
     `gnutls_srp_client_credentials_t' in case of a client, and
     `gnutls_srp_server_credentials_t', in case of a server.

     For `GNUTLS_CRD_CERTIFICATE', `cred' should be
     `gnutls_certificate_credentials_t'.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_crypto_bigint_register2
------------------------------

 -- Function: int gnutls_crypto_bigint_register2 (int PRIORITY, int
          VERSION, const gnutls_crypto_bigint_st * S)
     PRIORITY: is the priority of the interface

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new interface's data

     This function will register an interface for gnutls to operate on
     big integers. Any interface registered will override the included
     interface. The interface with the lowest priority will be used by
     gnutls.

     Note that the bigint interface must interoperate with the public
     key interface. Thus if this interface is updated the
     `gnutls_crypto_pk_register()' should also be used.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_bigint_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_cipher_register2
------------------------------

 -- Function: int gnutls_crypto_cipher_register2 (int PRIORITY, int
          VERSION, const gnutls_crypto_cipher_st * S)
     PRIORITY: is the priority of the cipher interface

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new interface's data

     This function will register a cipher interface to be used by
     gnutls. Any interface registered will override the included engine
     and by convention kernel implemented interfaces should have
     priority of 90. The interface with the lowest priority will be used
     by gnutls.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_cipher_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_digest_register2
------------------------------

 -- Function: int gnutls_crypto_digest_register2 (int PRIORITY, int
          VERSION, const gnutls_crypto_digest_st * S)
     PRIORITY: is the priority of the digest interface

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new interface's data

     This function will register a digest interface to be used by
     gnutls. Any interface registered will override the included engine
     and by convention kernel implemented interfaces should have
     priority of 90. The interface with the lowest priority will be used
     by gnutls.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_digest_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_mac_register2
---------------------------

 -- Function: int gnutls_crypto_mac_register2 (int PRIORITY, int
          VERSION, const gnutls_crypto_mac_st * S)
     PRIORITY: is the priority of the mac interface

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new interface's data

     This function will register a mac interface to be used by gnutls.
     Any interface registered will override the included engine and by
     convention kernel implemented interfaces should have priority of
     90. The interface with the lowest priority will be used by gnutls.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_digest_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_pk_register2
--------------------------

 -- Function: int gnutls_crypto_pk_register2 (int PRIORITY, int
          VERSION, const gnutls_crypto_pk_st * S)
     PRIORITY: is the priority of the interface

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new interface's data

     This function will register an interface for gnutls to operate on
     public key operations. Any interface registered will override the
     included interface. The interface with the lowest priority will be
     used by gnutls.

     Note that the bigint interface must interoperate with the bigint
     interface. Thus if this interface is updated the
     `gnutls_crypto_bigint_register()' should also be used.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_pk_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_rnd_register2
---------------------------

 -- Function: int gnutls_crypto_rnd_register2 (int PRIORITY, int
          VERSION, const gnutls_crypto_rnd_st * S)
     PRIORITY: is the priority of the generator

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new generator's data

     This function will register a random generator to be used by
     gnutls.  Any generator registered will override the included
     generator and by convention kernel implemented generators have
     priority of 90.  The generator with the lowest priority will be
     used by gnutls.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_rnd_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_single_cipher_register2
-------------------------------------

 -- Function: int gnutls_crypto_single_cipher_register2
          (gnutls_cipher_algorithm_t ALGORITHM, int PRIORITY, int
          VERSION, const gnutls_crypto_cipher_st * S)
     ALGORITHM: is the gnutls algorithm identifier

     PRIORITY: is the priority of the algorithm

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new cipher's data

     This function will register a cipher algorithm to be used by
     gnutls.  Any algorithm registered will override the included
     algorithms and by convention kernel implemented algorithms have
     priority of 90.  The algorithm with the lowest priority will be
     used by gnutls.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_single_cipher_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_single_digest_register2
-------------------------------------

 -- Function: int gnutls_crypto_single_digest_register2
          (gnutls_digest_algorithm_t ALGORITHM, int PRIORITY, int
          VERSION, const gnutls_crypto_digest_st * S)
     ALGORITHM: is the gnutls algorithm identifier

     PRIORITY: is the priority of the algorithm

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new algorithms's data

     This function will register a digest (hash) algorithm to be used by
     gnutls.  Any algorithm registered will override the included
     algorithms and by convention kernel implemented algorithms have
     priority of 90.  The algorithm with the lowest priority will be
     used by gnutls.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_single_digest_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_crypto_single_mac_register2
----------------------------------

 -- Function: int gnutls_crypto_single_mac_register2
          (gnutls_mac_algorithm_t ALGORITHM, int PRIORITY, int VERSION,
          const gnutls_crypto_mac_st * S)
     ALGORITHM: is the gnutls algorithm identifier

     PRIORITY: is the priority of the algorithm

     VERSION: should be set to `GNUTLS_CRYPTO_API_VERSION'

     S: is a structure holding new algorithms's data

     This function will register a MAC algorithm to be used by gnutls.
     Any algorithm registered will override the included algorithms and
     by convention kernel implemented algorithms have priority of 90.
     The algorithm with the lowest priority will be used by gnutls.

     This function should be called before `gnutls_global_init()'.

     For simplicity you can use the convenience
     `gnutls_crypto_single_mac_register()' macro.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.6.0

gnutls_db_check_entry
---------------------

 -- Function: int gnutls_db_check_entry (gnutls_session_t SESSION,
          gnutls_datum_t SESSION_ENTRY)
     SESSION: is a `gnutls_session_t' structure.

     SESSION_ENTRY: is the session data (not key)

     Check if database entry has expired.  This function is to be used
     when you want to clear unnesessary session which occupy space in
     your backend.

     *Returns:* Returns `GNUTLS_E_EXPIRED', if the database entry has
     expired or 0 otherwise.

gnutls_db_get_ptr
-----------------

 -- Function: void * gnutls_db_get_ptr (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get db function pointer.

     *Returns:* the pointer that will be sent to db store, retrieve and
     delete functions, as the first argument.

gnutls_db_remove_session
------------------------

 -- Function: void gnutls_db_remove_session (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function will remove the current session data from the
     session database.  This will prevent future handshakes reusing
     these session data.  This function should be called if a session
     was terminated abnormally, and before `gnutls_deinit()' is called.

     Normally `gnutls_deinit()' will remove abnormally terminated
     sessions.

gnutls_db_set_cache_expiration
------------------------------

 -- Function: void gnutls_db_set_cache_expiration (gnutls_session_t
          SESSION, int SECONDS)
     SESSION: is a `gnutls_session_t' structure.

     SECONDS: is the number of seconds.

     Set the expiration time for resumed sessions. The default is 3600
     (one hour) at the time writing this.

gnutls_db_set_ptr
-----------------

 -- Function: void gnutls_db_set_ptr (gnutls_session_t SESSION, void *
          PTR)
     SESSION: is a `gnutls_session_t' structure.

     PTR: is the pointer

     Sets the pointer that will be provided to db store, retrieve and
     delete functions, as the first argument.

gnutls_db_set_remove_function
-----------------------------

 -- Function: void gnutls_db_set_remove_function (gnutls_session_t
          SESSION, gnutls_db_remove_func REM_FUNC)
     SESSION: is a `gnutls_session_t' structure.

     REM_FUNC: is the function.

     Sets the function that will be used to remove data from the
     resumed sessions database. This function must return 0 on success.

     The first argument to `rem_func' will be null unless
     `gnutls_db_set_ptr()' has been called.

gnutls_db_set_retrieve_function
-------------------------------

 -- Function: void gnutls_db_set_retrieve_function (gnutls_session_t
          SESSION, gnutls_db_retr_func RETR_FUNC)
     SESSION: is a `gnutls_session_t' structure.

     RETR_FUNC: is the function.

     Sets the function that will be used to retrieve data from the
     resumed sessions database.  This function must return a
     gnutls_datum_t containing the data on success, or a gnutls_datum_t
     containing null and 0 on failure.

     The datum's data must be allocated using the function
     `gnutls_malloc()'.

     The first argument to `retr_func' will be null unless
     `gnutls_db_set_ptr()' has been called.

gnutls_db_set_store_function
----------------------------

 -- Function: void gnutls_db_set_store_function (gnutls_session_t
          SESSION, gnutls_db_store_func STORE_FUNC)
     SESSION: is a `gnutls_session_t' structure.

     STORE_FUNC: is the function

     Sets the function that will be used to store data from the resumed
     sessions database. This function must remove 0 on success.

     The first argument to `store_func()' will be null unless
     `gnutls_db_set_ptr()' has been called.

gnutls_deinit
-------------

 -- Function: void gnutls_deinit (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function clears all buffers associated with the `session'.
     This function will also remove session data from the session
     database if the session was terminated abnormally.

gnutls_dh_get_group
-------------------

 -- Function: int gnutls_dh_get_group (gnutls_session_t SESSION,
          gnutls_datum_t * RAW_GEN, gnutls_datum_t * RAW_PRIME)
     SESSION: is a gnutls session

     RAW_GEN: will hold the generator.

     RAW_PRIME: will hold the prime.

     This function will return the group parameters used in the last
     Diffie-Hellman key exchange with the peer.  These are the prime and
     the generator used.  This function should be used for both
     anonymous and ephemeral Diffie-Hellman.  The output parameters must
     be freed with `gnutls_free()'.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_dh_get_peers_public_bits
-------------------------------

 -- Function: int gnutls_dh_get_peers_public_bits (gnutls_session_t
          SESSION)
     SESSION: is a gnutls session

     Get the Diffie-Hellman public key bit size.  Can be used for both
     anonymous and ephemeral Diffie-Hellman.

     *Returns:* the public key bit size used in the last Diffie-Hellman
     key exchange with the peer, or a negative value in case of error.

gnutls_dh_get_prime_bits
------------------------

 -- Function: int gnutls_dh_get_prime_bits (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     This function will return the bits of the prime used in the last
     Diffie-Hellman key exchange with the peer.  Should be used for both
     anonymous and ephemeral Diffie-Hellman.  Note that some ciphers,
     like RSA and DSA without DHE, does not use a Diffie-Hellman key
     exchange, and then this function will return 0.

     *Returns:* The Diffie-Hellman bit strength is returned, or 0 if no
     Diffie-Hellman key exchange was done, or a negative error code on
     failure.

gnutls_dh_get_pubkey
--------------------

 -- Function: int gnutls_dh_get_pubkey (gnutls_session_t SESSION,
          gnutls_datum_t * RAW_KEY)
     SESSION: is a gnutls session

     RAW_KEY: will hold the public key.

     This function will return the peer's public key used in the last
     Diffie-Hellman key exchange.  This function should be used for both
     anonymous and ephemeral Diffie-Hellman.  The output parameters must
     be freed with `gnutls_free()'.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_dh_get_secret_bits
-------------------------

 -- Function: int gnutls_dh_get_secret_bits (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     This function will return the bits used in the last Diffie-Hellman
     key exchange with the peer.  Should be used for both anonymous and
     ephemeral Diffie-Hellman.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_dh_params_cpy
--------------------

 -- Function: int gnutls_dh_params_cpy (gnutls_dh_params_t DST,
          gnutls_dh_params_t SRC)
     DST: Is the destination structure, which should be initialized.

     SRC: Is the source structure

     This function will copy the DH parameters structure from source to
     destination.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_dh_params_deinit
-----------------------

 -- Function: void gnutls_dh_params_deinit (gnutls_dh_params_t
          DH_PARAMS)
     DH_PARAMS: Is a structure that holds the prime numbers

     This function will deinitialize the DH parameters structure.

gnutls_dh_params_export_pkcs3
-----------------------------

 -- Function: int gnutls_dh_params_export_pkcs3 (gnutls_dh_params_t
          PARAMS, gnutls_x509_crt_fmt_t FORMAT, unsigned char *
          PARAMS_DATA, size_t * PARAMS_DATA_SIZE)
     PARAMS: Holds the DH parameters

     FORMAT: the format of output params. One of PEM or DER.

     PARAMS_DATA: will contain a PKCS3 DHParams structure PEM or DER
     encoded

     PARAMS_DATA_SIZE: holds the size of params_data (and will be
     replaced by the actual size of parameters)

     This function will export the given dh parameters to a PKCS3
     DHParams structure. This is the format generated by "openssl
     dhparam" tool.  If the buffer provided is not long enough to hold
     the output, then GNUTLS_E_SHORT_MEMORY_BUFFER will be returned.

     If the structure is PEM encoded, it will have a header of "BEGIN
     DH PARAMETERS".

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_dh_params_export_raw
---------------------------

 -- Function: int gnutls_dh_params_export_raw (gnutls_dh_params_t
          PARAMS, gnutls_datum_t * PRIME, gnutls_datum_t * GENERATOR,
          unsigned int * BITS)
     PARAMS: Holds the DH parameters

     PRIME: will hold the new prime

     GENERATOR: will hold the new generator

     BITS: if non null will hold is the prime's number of bits

     This function will export the pair of prime and generator for use
     in the Diffie-Hellman key exchange.  The new parameters will be
     allocated using `gnutls_malloc()' and will be stored in the
     appropriate datum.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_dh_params_generate2
--------------------------

 -- Function: int gnutls_dh_params_generate2 (gnutls_dh_params_t
          PARAMS, unsigned int BITS)
     PARAMS: Is the structure that the DH parameters will be stored

     BITS: is the prime's number of bits

     This function will generate a new pair of prime and generator for
     use in the Diffie-Hellman key exchange. The new parameters will be
     allocated using `gnutls_malloc()' and will be stored in the
     appropriate datum.  This function is normally slow.

     Do not set the number of bits directly, use
     `gnutls_sec_param_to_pk_bits()' to get bits for `GNUTLS_PK_DSA'.
     Also note that the DH parameters are only useful to servers.
     Since clients use the parameters sent by the server, it's of no
     use to call this in client side.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_dh_params_import_pkcs3
-----------------------------

 -- Function: int gnutls_dh_params_import_pkcs3 (gnutls_dh_params_t
          PARAMS, const gnutls_datum_t * PKCS3_PARAMS,
          gnutls_x509_crt_fmt_t FORMAT)
     PARAMS: A structure where the parameters will be copied to

     PKCS3_PARAMS: should contain a PKCS3 DHParams structure PEM or DER
     encoded

     FORMAT: the format of params. PEM or DER.

     This function will extract the DHParams found in a PKCS3 formatted
     structure. This is the format generated by "openssl dhparam" tool.

     If the structure is PEM encoded, it should have a header of "BEGIN
     DH PARAMETERS".

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_dh_params_import_raw
---------------------------

 -- Function: int gnutls_dh_params_import_raw (gnutls_dh_params_t
          DH_PARAMS, const gnutls_datum_t * PRIME, const gnutls_datum_t
          * GENERATOR)
     DH_PARAMS: Is a structure that will hold the prime numbers

     PRIME: holds the new prime

     GENERATOR: holds the new generator

     This function will replace the pair of prime and generator for use
     in the Diffie-Hellman key exchange.  The new parameters should be
     stored in the appropriate gnutls_datum.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_dh_params_init
---------------------

 -- Function: int gnutls_dh_params_init (gnutls_dh_params_t * DH_PARAMS)
     DH_PARAMS: Is a structure that will hold the prime numbers

     This function will initialize the DH parameters structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_dh_set_prime_bits
------------------------

 -- Function: void gnutls_dh_set_prime_bits (gnutls_session_t SESSION,
          unsigned int BITS)
     SESSION: is a `gnutls_session_t' structure.

     BITS: is the number of bits

     This function sets the number of bits, for use in an Diffie-Hellman
     key exchange.  This is used both in DH ephemeral and DH anonymous
     cipher suites.  This will set the minimum size of the prime that
     will be used for the handshake.

     In the client side it sets the minimum accepted number of bits.  If
     a server sends a prime with less bits than that
     `GNUTLS_E_DH_PRIME_UNACCEPTABLE' will be returned by the handshake.

     This function has no effect in server side.

gnutls_error_is_fatal
---------------------

 -- Function: int gnutls_error_is_fatal (int ERROR)
     ERROR: is a GnuTLS error code, a negative value

     If a GnuTLS function returns a negative value you may feed that
     value to this function to see if the error condition is fatal.

     Note that you may want to check the error code manually, since some
     non-fatal errors to the protocol may be fatal for you program.

     This function is only useful if you are dealing with errors from
     the record layer or the handshake layer.

     *Returns:* 1 if the error code is fatal, for positive `error'
     values, 0 is returned.  For unknown `error' values, -1 is returned.

gnutls_error_to_alert
---------------------

 -- Function: int gnutls_error_to_alert (int ERR, int * LEVEL)
     ERR: is a negative integer

     LEVEL: the alert level will be stored there

     Get an alert depending on the error code returned by a gnutls
     function.  All alerts sent by this function should be considered
     fatal.  The only exception is when `err' is `GNUTLS_E_REHANDSHAKE',
     where a warning alert should be sent to the peer indicating that no
     renegotiation will be performed.

     If there is no mapping to a valid alert the alert to indicate
     internal error is returned.

     *Returns:* the alert code to use for a particular error code.

gnutls_ext_register
-------------------

 -- Function: int gnutls_ext_register (int TYPE, const char * NAME,
          gnutls_ext_parse_type_t PARSE_TYPE, gnutls_ext_recv_func
          RECV_FUNC, gnutls_ext_send_func SEND_FUNC)
     TYPE: the 16-bit integer referring to the extension type

     NAME: human printable name of the extension used for debugging

     PARSE_TYPE: either `GNUTLS_EXT_TLS' or `GNUTLS_EXT_APPLICATION'.

     RECV_FUNC: a function to receive extension data

     SEND_FUNC: a function to send extension data

     This function is used to register a new TLS extension handler.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

     *Deprecated in:* 2.12.0

gnutls_fingerprint
------------------

 -- Function: int gnutls_fingerprint (gnutls_digest_algorithm_t ALGO,
          const gnutls_datum_t * DATA, void * RESULT, size_t *
          RESULT_SIZE)
     ALGO: is a digest algorithm

     DATA: is the data

     RESULT: is the place where the result will be copied (may be null).

     RESULT_SIZE: should hold the size of the result. The actual size
     of the returned result will also be copied there.

     This function will calculate a fingerprint (actually a hash), of
     the given data.  The result is not printable data.  You should
     convert it to hex, or to something else printable.

     This is the usual way to calculate a fingerprint of an X.509 DER
     encoded certificate.  Note however that the fingerprint of an
     OpenPGP is not just a hash and cannot be calculated with this
     function.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_free
-----------

 -- Function: void gnutls_free (void * PTR)
     This function will free data pointed by ptr.

     The deallocation function used is the one set by
     `gnutls_global_set_mem_functions()'.

gnutls_global_deinit
--------------------

 -- Function: void gnutls_global_deinit ( VOID)
     This function deinitializes the global data, that were initialized
     using `gnutls_global_init()'.

     Note!  This function is not thread safe.  See the discussion for
     `gnutls_global_init()' for more information.

gnutls_global_init
------------------

 -- Function: int gnutls_global_init ( VOID)
     This function initializes the global data to defaults.  Every
     gnutls application has a global data which holds common parameters
     shared by gnutls session structures.  You should call
     `gnutls_global_deinit()' when gnutls usage is no longer needed

     Note that this function will also initialize the underlying crypto
     backend, if it has not been initialized before.

     This function increment a global counter, so that
     `gnutls_global_deinit()' only releases resources when it has been
     called as many times as `gnutls_global_init()'.  This is useful
     when GnuTLS is used by more than one library in an application.
     This function can be called many times, but will only do something
     the first time.

     Note!  This function is not thread safe.  If two threads call this
     function simultaneously, they can cause a race between checking
     the global counter and incrementing it, causing both threads to
     execute the library initialization code.  That would lead to a
     memory leak.  To handle this, your application could invoke this
     function after aquiring a thread mutex.  To ignore the potential
     memory leak is also an option.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_global_set_log_function
------------------------------

 -- Function: void gnutls_global_set_log_function (gnutls_log_func
          LOG_FUNC)
     LOG_FUNC: it's a log function

     This is the function where you set the logging function gnutls is
     going to use.  This function only accepts a character array.
     Normally you may not use this function since it is only used for
     debugging purposes.

     gnutls_log_func is of the form, void (*gnutls_log_func)( int
     level, const char*);

gnutls_global_set_log_level
---------------------------

 -- Function: void gnutls_global_set_log_level (int LEVEL)
     LEVEL: it's an integer from 0 to 9.

     This is the function that allows you to set the log level.  The
     level is an integer between 0 and 9.  Higher values mean more
     verbosity. The default value is 0.  Larger values should only be
     used with care, since they may reveal sensitive information.

     Use a log level over 10 to enable all debugging options.

gnutls_global_set_mem_functions
-------------------------------

 -- Function: void gnutls_global_set_mem_functions
          (gnutls_alloc_function ALLOC_FUNC, gnutls_alloc_function
          SECURE_ALLOC_FUNC, gnutls_is_secure_function IS_SECURE_FUNC,
          gnutls_realloc_function REALLOC_FUNC, gnutls_free_function
          FREE_FUNC)
     ALLOC_FUNC: it's the default memory allocation function. Like
     `malloc()'.

     SECURE_ALLOC_FUNC: This is the memory allocation function that
     will be used for sensitive data.

     IS_SECURE_FUNC: a function that returns 0 if the memory given is
     not secure. May be NULL.

     REALLOC_FUNC: A realloc function

     FREE_FUNC: The function that frees allocated data. Must accept a
     NULL pointer.

     This is the function were you set the memory allocation functions
     gnutls is going to use. By default the libc's allocation functions
     (`malloc()', `free()'), are used by gnutls, to allocate both
     sensitive and not sensitive data.  This function is provided to
     set the memory allocation functions to something other than the
     defaults

     This function must be called before `gnutls_global_init()' is
     called.  This function is not thread safe.

gnutls_global_set_mutex
-----------------------

 -- Function: void gnutls_global_set_mutex (mutex_init_func INIT,
          mutex_deinit_func DEINIT, mutex_lock_func LOCK,
          mutex_unlock_func UNLOCK)
     INIT: mutex initialization function

     DEINIT: mutex deinitialization function

     LOCK: mutex locking function

     UNLOCK: mutex unlocking function

     With this function you are allowed to override the default mutex
     locks used in some parts of gnutls and dependent libraries. This
     function should be used if you have complete control of your
     program and libraries.  Do not call this function from a library.
     Instead only initialize gnutls and the default OS mutex locks will
     be used.

     This function must be called before `gnutls_global_init()'.

gnutls_global_set_time_function
-------------------------------

 -- Function: void gnutls_global_set_time_function (gnutls_time_func
          TIME_FUNC)
     TIME_FUNC: it's the system time function

     This is the function where you can override the default system
     time function.

     gnutls_time_func is of the form, time_t (*gnutls_time_func)(
     time*);

gnutls_handshake_get_last_in
----------------------------

 -- Function: gnutls_handshake_description_t
gnutls_handshake_get_last_in (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function is only useful to check where the last performed
     handshake failed.  If the previous handshake succeed or was not
     performed at all then no meaningful value will be returned.

     Check `gnutls_handshake_description_t' in gnutls.h for the
     available handshake descriptions.

     *Returns:* the last handshake message type received, a
     `gnutls_handshake_description_t'.

gnutls_handshake_get_last_out
-----------------------------

 -- Function: gnutls_handshake_description_t
gnutls_handshake_get_last_out (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function is only useful to check where the last performed
     handshake failed.  If the previous handshake succeed or was not
     performed at all then no meaningful value will be returned.

     Check `gnutls_handshake_description_t' in gnutls.h for the
     available handshake descriptions.

     *Returns:* the last handshake message type sent, a
     `gnutls_handshake_description_t'.

gnutls_handshake_set_max_packet_length
--------------------------------------

 -- Function: void gnutls_handshake_set_max_packet_length
          (gnutls_session_t SESSION, size_t MAX)
     SESSION: is a `gnutls_session_t' structure.

     MAX: is the maximum number.

     This function will set the maximum size of all handshake messages.
     Handshakes over this size are rejected with
     `GNUTLS_E_HANDSHAKE_TOO_LARGE' error code.  The default value is
     48kb which is typically large enough.  Set this to 0 if you do not
     want to set an upper limit.

     The reason for restricting the handshake message sizes are to
     limit Denial of Service attacks.

gnutls_handshake_set_post_client_hello_function
-----------------------------------------------

 -- Function: void gnutls_handshake_set_post_client_hello_function
          (gnutls_session_t SESSION,
          gnutls_handshake_post_client_hello_func FUNC)
     SESSION: is a `gnutls_session_t' structure.

     FUNC: is the function to be called

     This function will set a callback to be called after the client
     hello has been received (callback valid in server side only). This
     allows the server to adjust settings based on received extensions.

     Those settings could be ciphersuites, requesting certificate, or
     anything else except for version negotiation (this is done before
     the hello message is parsed).

     This callback must return 0 on success or a gnutls error code to
     terminate the handshake.

     *Warning:* You should not use this function to terminate the
     handshake based on client input unless you know what you are
     doing. Before the handshake is finished there is no way to know if
     there is a man-in-the-middle attack being performed.

gnutls_handshake_set_private_extensions
---------------------------------------

 -- Function: void gnutls_handshake_set_private_extensions
          (gnutls_session_t SESSION, int ALLOW)
     SESSION: is a `gnutls_session_t' structure.

     ALLOW: is an integer (0 or 1)

     This function will enable or disable the use of private cipher
     suites (the ones that start with 0xFF).  By default or if `allow'
     is 0 then these cipher suites will not be advertized nor used.

     Unless this function is called with the option to allow (1), then
     no compression algorithms, like LZO.  That is because these
     algorithms are not yet defined in any RFC or even internet draft.

     Enabling the private ciphersuites when talking to other than
     gnutls servers and clients may cause interoperability problems.

gnutls_handshake
----------------

 -- Function: int gnutls_handshake (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function does the handshake of the TLS/SSL protocol, and
     initializes the TLS connection.

     This function will fail if any problem is encountered, and will
     return a negative error code. In case of a client, if the client
     has asked to resume a session, but the server couldn't, then a
     full handshake will be performed.

     The non-fatal errors such as `GNUTLS_E_AGAIN' and
     `GNUTLS_E_INTERRUPTED' interrupt the handshake procedure, which
     should be later be resumed.  Call this function again, until it
     returns 0; cf.  `gnutls_record_get_direction()' and
     `gnutls_error_is_fatal()'.

     If this function is called by a server after a rehandshake request
     then `GNUTLS_E_GOT_APPLICATION_DATA' or
     `GNUTLS_E_WARNING_ALERT_RECEIVED' may be returned.  Note that these
     are non fatal errors, only in the specific case of a rehandshake.
     Their meaning is that the client rejected the rehandshake request
     or in the case of `GNUTLS_E_GOT_APPLICATION_DATA' it might also
     mean that some data were pending.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

gnutls_hash_deinit
------------------

 -- Function: void gnutls_hash_deinit (gnutls_hash_hd_t HANDLE, void *
          DIGEST)
     HANDLE: is a `gnutls_hash_hd_t' structure.

     DIGEST: is the output value of the hash

     This function will deinitialize all resources occupied by the
     given hash context.

     *Since:* 2.10.0

gnutls_hash_fast
----------------

 -- Function: int gnutls_hash_fast (gnutls_digest_algorithm_t
          ALGORITHM, const void * TEXT, size_t TEXTLEN, void * DIGEST)
     ALGORITHM: the hash algorithm to use

     TEXT: the data to hash

     TEXTLEN: The length of data to hash

     DIGEST: is the output value of the hash

     This convenience function will hash the given data and return
     output on a single call.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_hash_get_len
-------------------

 -- Function: int gnutls_hash_get_len (gnutls_digest_algorithm_t
          ALGORITHM)
     ALGORITHM: the hash algorithm to use

     This function will return the length of the output data of the
     given hash algorithm.

     *Returns:* The length or zero on error.

     *Since:* 2.10.0

gnutls_hash_init
----------------

 -- Function: int gnutls_hash_init (gnutls_hash_hd_t * DIG,
          gnutls_digest_algorithm_t ALGORITHM)
     DIG: is a `gnutls_hash_hd_t' structure.

     ALGORITHM: the hash algorithm to use

     This function will initialize an context that can be used to
     produce a Message Digest of data.  This will effectively use the
     current crypto backend in use by gnutls or the cryptographic
     accelerator in use.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_hash_output
------------------

 -- Function: void gnutls_hash_output (gnutls_hash_hd_t HANDLE, void *
          DIGEST)
     HANDLE: is a `gnutls_hash_hd_t' structure.

     DIGEST: is the output value of the hash

     This function will output the current hash value.

     *Since:* 2.10.0

gnutls_hash
-----------

 -- Function: int gnutls_hash (gnutls_hash_hd_t HANDLE, const void *
          TEXT, size_t TEXTLEN)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     TEXT: the data to hash

     TEXTLEN: The length of data to hash

     This function will hash the given data using the algorithm
     specified by the context.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_hex2bin
--------------

 -- Function: int gnutls_hex2bin (const char * HEX_DATA, size_t
          HEX_SIZE, char * BIN_DATA, size_t * BIN_SIZE)
     HEX_DATA: string with data in hex format

     HEX_SIZE: size of hex data

     BIN_DATA: output array with binary data

     BIN_SIZE: when calling *`bin_size' should hold size of `bin_data',
     on return will hold actual size of `bin_data'.

     Convert a buffer with hex data to binary data.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

     *Since:* 2.4.0

gnutls_hex_decode
-----------------

 -- Function: int gnutls_hex_decode (const gnutls_datum_t * HEX_DATA,
          char * RESULT, size_t * RESULT_SIZE)
     HEX_DATA: contain the encoded data

     RESULT: the place where decoded data will be copied

     RESULT_SIZE: holds the size of the result

     This function will decode the given encoded data, using the hex
     encoding used by PSK password files.

     Note that hex_data should be null terminated.

     *Returns:* `GNUTLS_E_SHORT_MEMORY_BUFFER' if the buffer given is
     not long enough, or 0 on success.

gnutls_hex_encode
-----------------

 -- Function: int gnutls_hex_encode (const gnutls_datum_t * DATA, char
          * RESULT, size_t * RESULT_SIZE)
     DATA: contain the raw data

     RESULT: the place where hex data will be copied

     RESULT_SIZE: holds the size of the result

     This function will convert the given data to printable data, using
     the hex encoding, as used in the PSK password files.

     *Returns:* `GNUTLS_E_SHORT_MEMORY_BUFFER' if the buffer given is
     not long enough, or 0 on success.

gnutls_hmac_deinit
------------------

 -- Function: void gnutls_hmac_deinit (gnutls_hmac_hd_t HANDLE, void *
          DIGEST)
     HANDLE: is a `gnutls_hmac_hd_t' structure.

     DIGEST: is the output value of the MAC

     This function will deinitialize all resources occupied by the
     given hmac context.

     *Since:* 2.10.0

gnutls_hmac_fast
----------------

 -- Function: int gnutls_hmac_fast (gnutls_mac_algorithm_t ALGORITHM,
          const void * KEY, size_t KEYLEN, const void * TEXT, size_t
          TEXTLEN, void * DIGEST)
     ALGORITHM: the hash algorithm to use

     KEY: the key to use

     KEYLEN: The length of the key

     TEXT: the data to hash

     TEXTLEN: The length of data to hash

     DIGEST: is the output value of the hash

     This convenience function will hash the given data and return
     output on a single call.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_hmac_get_len
-------------------

 -- Function: int gnutls_hmac_get_len (gnutls_mac_algorithm_t ALGORITHM)
     ALGORITHM: the hmac algorithm to use

     This function will return the length of the output data of the
     given hmac algorithm.

     *Returns:* The length or zero on error.

     *Since:* 2.10.0

gnutls_hmac_init
----------------

 -- Function: int gnutls_hmac_init (gnutls_hmac_hd_t * DIG,
          gnutls_digest_algorithm_t ALGORITHM, const void * KEY, size_t
          KEYLEN)
     DIG: is a `gnutls_hmac_hd_t' structure.

     ALGORITHM: the HMAC algorithm to use

     KEY: The key to be used for encryption

     KEYLEN: The length of the key

     This function will initialize an context that can be used to
     produce a Message Authentication Code (MAC) of data.  This will
     effectively use the current crypto backend in use by gnutls or the
     cryptographic accelerator in use.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_hmac_output
------------------

 -- Function: void gnutls_hmac_output (gnutls_hmac_hd_t HANDLE, void *
          DIGEST)
     HANDLE: is a `gnutls_hmac_hd_t' structure.

     DIGEST: is the output value of the MAC

     This function will output the current MAC value.

     *Since:* 2.10.0

gnutls_hmac
-----------

 -- Function: int gnutls_hmac (gnutls_hmac_hd_t HANDLE, const void *
          TEXT, size_t TEXTLEN)
     HANDLE: is a `gnutls_cipher_hd_t' structure.

     TEXT: the data to hash

     TEXTLEN: The length of data to hash

     This function will hash the given data using the algorithm
     specified by the context.

     *Returns:* Zero or a negative value on error.

     *Since:* 2.10.0

gnutls_init
-----------

 -- Function: int gnutls_init (gnutls_session_t * SESSION,
          gnutls_connection_end_t CON_END)
     SESSION: is a pointer to a `gnutls_session_t' structure.

     CON_END: indicate if this session is to be used for server or
     client.

     This function initializes the current session to null. Every
     session must be initialized before use, so internal structures can
     be allocated.  This function allocates structures which can only
     be free'd by calling `gnutls_deinit()'.  Returns zero on success.

     `con_end' can be one of `GNUTLS_CLIENT' and `GNUTLS_SERVER'.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_kx_get_id
----------------

 -- Function: gnutls_kx_algorithm_t gnutls_kx_get_id (const char * NAME)
     NAME: is a KX name

     Convert a string to a `gnutls_kx_algorithm_t' value.  The names are
     compared in a case insensitive way.

     *Returns:* an id of the specified KX algorithm, or
     `GNUTLS_KX_UNKNOWN' on error.

gnutls_kx_get_name
------------------

 -- Function: const char * gnutls_kx_get_name (gnutls_kx_algorithm_t
          ALGORITHM)
     ALGORITHM: is a key exchange algorithm

     Convert a `gnutls_kx_algorithm_t' value to a string.

     *Returns:* a pointer to a string that contains the name of the
     specified key exchange algorithm, or `NULL'.

gnutls_kx_get
-------------

 -- Function: gnutls_kx_algorithm_t gnutls_kx_get (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get currently used key exchange algorithm.

     *Returns:* the key exchange algorithm used in the last handshake, a
     `gnutls_kx_algorithm_t' value.

gnutls_kx_list
--------------

 -- Function: const gnutls_kx_algorithm_t * gnutls_kx_list ( VOID)
     Get a list of supported key exchange algorithms.

     *Returns:* a zero-terminated list of `gnutls_kx_algorithm_t'
     integers indicating the available key exchange algorithms.

gnutls_kx_set_priority
----------------------

 -- Function: int gnutls_kx_set_priority (gnutls_session_t SESSION,
          const int * LIST)
     SESSION: is a `gnutls_session_t' structure.

     LIST: is a 0 terminated list of gnutls_kx_algorithm_t elements.

     Sets the priority on the key exchange algorithms supported by
     gnutls.  Priority is higher for elements specified before others.
     After specifying the algorithms you want, you must append a 0.
     Note that the priority is set on the client. The server does not
     use the algorithm's priority except for disabling algorithms that
     were not specified.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_mac_get_id
-----------------

 -- Function: gnutls_mac_algorithm_t gnutls_mac_get_id (const char *
          NAME)
     NAME: is a MAC algorithm name

     Convert a string to a `gnutls_mac_algorithm_t' value.  The names
     are compared in a case insensitive way.

     *Returns:* a `gnutls_mac_algorithm_t' id of the specified MAC
     algorithm string, or `GNUTLS_MAC_UNKNOWN' on failures.

gnutls_mac_get_key_size
-----------------------

 -- Function: size_t gnutls_mac_get_key_size (gnutls_mac_algorithm_t
          ALGORITHM)
     ALGORITHM: is an encryption algorithm

     Get size of MAC key.

     *Returns:* length (in bytes) of the given MAC key size, or 0 if the
     given MAC algorithm is invalid.

gnutls_mac_get_name
-------------------

 -- Function: const char * gnutls_mac_get_name (gnutls_mac_algorithm_t
          ALGORITHM)
     ALGORITHM: is a MAC algorithm

     Convert a `gnutls_mac_algorithm_t' value to a string.

     *Returns:* a string that contains the name of the specified MAC
     algorithm, or `NULL'.

gnutls_mac_get
--------------

 -- Function: gnutls_mac_algorithm_t gnutls_mac_get (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get currently used MAC algorithm.

     *Returns:* the currently used mac algorithm, a
     `gnutls_mac_algorithm_t' value.

gnutls_mac_list
---------------

 -- Function: const gnutls_mac_algorithm_t * gnutls_mac_list ( VOID)
     Get a list of hash algorithms for use as MACs.  Note that not
     necessarily all MACs are supported in TLS cipher suites.  For
     example, MD2 is not supported as a cipher suite, but is supported
     for other purposes (e.g., X.509 signature verification or similar).

     *Returns:* Return a zero-terminated list of
     `gnutls_mac_algorithm_t' integers indicating the available MACs.

gnutls_mac_set_priority
-----------------------

 -- Function: int gnutls_mac_set_priority (gnutls_session_t SESSION,
          const int * LIST)
     SESSION: is a `gnutls_session_t' structure.

     LIST: is a 0 terminated list of gnutls_mac_algorithm_t elements.

     Sets the priority on the mac algorithms supported by gnutls.
     Priority is higher for elements specified before others.  After
     specifying the algorithms you want, you must append a 0.  Note
     that the priority is set on the client. The server does not use
     the algorithm's priority except for disabling algorithms that were
     not specified.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_malloc
-------------

 -- Function: void * gnutls_malloc (size_t S)
     This function will allocate 's' bytes data, and return a pointer
     to memory. This function is supposed to be used by callbacks.

     The allocation function used is the one set by
     `gnutls_global_set_mem_functions()'.

gnutls_openpgp_send_cert
------------------------

 -- Function: void gnutls_openpgp_send_cert (gnutls_session_t SESSION,
          gnutls_openpgp_crt_status_t STATUS)
     SESSION: is a pointer to a `gnutls_session_t' structure.

     STATUS: is one of GNUTLS_OPENPGP_CERT, or
     GNUTLS_OPENPGP_CERT_FINGERPRINT

     This function will order gnutls to send the key fingerprint
     instead of the key in the initial handshake procedure. This should
     be used with care and only when there is indication or knowledge
     that the server can obtain the client's key.

gnutls_pem_base64_decode_alloc
------------------------------

 -- Function: int gnutls_pem_base64_decode_alloc (const char * HEADER,
          const gnutls_datum_t * B64_DATA, gnutls_datum_t * RESULT)
     HEADER: The PEM header (eg. CERTIFICATE)

     B64_DATA: contains the encoded data

     RESULT: the place where decoded data lie

     This function will decode the given encoded data. The decoded data
     will be allocated, and stored into result.  If the header given is
     non null this function will search for "----BEGIN header" and
     decode only this part. Otherwise it will decode the first PEM
     packet found.

     You should use `gnutls_free()' to free the returned data.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_pem_base64_decode
------------------------

 -- Function: int gnutls_pem_base64_decode (const char * HEADER, const
          gnutls_datum_t * B64_DATA, unsigned char * RESULT, size_t *
          RESULT_SIZE)
     HEADER: A null terminated string with the PEM header (eg.
     CERTIFICATE)

     B64_DATA: contain the encoded data

     RESULT: the place where decoded data will be copied

     RESULT_SIZE: holds the size of the result

     This function will decode the given encoded data.  If the header
     given is non null this function will search for "----BEGIN header"
     and decode only this part.  Otherwise it will decode the first PEM
     packet found.

     *Returns:* On success `GNUTLS_E_SUCCESS' (0) is returned,
     `GNUTLS_E_SHORT_MEMORY_BUFFER' is returned if the buffer given is
     not long enough, or 0 on success.

gnutls_pem_base64_encode_alloc
------------------------------

 -- Function: int gnutls_pem_base64_encode_alloc (const char * MSG,
          const gnutls_datum_t * DATA, gnutls_datum_t * RESULT)
     MSG: is a message to be put in the encoded header

     DATA: contains the raw data

     RESULT: will hold the newly allocated encoded data

     This function will convert the given data to printable data, using
     the base64 encoding.  This is the encoding used in PEM messages.
     This function will allocate the required memory to hold the encoded
     data.

     You should use `gnutls_free()' to free the returned data.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_pem_base64_encode
------------------------

 -- Function: int gnutls_pem_base64_encode (const char * MSG, const
          gnutls_datum_t * DATA, char * RESULT, size_t * RESULT_SIZE)
     MSG: is a message to be put in the header

     DATA: contain the raw data

     RESULT: the place where base64 data will be copied

     RESULT_SIZE: holds the size of the result

     This function will convert the given data to printable data, using
     the base64 encoding. This is the encoding used in PEM messages.

     The output string will be null terminated, although the size will
     not include the terminating null.

     *Returns:* On success `GNUTLS_E_SUCCESS' (0) is returned,
     `GNUTLS_E_SHORT_MEMORY_BUFFER' is returned if the buffer given is
     not long enough, or 0 on success.

gnutls_perror
-------------

 -- Function: void gnutls_perror (int ERROR)
     ERROR: is a GnuTLS error code, a negative value

     This function is like `perror()'. The only difference is that it
     accepts an error number returned by a gnutls function.

gnutls_pk_algorithm_get_name
----------------------------

 -- Function: const char * gnutls_pk_algorithm_get_name
          (gnutls_pk_algorithm_t ALGORITHM)
     ALGORITHM: is a pk algorithm

     Convert a `gnutls_pk_algorithm_t' value to a string.

     *Returns:* a string that contains the name of the specified public
     key algorithm, or `NULL'.

gnutls_pk_bits_to_sec_param
---------------------------

 -- Function: gnutls_sec_param_t gnutls_pk_bits_to_sec_param
          (gnutls_pk_algorithm_t ALGO, unsigned int BITS)
     ALGO: is a public key algorithm

     BITS: is the number of bits

     This is the inverse of `gnutls_sec_param_to_pk_bits()'. Given an
     algorithm and the number of bits, it will return the security
     parameter. This is a rough indication.

     *Returns:* The security parameter.

gnutls_pk_get_id
----------------

 -- Function: gnutls_pk_algorithm_t gnutls_pk_get_id (const char * NAME)
     NAME: is a string containing a public key algorithm name.

     Convert a string to a `gnutls_pk_algorithm_t' value.  The names are
     compared in a case insensitive way.  For example,
     gnutls_pk_get_id("RSA") will return `GNUTLS_PK_RSA'.

     *Returns:* a `gnutls_pk_algorithm_t' id of the specified public key
     algorithm string, or `GNUTLS_PK_UNKNOWN' on failures.

     *Since:* 2.6.0

gnutls_pk_get_name
------------------

 -- Function: const char * gnutls_pk_get_name (gnutls_pk_algorithm_t
          ALGORITHM)
     ALGORITHM: is a public key algorithm

     Convert a `gnutls_pk_algorithm_t' value to a string.

     *Returns:* a pointer to a string that contains the name of the
     specified public key algorithm, or `NULL'.

     *Since:* 2.6.0

gnutls_pk_list
--------------

 -- Function: const gnutls_pk_algorithm_t * gnutls_pk_list ( VOID)
     Get a list of supported public key algorithms.

     *Returns:* a zero-terminated list of `gnutls_pk_algorithm_t'
     integers indicating the available ciphers.

     *Since:* 2.6.0

gnutls_pkcs11_add_provider
--------------------------

 -- Function: int gnutls_pkcs11_add_provider (const char * NAME, const
          char * PARAMS)
     NAME: The filename of the module

     PARAMS: should be NULL

     This function will load and add a PKCS 11 module to the module
     list used in gnutls. After this function is called the module will
     be used for PKCS 11 operations.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_copy_secret_key
-----------------------------

 -- Function: int gnutls_pkcs11_copy_secret_key (const char *
          TOKEN_URL, gnutls_datum_t * KEY, const char * LABEL, unsigned
          int KEY_USAGE, unsigned int FLAGS)
     TOKEN_URL: A PKCS `11' URL specifying a token

     KEY: The raw key

     LABEL: A name to be used for the stored data

     KEY_USAGE: One of GNUTLS_KEY_*

     FLAGS: One of GNUTLS_PKCS11_OBJ_FLAG_*

     This function will copy a raw secret (symmetric) key into a PKCS
     `11' token specified by a URL. The key can be marked as sensitive
     or not.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_copy_x509_crt
---------------------------

 -- Function: int gnutls_pkcs11_copy_x509_crt (const char * TOKEN_URL,
          gnutls_x509_crt_t CRT, const char * LABEL, unsigned int FLAGS)
     TOKEN_URL: A PKCS `11' URL specifying a token

     CRT: A certificate

     LABEL: A name to be used for the stored data

     FLAGS: One of GNUTLS_PKCS11_OBJ_FLAG_*

     This function will copy a certificate into a PKCS `11' token
     specified by a URL. The certificate can be marked as trusted or
     not.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_copy_x509_privkey
-------------------------------

 -- Function: int gnutls_pkcs11_copy_x509_privkey (const char *
          TOKEN_URL, gnutls_x509_privkey_t KEY, const char * LABEL,
          unsigned int KEY_USAGE, unsigned int FLAGS)
     TOKEN_URL: A PKCS `11' URL specifying a token

     KEY: A private key

     LABEL: A name to be used for the stored data

     KEY_USAGE: One of GNUTLS_KEY_*

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will copy a private key into a PKCS `11' token
     specified by a URL. It is highly recommended flags to contain
     `GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE' unless there is a strong
     reason not to.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_deinit
--------------------

 -- Function: void gnutls_pkcs11_deinit ( VOID)
     This function will deinitialize the PKCS 11 subsystem in gnutls.

gnutls_pkcs11_delete_url
------------------------

 -- Function: int gnutls_pkcs11_delete_url (const char * OBJECT_URL,
          unsigned int FLAGS)
     OBJECT_URL: The URL of the object to delete.

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will delete objects matching the given URL.

     *Returns:* On success, the number of objects deleted is returned,
     otherwise a negative error value.

gnutls_pkcs11_init
------------------

 -- Function: int gnutls_pkcs11_init (unsigned int FLAGS, const char *
          DEPRECATED_CONFIG_FILE)
     FLAGS: `GNUTLS_PKCS11_FLAG_MANUAL' or `GNUTLS_PKCS11_FLAG_AUTO'

     DEPRECATED_CONFIG_FILE: either NULL or the location of a deprecated
     configuration file

     This function will initialize the PKCS 11 subsystem in gnutls. It
     will read configuration files if `GNUTLS_PKCS11_FLAG_AUTO' is used
     or allow you to independently load PKCS 11 modules using
     `gnutls_pkcs11_add_provider()' if `GNUTLS_PKCS11_FLAG_MANUAL' is
     specified.

     Using a custom configfile is deprecated and will not be supported
     in future versions of gnutls.

     Normally you don't need to call this function since it is being
     called by `gnutls_global_init()' using the
     `GNUTLS_PKCS11_FLAG_AUTO'. If you need to call this function, you
     must call it before `gnutls_global_init()'.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_obj_deinit
------------------------

 -- Function: void gnutls_pkcs11_obj_deinit (gnutls_pkcs11_obj_t OBJ)
     OBJ: The structure to be initialized

     This function will deinitialize a certificate structure.

gnutls_pkcs11_obj_export_url
----------------------------

 -- Function: int gnutls_pkcs11_obj_export_url (gnutls_pkcs11_obj_t
          OBJ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)
     OBJ: Holds the PKCS 11 certificate

     DETAILED: non zero if a detailed URL is required

     URL: will contain an allocated url

     This function will export a URL identifying the given certificate.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_obj_export
------------------------

 -- Function: int gnutls_pkcs11_obj_export (gnutls_pkcs11_obj_t OBJ,
          void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)
     OBJ: Holds the object

     OUTPUT_DATA: will contain a certificate PEM or DER encoded

     OUTPUT_DATA_SIZE: holds the size of output_data (and will be
     replaced by the actual size of parameters)

     This function will export the pkcs11 object data. It is normal for
     PKCS `11' data to be inaccesible and in that case
     `GNUTLS_E_INVALID_REQUEST' will be returned.

     If the buffer provided is not long enough to hold the output, then
     *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
     be returned.

     If the structure is PEM encoded, it will have a header of "BEGIN
     CERTIFICATE".

     *Return value:* In case of failure a negative value will be
     returned, and 0 on success.

gnutls_pkcs11_obj_get_info
--------------------------

 -- Function: int gnutls_pkcs11_obj_get_info (gnutls_pkcs11_obj_t CRT,
          gnutls_pkcs11_obj_info_t ITYPE, void * OUTPUT, size_t *
          OUTPUT_SIZE)
     CRT: should contain a `gnutls_pkcs11_obj_t' structure

     ITYPE: Denotes the type of information requested

     OUTPUT: where output will be stored

     OUTPUT_SIZE: contains the maximum size of the output and will be
     overwritten with actual

     This function will return information about the PKCS 11
     certificatesuch as the label, id as well as token information
     where the key is stored. When output is text it returns null
     terminated string although `output_size' contains the size of the
     actual data only.

     *Returns:* zero on success or a negative value on error.

gnutls_pkcs11_obj_get_type
--------------------------

 -- Function: gnutls_pkcs11_obj_type_t gnutls_pkcs11_obj_get_type
          (gnutls_pkcs11_obj_t OBJ)
     This function will return the type of the certificate being stored
     in the structure.

     *Returns:* The type of the certificate.

gnutls_pkcs11_obj_import_url
----------------------------

 -- Function: int gnutls_pkcs11_obj_import_url (gnutls_pkcs11_obj_t
          CERT, const char * URL, unsigned int FLAGS)
     CERT: The structure to store the parsed certificate

     URL: a PKCS 11 url identifying the key

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will "import" a PKCS 11 URL identifying a certificate
     key to the `gnutls_pkcs11_obj_t' structure. This does not involve
     any parsing (such as X.509 or OpenPGP) since the
     `gnutls_pkcs11_obj_t' is format agnostic. Only data are
     transferred.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_obj_init
----------------------

 -- Function: int gnutls_pkcs11_obj_init (gnutls_pkcs11_obj_t * OBJ)
     OBJ: The structure to be initialized

     This function will initialize a pkcs11 certificate structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_obj_list_import_url
---------------------------------

 -- Function: int gnutls_pkcs11_obj_list_import_url
          (gnutls_pkcs11_obj_t * P_LIST, unsigned int * N_LIST, const
          char * URL, gnutls_pkcs11_obj_attr_t ATTRS, unsigned int
          FLAGS)
     P_LIST: An uninitialized object list (may be NULL)

     N_LIST: initially should hold the maximum size of the list. Will
     contain the actual size.

     URL: A PKCS 11 url identifying a set of objects

     ATTRS: Attributes of type `gnutls_pkcs11_obj_attr_t' that can be
     used to limit output

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will initialize and set values to an object list by
     using all objects identified by a PKCS 11 URL.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_privkey_deinit
----------------------------

 -- Function: void gnutls_pkcs11_privkey_deinit
          (gnutls_pkcs11_privkey_t KEY)
     KEY: The structure to be initialized

     This function will deinitialize a private key structure.

gnutls_pkcs11_privkey_export_url
--------------------------------

 -- Function: int gnutls_pkcs11_privkey_export_url
          (gnutls_pkcs11_privkey_t KEY, gnutls_pkcs11_url_type_t
          DETAILED, char ** URL)
     KEY: Holds the PKCS 11 key

     DETAILED: non zero if a detailed URL is required

     URL: will contain an allocated url

     This function will export a URL identifying the given key.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_privkey_get_info
------------------------------

 -- Function: int gnutls_pkcs11_privkey_get_info
          (gnutls_pkcs11_privkey_t PKEY, gnutls_pkcs11_obj_info_t
          ITYPE, void * OUTPUT, size_t * OUTPUT_SIZE)
     PKEY: should contain a `gnutls_pkcs11_privkey_t' structure

     ITYPE: Denotes the type of information requested

     OUTPUT: where output will be stored

     OUTPUT_SIZE: contains the maximum size of the output and will be
     overwritten with actual

     This function will return information about the PKCS 11 private
     key such as the label, id as well as token information where the
     key is stored. When output is text it returns null terminated
     string although `output_size' contains the size of the actual data
     only.

     *Returns:* zero on success or a negative value on error.

gnutls_pkcs11_privkey_get_pk_algorithm
--------------------------------------

 -- Function: int gnutls_pkcs11_privkey_get_pk_algorithm
          (gnutls_pkcs11_privkey_t KEY, unsigned int * BITS)
     KEY: should contain a `gnutls_pkcs11_privkey_t' structure

     This function will return the public key algorithm of a private
     key.

     *Returns:* a member of the `gnutls_pk_algorithm_t' enumeration on
     success, or a negative value on error.

gnutls_pkcs11_privkey_import_url
--------------------------------

 -- Function: int gnutls_pkcs11_privkey_import_url
          (gnutls_pkcs11_privkey_t PKEY, const char * URL, unsigned int
          FLAGS)
     PKEY: The structure to store the parsed key

     URL: a PKCS 11 url identifying the key

     FLAGS: sequence of GNUTLS_PKCS_PRIVKEY_*

     This function will "import" a PKCS 11 URL identifying a private
     key to the `gnutls_pkcs11_privkey_t' structure. In reality since
     in most cases keys cannot be exported, the private key structure
     is being associated with the available operations on the token.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_privkey_init
--------------------------

 -- Function: int gnutls_pkcs11_privkey_init (gnutls_pkcs11_privkey_t *
          KEY)
     KEY: The structure to be initialized

     This function will initialize an private key structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_reinit
--------------------

 -- Function: int gnutls_pkcs11_reinit ( VOID)
     This function will reinitialize the PKCS 11 subsystem in gnutls.
     This is required by PKCS 11 when an application uses `fork()'. The
     reinitialization function must be called on the child.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0.0

gnutls_pkcs11_set_pin_function
------------------------------

 -- Function: void gnutls_pkcs11_set_pin_function
          (gnutls_pkcs11_pin_callback_t FN, void * USERDATA)
     FN: The PIN callback

     USERDATA: data to be supplied to callback

     This function will set a callback function to be used when a PIN
     is required for PKCS 11 operations.

     Callback for PKCS`11' PIN entry.  The callback provides the PIN
     code to unlock the token with label 'token_label', specified by
     the URL 'token_url'.

     The PIN code, as a NUL-terminated ASCII string, should be copied
     into the 'pin' buffer (of maximum size pin_max), and return 0 to
     indicate success. Alternatively, the callback may return a
     negative gnutls error code to indicate failure and cancel PIN
     entry (in which case, the contents of the 'pin' parameter are
     ignored).

     When a PIN is required, the callback will be invoked repeatedly
     (and indefinitely) until either the returned PIN code is correct,
     the callback returns failure, or the token refuses login (e.g. when
     the token is locked due to too many incorrect PINs!).  For the
     first such invocation, the 'attempt' counter will have value zero;
     it will increase by one for each subsequent attempt.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_set_token_function
--------------------------------

 -- Function: void gnutls_pkcs11_set_token_function
          (gnutls_pkcs11_token_callback_t FN, void * USERDATA)
     FN: The token callback

     USERDATA: data to be supplied to callback

     This function will set a callback function to be used when a token
     needs to be inserted to continue PKCS 11 operations.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_token_get_flags
-----------------------------

 -- Function: int gnutls_pkcs11_token_get_flags (const char * URL,
          unsigned int * FLAGS)
     URL: should contain a PKCS 11 URL

     FLAGS: The output flags (GNUTLS_PKCS11_TOKEN_*)

     This function will return information about the PKCS 11 token
     flags.

     *Returns:* zero on success or a negative value on error.

gnutls_pkcs11_token_get_info
----------------------------

 -- Function: int gnutls_pkcs11_token_get_info (const char * URL,
          gnutls_pkcs11_token_info_t TTYPE, void * OUTPUT, size_t *
          OUTPUT_SIZE)
     URL: should contain a PKCS 11 URL

     TTYPE: Denotes the type of information requested

     OUTPUT: where output will be stored

     OUTPUT_SIZE: contains the maximum size of the output and will be
     overwritten with actual

     This function will return information about the PKCS 11 token such
     as the label, id as well as token information where the key is
     stored.

     *Returns:* zero on success or a negative value on error.

gnutls_pkcs11_token_get_mechanism
---------------------------------

 -- Function: int gnutls_pkcs11_token_get_mechanism (const char * URL,
          int IDX, unsigned long * MECHANISM)
     URL: should contain a PKCS 11 URL

     IDX: The index of the mechanism

     MECHANISM: The PKCS `11' mechanism ID

     This function will return the names of the supported mechanisms by
     the token. It should be called with an increasing index until it
     return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE.

     *Returns:* zero on success or a negative value on error.

gnutls_pkcs11_token_get_url
---------------------------

 -- Function: int gnutls_pkcs11_token_get_url (unsigned int SEQ,
          gnutls_pkcs11_url_type_t DETAILED, char ** URL)
     SEQ: sequence number starting from 0

     DETAILED: non zero if a detailed URL is required

     URL: will contain an allocated url

     This function will return the URL for each token available in
     system. The url has to be released using `gnutls_free()'

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned,
     `GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE' if the sequence number
     exceeds the available tokens, otherwise a negative error value.

gnutls_pkcs11_token_init
------------------------

 -- Function: int gnutls_pkcs11_token_init (const char * TOKEN_URL,
          const char * SO_PIN, const char * LABEL)
     TOKEN_URL: A PKCS `11' URL specifying a token

     SO_PIN: Security Officer's PIN

     LABEL: A name to be used for the token

     This function will initialize (format) a token. If the token is at
     a factory defaults state the security officer's PIN given will be
     set to be the default. Otherwise it should match the officer's PIN.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pkcs11_token_set_pin
---------------------------

 -- Function: int gnutls_pkcs11_token_set_pin (const char * TOKEN_URL,
          const char * OLDPIN, const char * NEWPIN, unsigned int FLAGS)
     TOKEN_URL: A PKCS `11' URL specifying a token

     OLDPIN: old user's PIN

     NEWPIN: new user's PIN

     FLAGS: one of gnutls_pkcs11_pin_flag_t

     This function will modify or set a user's PIN for the given token.
     If it is called to set a user pin for first time the oldpin must
     be NULL.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_prf_raw
--------------

 -- Function: int gnutls_prf_raw (gnutls_session_t SESSION, size_t
          LABEL_SIZE, const char * LABEL, size_t SEED_SIZE, const char
          * SEED, size_t OUTSIZE, char * OUT)
     SESSION: is a `gnutls_session_t' structure.

     LABEL_SIZE: length of the `label' variable.

     LABEL: label used in PRF computation, typically a short string.

     SEED_SIZE: length of the `seed' variable.

     SEED: optional extra data to seed the PRF with.

     OUTSIZE: size of pre-allocated output buffer to hold the output.

     OUT: pre-allocate buffer to hold the generated data.

     Apply the TLS Pseudo-Random-Function (PRF) using the master secret
     on some data.

     The `label' variable usually contain a string denoting the purpose
     for the generated data.  The `seed' usually contain data such as
     the client and server random, perhaps together with some additional
     data that is added to guarantee uniqueness of the output for a
     particular purpose.

     Because the output is not guaranteed to be unique for a particular
     session unless `seed' include the client random and server random
     fields (the PRF would output the same data on another connection
     resumed from the first one), it is not recommended to use this
     function directly.  The `gnutls_prf()' function seed the PRF with
     the client and server random fields directly, and is recommended
     if you want to generate pseudo random data unique for each session.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_prf
----------

 -- Function: int gnutls_prf (gnutls_session_t SESSION, size_t
          LABEL_SIZE, const char * LABEL, int SERVER_RANDOM_FIRST,
          size_t EXTRA_SIZE, const char * EXTRA, size_t OUTSIZE, char *
          OUT)
     SESSION: is a `gnutls_session_t' structure.

     LABEL_SIZE: length of the `label' variable.

     LABEL: label used in PRF computation, typically a short string.

     SERVER_RANDOM_FIRST: non-0 if server random field should be first
     in seed

     EXTRA_SIZE: length of the `extra' variable.

     EXTRA: optional extra data to seed the PRF with.

     OUTSIZE: size of pre-allocated output buffer to hold the output.

     OUT: pre-allocate buffer to hold the generated data.

     Apply the TLS Pseudo-Random-Function (PRF) using the master secret
     on some data, seeded with the client and server random fields.

     The `label' variable usually contain a string denoting the purpose
     for the generated data.  The `server_random_first' indicate whether
     the client random field or the server random field should be first
     in the seed.  Non-0 indicate that the server random field is first,
     0 that the client random field is first.

     The `extra' variable can be used to add more data to the seed,
     after the random variables.  It can be used to tie make sure the
     generated output is strongly connected to some additional data
     (e.g., a string used in user authentication).

     The output is placed in *`OUT', which must be pre-allocated.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_priority_deinit
----------------------

 -- Function: void gnutls_priority_deinit (gnutls_priority_t
          PRIORITY_CACHE)
     PRIORITY_CACHE: is a `gnutls_prioritity_t' structure.

     Deinitializes the priority cache.

gnutls_priority_init
--------------------

 -- Function: int gnutls_priority_init (gnutls_priority_t *
          PRIORITY_CACHE, const char * PRIORITIES, const char **
          ERR_POS)
     PRIORITY_CACHE: is a `gnutls_prioritity_t' structure.

     PRIORITIES: is a string describing priorities

     ERR_POS: In case of an error this will have the position in the
     string the error occured

     Sets priorities for the ciphers, key exchange methods, macs and
     compression methods.

     The `priorities' option allows you to specify a colon separated
     list of the cipher priorities to enable.

     *Common keywords:* Some keywords are defined to provide quick
     access to common preferences.

     "PERFORMANCE" means all the "secure" ciphersuites are enabled,
     limited to 128 bit ciphers and sorted by terms of speed
     performance.

     "NORMAL" means all "secure" ciphersuites. The 256-bit ciphers are
     included as a fallback only.  The ciphers are sorted by security
     margin.

     "SECURE128" means all "secure" ciphersuites with ciphers up to 128
     bits, sorted by security margin.

     "SECURE256" means all "secure" ciphersuites including the 256 bit
     ciphers, sorted by security margin.

     "EXPORT" means all ciphersuites are enabled, including the
     low-security 40 bit ciphers.

     "NONE" means nothing is enabled.  This disables even protocols and
     compression methods.

     *Special keywords:* "!" or "-" appended with an algorithm will
     remove this algorithm.

     "+" appended with an algorithm will add this algorithm.

     Check the GnuTLS manual section "Priority strings" for detailed
     information.

     *Examples:*
     "NONE:+VERS-TLS-ALL:+MAC-ALL:+RSA:+AES-128-CBC:+SIGN-ALL:+COMP-NULL"

     "NORMAL:-ARCFOUR-128" means normal ciphers except for ARCFOUR-128.

     "SECURE:-VERS-SSL3.0:+COMP-DEFLATE" means that only secure ciphers
     are enabled, SSL3.0 is disabled, and libz compression enabled.

     "NONE:+VERS-TLS-ALL:+AES-128-CBC:+RSA:+SHA1:+COMP-NULL:+SIGN-RSA-SHA1",

     "NORMAL:`COMPAT'" is the most compatible mode.

     *Returns:* On syntax error `GNUTLS_E_INVALID_REQUEST' is returned,
     `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_priority_set_direct
--------------------------

 -- Function: int gnutls_priority_set_direct (gnutls_session_t SESSION,
          const char * PRIORITIES, const char ** ERR_POS)
     SESSION: is a `gnutls_session_t' structure.

     PRIORITIES: is a string describing priorities

     ERR_POS: In case of an error this will have the position in the
     string the error occured

     Sets the priorities to use on the ciphers, key exchange methods,
     macs and compression methods.  This function avoids keeping a
     priority cache and is used to directly set string priorities to a
     TLS session.  For documentation check the `gnutls_priority_init()'.

     *Returns:* On syntax error `GNUTLS_E_INVALID_REQUEST' is returned,
     `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_priority_set
-------------------

 -- Function: int gnutls_priority_set (gnutls_session_t SESSION,
          gnutls_priority_t PRIORITY)
     SESSION: is a `gnutls_session_t' structure.

     PRIORITY: is a `gnutls_priority_t' structure.

     Sets the priorities to use on the ciphers, key exchange methods,
     macs and compression methods.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_privkey_decrypt_data
---------------------------

 -- Function: int gnutls_privkey_decrypt_data (gnutls_privkey_t KEY,
          unsigned int FLAGS, const gnutls_datum_t * CIPHERTEXT,
          gnutls_datum_t * PLAINTEXT)
     KEY: Holds the key

     FLAGS: zero for now

     CIPHERTEXT: holds the data to be decrypted

     PLAINTEXT: will contain the decrypted data, allocated with
     `gnutls_malloc()'

     This function will decrypt the given data using the algorithm
     supported by the private key.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_privkey_deinit
---------------------

 -- Function: void gnutls_privkey_deinit (gnutls_privkey_t KEY)
     KEY: The structure to be deinitialized

     This function will deinitialize a private key structure.

gnutls_privkey_get_pk_algorithm
-------------------------------

 -- Function: int gnutls_privkey_get_pk_algorithm (gnutls_privkey_t
          KEY, unsigned int * BITS)
     KEY: should contain a `gnutls_privkey_t' structure

     BITS: If set will return the number of bits of the parameters (may
     be NULL)

     This function will return the public key algorithm of a private
     key and if possible will return a number of bits that indicates
     the security parameter of the key.

     *Returns:* a member of the `gnutls_pk_algorithm_t' enumeration on
     success, or a negative value on error.

gnutls_privkey_get_type
-----------------------

 -- Function: gnutls_privkey_type_t gnutls_privkey_get_type
          (gnutls_privkey_t KEY)
     KEY: should contain a `gnutls_privkey_t' structure

     This function will return the type of the private key. This is
     actually the type of the subsystem used to set this private key.

     *Returns:* a member of the `gnutls_privkey_type_t' enumeration on
     success, or a negative value on error.

gnutls_privkey_import_openpgp
-----------------------------

 -- Function: int gnutls_privkey_import_openpgp (gnutls_privkey_t PKEY,
          gnutls_openpgp_privkey_t KEY, unsigned int FLAGS)
     PKEY: The private key

     KEY: The private key to be imported

     FLAGS: should be zero

     This function will import the given private key to the abstract
     `gnutls_privkey_t' structure.

     The `gnutls_openpgp_privkey_t' object must not be deallocated
     during the lifetime of this structure. The subkey set as preferred
     will be used, or the master key otherwise.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_privkey_import_pkcs11
----------------------------

 -- Function: int gnutls_privkey_import_pkcs11 (gnutls_privkey_t PKEY,
          gnutls_pkcs11_privkey_t KEY, unsigned int FLAGS)
     PKEY: The private key

     KEY: The private key to be imported

     FLAGS: should be zero

     This function will import the given private key to the abstract
     `gnutls_privkey_t' structure.

     The `gnutls_pkcs11_privkey_t' object must not be deallocated
     during the lifetime of this structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_privkey_import_x509
--------------------------

 -- Function: int gnutls_privkey_import_x509 (gnutls_privkey_t PKEY,
          gnutls_x509_privkey_t KEY, unsigned int FLAGS)
     PKEY: The private key

     KEY: The private key to be imported

     FLAGS: should be zero

     This function will import the given private key to the abstract
     `gnutls_privkey_t' structure.

     The `gnutls_x509_privkey_t' object must not be deallocated during
     the lifetime of this structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_privkey_init
-------------------

 -- Function: int gnutls_privkey_init (gnutls_privkey_t * KEY)
     KEY: The structure to be initialized

     This function will initialize an private key structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_privkey_sign_data
------------------------

 -- Function: int gnutls_privkey_sign_data (gnutls_privkey_t SIGNER,
          gnutls_digest_algorithm_t HASH, unsigned int FLAGS, const
          gnutls_datum_t * DATA, gnutls_datum_t * SIGNATURE)
     SIGNER: Holds the key

     HASH: should be a digest algorithm

     FLAGS: should be 0 for now

     DATA: holds the data to be signed

     SIGNATURE: will contain the signature allocate with
     `gnutls_malloc()'

     This function will sign the given data using a signature algorithm
     supported by the private key. Signature algorithms are always used
     together with a hash functions.  Different hash functions may be
     used for the RSA algorithm, but only SHA-1 for the DSA keys.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

     *Since:* 2.12.0

gnutls_privkey_sign_hash
------------------------

 -- Function: int gnutls_privkey_sign_hash (gnutls_privkey_t SIGNER,
          gnutls_digest_algorithm_t HASH_ALGO, unsigned int FLAGS,
          const gnutls_datum_t * HASH_DATA, gnutls_datum_t * SIGNATURE)
     SIGNER: Holds the signer's key

     HASH_ALGO: The hash algorithm used

     FLAGS: zero for now

     HASH_DATA: holds the data to be signed

     SIGNATURE: will contain newly allocated signature

     This function will sign the given hashed data using a signature
     algorithm supported by the private key. Signature algorithms are
     always used together with a hash functions.  Different hash
     functions may be used for the RSA algorithm, but only SHA-XXX for
     the DSA keys.

     Use `gnutls_x509_crt_get_preferred_hash_algorithm()' to determine
     the hash algorithm.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

     *Since:* 2.12.0

gnutls_protocol_get_id
----------------------

 -- Function: gnutls_protocol_t gnutls_protocol_get_id (const char *
          NAME)
     NAME: is a protocol name

     The names are compared in a case insensitive way.

     *Returns:* an id of the specified protocol, or
     `GNUTLS_VERSION_UNKNOWN' on error.

gnutls_protocol_get_name
------------------------

 -- Function: const char * gnutls_protocol_get_name (gnutls_protocol_t
          VERSION)
     VERSION: is a (gnutls) version number

     Convert a `gnutls_protocol_t' value to a string.

     *Returns:* a string that contains the name of the specified TLS
     version (e.g., "TLS1.0"), or `NULL'.

gnutls_protocol_get_version
---------------------------

 -- Function: gnutls_protocol_t gnutls_protocol_get_version
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get TLS version, a `gnutls_protocol_t' value.

     *Returns:* the version of the currently used protocol.

gnutls_protocol_list
--------------------

 -- Function: const gnutls_protocol_t * gnutls_protocol_list ( VOID)
     Get a list of supported protocols, e.g. SSL 3.0, TLS 1.0 etc.

     *Returns:* a zero-terminated list of `gnutls_protocol_t' integers
     indicating the available protocols.

gnutls_protocol_set_priority
----------------------------

 -- Function: int gnutls_protocol_set_priority (gnutls_session_t
          SESSION, const int * LIST)
     SESSION: is a `gnutls_session_t' structure.

     LIST: is a 0 terminated list of gnutls_protocol_t elements.

     Sets the priority on the protocol versions supported by gnutls.
     This function actually enables or disables protocols. Newer
     protocol versions always have highest priority.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_psk_allocate_client_credentials
--------------------------------------

 -- Function: int gnutls_psk_allocate_client_credentials
          (gnutls_psk_client_credentials_t * SC)
     SC: is a pointer to a `gnutls_psk_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to allocate it.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_psk_allocate_server_credentials
--------------------------------------

 -- Function: int gnutls_psk_allocate_server_credentials
          (gnutls_psk_server_credentials_t * SC)
     SC: is a pointer to a `gnutls_psk_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to allocate it.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_psk_client_get_hint
--------------------------

 -- Function: const char * gnutls_psk_client_get_hint (gnutls_session_t
          SESSION)
     SESSION: is a gnutls session

     The PSK identity hint may give the client help in deciding which
     username to use.  This should only be called in case of PSK
     authentication and in case of a client.

     *Returns:* the identity hint of the peer, or `NULL' in case of an
     error.

     *Since:* 2.4.0

gnutls_psk_free_client_credentials
----------------------------------

 -- Function: void gnutls_psk_free_client_credentials
          (gnutls_psk_client_credentials_t SC)
     SC: is a `gnutls_psk_client_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to free (deallocate) it.

gnutls_psk_free_server_credentials
----------------------------------

 -- Function: void gnutls_psk_free_server_credentials
          (gnutls_psk_server_credentials_t SC)
     SC: is a `gnutls_psk_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to free (deallocate) it.

gnutls_psk_netconf_derive_key
-----------------------------

 -- Function: int gnutls_psk_netconf_derive_key (const char * PASSWORD,
          const char * PSK_IDENTITY, const char * PSK_IDENTITY_HINT,
          gnutls_datum_t * OUTPUT_KEY)
     PASSWORD: zero terminated string containing password.

     PSK_IDENTITY: zero terminated string with PSK identity.

     PSK_IDENTITY_HINT: zero terminated string with PSK identity hint.

     OUTPUT_KEY: output variable, contains newly allocated *data
     pointer.

     This function will derive a PSK key from a password, for use with
     the Netconf protocol.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

     *Since:* 2.4.0

     *Deprecated:* The need for this interface was dropped from the
     standard on publication as a RFC.  The function works now but will
     return a hard failure in a future release.

gnutls_psk_server_get_username
------------------------------

 -- Function: const char * gnutls_psk_server_get_username
          (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     This should only be called in case of PSK authentication and in
     case of a server.

     *Returns:* the username of the peer, or `NULL' in case of an error.

gnutls_psk_set_client_credentials_function
------------------------------------------

 -- Function: void gnutls_psk_set_client_credentials_function
          (gnutls_psk_client_credentials_t CRED,
          gnutls_psk_client_credentials_function * FUNC)
     CRED: is a `gnutls_psk_server_credentials_t' structure.

     FUNC: is the callback function

     This function can be used to set a callback to retrieve the
     username and password for client PSK authentication.  The
     callback's function form is: int (*callback)(gnutls_session_t,
     char** username, gnutls_datum_t* key);

     The `username' and `key'->data must be allocated using
     `gnutls_malloc()'.  `username' should be ASCII strings or UTF-8
     strings prepared using the "SASLprep" profile of "stringprep".

     The callback function will be called once per handshake.

     The callback function should return 0 on success.  -1 indicates an
     error.

gnutls_psk_set_client_credentials
---------------------------------

 -- Function: int gnutls_psk_set_client_credentials
          (gnutls_psk_client_credentials_t RES, const char * USERNAME,
          const gnutls_datum_t * KEY, gnutls_psk_key_flags FLAGS)
     RES: is a `gnutls_psk_client_credentials_t' structure.

     USERNAME: is the user's zero-terminated userid

     KEY: is the user's key

     This function sets the username and password, in a
     gnutls_psk_client_credentials_t structure.  Those will be used in
     PSK authentication.  `username' should be an ASCII string or UTF-8
     strings prepared using the "SASLprep" profile of "stringprep".  The
     key can be either in raw byte format or in Hex format (without the
     0x prefix).

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_psk_set_params_function
------------------------------

 -- Function: void gnutls_psk_set_params_function
          (gnutls_psk_server_credentials_t RES, gnutls_params_function
          * FUNC)
     RES: is a gnutls_psk_server_credentials_t structure

     FUNC: is the function to be called

     This function will set a callback in order for the server to get
     the Diffie-Hellman or RSA parameters for PSK authentication.  The
     callback should return zero on success.

gnutls_psk_set_server_credentials_file
--------------------------------------

 -- Function: int gnutls_psk_set_server_credentials_file
          (gnutls_psk_server_credentials_t RES, const char *
          PASSWORD_FILE)
     RES: is a `gnutls_psk_server_credentials_t' structure.

     PASSWORD_FILE: is the PSK password file (passwd.psk)

     This function sets the password file, in a
     `gnutls_psk_server_credentials_t' structure.  This password file
     holds usernames and keys and will be used for PSK authentication.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_psk_set_server_credentials_function
------------------------------------------

 -- Function: void gnutls_psk_set_server_credentials_function
          (gnutls_psk_server_credentials_t CRED,
          gnutls_psk_server_credentials_function * FUNC)
     CRED: is a `gnutls_psk_server_credentials_t' structure.

     FUNC: is the callback function

     This function can be used to set a callback to retrieve the user's
     PSK credentials.  The callback's function form is: int
     (*callback)(gnutls_session_t, const char* username,
     gnutls_datum_t* key);

     `username' contains the actual username.  The `key' must be filled
     in using the `gnutls_malloc()'.

     In case the callback returned a negative number then gnutls will
     assume that the username does not exist.

     The callback function will only be called once per handshake.  The
     callback function should return 0 on success, while -1 indicates
     an error.

gnutls_psk_set_server_credentials_hint
--------------------------------------

 -- Function: int gnutls_psk_set_server_credentials_hint
          (gnutls_psk_server_credentials_t RES, const char * HINT)
     RES: is a `gnutls_psk_server_credentials_t' structure.

     HINT: is the PSK identity hint string

     This function sets the identity hint, in a
     `gnutls_psk_server_credentials_t' structure.  This hint is sent to
     the client to help it chose a good PSK credential (i.e., username
     and password).

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

     *Since:* 2.4.0

gnutls_psk_set_server_dh_params
-------------------------------

 -- Function: void gnutls_psk_set_server_dh_params
          (gnutls_psk_server_credentials_t RES, gnutls_dh_params_t
          DH_PARAMS)
     RES: is a gnutls_psk_server_credentials_t structure

     DH_PARAMS: is a structure that holds Diffie-Hellman parameters.

     This function will set the Diffie-Hellman parameters for an
     anonymous server to use. These parameters will be used in
     Diffie-Hellman exchange with PSK cipher suites.

gnutls_psk_set_server_params_function
-------------------------------------

 -- Function: void gnutls_psk_set_server_params_function
          (gnutls_psk_server_credentials_t RES, gnutls_params_function
          * FUNC)
     RES: is a `gnutls_certificate_credentials_t' structure

     FUNC: is the function to be called

     This function will set a callback in order for the server to get
     the Diffie-Hellman parameters for PSK authentication.  The callback
     should return zero on success.

gnutls_pubkey_deinit
--------------------

 -- Function: void gnutls_pubkey_deinit (gnutls_pubkey_t KEY)
     KEY: The structure to be deinitialized

     This function will deinitialize a public key structure.

gnutls_pubkey_export
--------------------

 -- Function: int gnutls_pubkey_export (gnutls_pubkey_t KEY,
          gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t *
          OUTPUT_DATA_SIZE)
     KEY: Holds the certificate

     FORMAT: the format of output params. One of PEM or DER.

     OUTPUT_DATA: will contain a certificate PEM or DER encoded

     OUTPUT_DATA_SIZE: holds the size of output_data (and will be
     replaced by the actual size of parameters)

     This function will export the certificate to DER or PEM format.

     If the buffer provided is not long enough to hold the output, then
     *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
     be returned.

     If the structure is PEM encoded, it will have a header of "BEGIN
     CERTIFICATE".

     *Return value:* In case of failure a negative value will be
     returned, and 0 on success.

gnutls_pubkey_get_key_id
------------------------

 -- Function: int gnutls_pubkey_get_key_id (gnutls_pubkey_t KEY,
          unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t *
          OUTPUT_DATA_SIZE)
     KEY: Holds the public key

     FLAGS: should be 0 for now

     OUTPUT_DATA: will contain the key ID

     OUTPUT_DATA_SIZE: holds the size of output_data (and will be
     replaced by the actual size of parameters)

     This function will return a unique ID the depends on the public
     key parameters. This ID can be used in checking whether a
     certificate corresponds to the given public key.

     If the buffer provided is not long enough to hold the output, then
     *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
     be returned.  The output will normally be a SHA-1 hash output,
     which is 20 bytes.

     *Return value:* In case of failure a negative value will be
     returned, and 0 on success.

gnutls_pubkey_get_key_usage
---------------------------

 -- Function: int gnutls_pubkey_get_key_usage (gnutls_pubkey_t KEY,
          unsigned int * USAGE)
     KEY: should contain a `gnutls_pubkey_t' structure

     USAGE: If set will return the number of bits of the parameters
     (may be NULL)

     This function will return the key usage of the public key.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_get_pk_algorithm
------------------------------

 -- Function: int gnutls_pubkey_get_pk_algorithm (gnutls_pubkey_t KEY,
          unsigned int * BITS)
     KEY: should contain a `gnutls_pubkey_t' structure

     BITS: If set will return the number of bits of the parameters (may
     be NULL)

     This function will return the public key algorithm of a public key
     and if possible will return a number of bits that indicates the
     security parameter of the key.

     *Returns:* a member of the `gnutls_pk_algorithm_t' enumeration on
     success, or a negative value on error.

gnutls_pubkey_get_pk_dsa_raw
----------------------------

 -- Function: int gnutls_pubkey_get_pk_dsa_raw (gnutls_pubkey_t KEY,
          gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G,
          gnutls_datum_t * Y)
     KEY: Holds the public key

     P: will hold the p

     Q: will hold the q

     G: will hold the g

     Y: will hold the y

     This function will export the DSA public key's parameters found in
     the given certificate.  The new parameters will be allocated using
     `gnutls_malloc()' and will be stored in the appropriate datum.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

gnutls_pubkey_get_pk_rsa_raw
----------------------------

 -- Function: int gnutls_pubkey_get_pk_rsa_raw (gnutls_pubkey_t KEY,
          gnutls_datum_t * M, gnutls_datum_t * E)
     KEY: Holds the certificate

     M: will hold the modulus

     E: will hold the public exponent

     This function will export the RSA public key's parameters found in
     the given structure.  The new parameters will be allocated using
     `gnutls_malloc()' and will be stored in the appropriate datum.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

gnutls_pubkey_get_preferred_hash_algorithm
------------------------------------------

 -- Function: int gnutls_pubkey_get_preferred_hash_algorithm
          (gnutls_pubkey_t KEY, gnutls_digest_algorithm_t * HASH,
          unsigned int * MAND)
     KEY: Holds the certificate

     HASH: The result of the call with the hash algorithm used for
     signature

     MAND: If non zero it means that the algorithm MUST use this hash.
     May be NULL.

     This function will read the certifcate and return the appropriate
     digest algorithm to use for signing with this certificate. Some
     certificates (i.e.  DSA might not be able to sign without the
     preferred algorithm).

     *Returns:* the 0 if the hash algorithm is found. A negative value
     is returned on error.

     *Since:* 2.11.0

gnutls_pubkey_get_verify_algorithm
----------------------------------

 -- Function: int gnutls_pubkey_get_verify_algorithm (gnutls_pubkey_t
          KEY, const gnutls_datum_t * SIGNATURE,
          gnutls_digest_algorithm_t * HASH)
     KEY: Holds the certificate

     SIGNATURE: contains the signature

     HASH: The result of the call with the hash algorithm used for
     signature

     This function will read the certifcate and the signed data to
     determine the hash algorithm used to generate the signature.

     *Returns:* the 0 if the hash algorithm is found. A negative value
     is returned on error.

gnutls_pubkey_import_dsa_raw
----------------------------

 -- Function: int gnutls_pubkey_import_dsa_raw (gnutls_pubkey_t KEY,
          const gnutls_datum_t * P, const gnutls_datum_t * Q, const
          gnutls_datum_t * G, const gnutls_datum_t * Y)
     KEY: The structure to store the parsed key

     P: holds the p

     Q: holds the q

     G: holds the g

     Y: holds the y

     This function will convert the given DSA raw parameters to the
     native `gnutls_pubkey_t' format.  The output will be stored in
     `key'.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_import_openpgp
----------------------------

 -- Function: int gnutls_pubkey_import_openpgp (gnutls_pubkey_t KEY,
          gnutls_openpgp_crt_t CRT, unsigned int FLAGS)
     KEY: The public key

     CRT: The certificate to be imported

     FLAGS: should be zero

     This function will import the given public key to the abstract
     `gnutls_pubkey_t' structure. The subkey set as preferred will be
     imported or the master key otherwise.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_import_pkcs11_url
-------------------------------

 -- Function: int gnutls_pubkey_import_pkcs11_url (gnutls_pubkey_t KEY,
          const char * URL, unsigned int FLAGS)
     KEY: A key of type `gnutls_pubkey_t'

     URL: A PKCS 11 url

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will import a PKCS 11 certificate to a
     `gnutls_pubkey_t' structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_import_pkcs11
---------------------------

 -- Function: int gnutls_pubkey_import_pkcs11 (gnutls_pubkey_t KEY,
          gnutls_pkcs11_obj_t OBJ, unsigned int FLAGS)
     KEY: The public key

     OBJ: The parameters to be imported

     FLAGS: should be zero

     This function will import the given public key to the abstract
     `gnutls_pubkey_t' structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_import_privkey
----------------------------

 -- Function: int gnutls_pubkey_import_privkey (gnutls_pubkey_t KEY,
          gnutls_privkey_t PKEY, unsigned int USAGE, unsigned int FLAGS)
     KEY: The public key

     PKEY: The private key

     USAGE: GNUTLS_KEY_* key usage flags.

     FLAGS: should be zero

     This function will import the given public key to the abstract
     `gnutls_pubkey_t' structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

     *Since:* 2.12.0

gnutls_pubkey_import_rsa_raw
----------------------------

 -- Function: int gnutls_pubkey_import_rsa_raw (gnutls_pubkey_t KEY,
          const gnutls_datum_t * M, const gnutls_datum_t * E)
     KEY: Is a structure will hold the parameters

     M: holds the modulus

     E: holds the public exponent

     This function will replace the parameters in the given structure.
     The new parameters should be stored in the appropriate
     gnutls_datum.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_pubkey_import_x509
-------------------------

 -- Function: int gnutls_pubkey_import_x509 (gnutls_pubkey_t KEY,
          gnutls_x509_crt_t CRT, unsigned int FLAGS)
     KEY: The public key

     CRT: The certificate to be imported

     FLAGS: should be zero

     This function will import the given public key to the abstract
     `gnutls_pubkey_t' structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_import
--------------------

 -- Function: int gnutls_pubkey_import (gnutls_pubkey_t KEY, const
          gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)
     KEY: The structure to store the parsed public key.

     DATA: The DER or PEM encoded certificate.

     FORMAT: One of DER or PEM

     This function will convert the given DER or PEM encoded Public key
     to the native gnutls_pubkey_t format.The output will be stored *
     in  key.  If the Certificate is PEM encoded it should have a
     header of "PUBLIC KEY".

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_init
------------------

 -- Function: int gnutls_pubkey_init (gnutls_pubkey_t * KEY)
     KEY: The structure to be initialized

     This function will initialize an public key structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_set_key_usage
---------------------------

 -- Function: int gnutls_pubkey_set_key_usage (gnutls_pubkey_t KEY,
          unsigned int USAGE)
     KEY: a certificate of type `gnutls_x509_crt_t'

     USAGE: an ORed sequence of the GNUTLS_KEY_* elements.

     This function will set the key usage flags of the public key. This
     is only useful if the key is to be exported to a certificate or
     certificate request.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_pubkey_verify_data
-------------------------

 -- Function: int gnutls_pubkey_verify_data (gnutls_pubkey_t PUBKEY,
          unsigned int FLAGS, const gnutls_datum_t * DATA, const
          gnutls_datum_t * SIGNATURE)
     PUBKEY: Holds the public key

     FLAGS: should be 0 for now

     DATA: holds the data to be signed

     SIGNATURE: contains the signature

     This function will verify the given signed data, using the
     parameters from the certificate.

     *Returns:* In case of a verification failure
     `GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and a positive code
     on success.

     *Since:* 2.12.0

gnutls_pubkey_verify_hash
-------------------------

 -- Function: int gnutls_pubkey_verify_hash (gnutls_pubkey_t KEY,
          unsigned int FLAGS, const gnutls_datum_t * HASH, const
          gnutls_datum_t * SIGNATURE)
     KEY: Holds the certificate

     FLAGS: should be 0 for now

     HASH: holds the hash digest to be verified

     SIGNATURE: contains the signature

     This function will verify the given signed digest, using the
     parameters from the certificate.

     *Returns:* In case of a verification failure
     `GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and a positive code
     on success.

gnutls_record_check_pending
---------------------------

 -- Function: size_t gnutls_record_check_pending (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function checks if there are any data to receive in the gnutls
     buffers.

     *Returns:* the size of that data or 0.

gnutls_record_disable_padding
-----------------------------

 -- Function: void gnutls_record_disable_padding (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Used to disabled padding in TLS 1.0 and above.  Normally you do not
     need to use this function, but there are buggy clients that
     complain if a server pads the encrypted data.  This of course will
     disable protection against statistical attacks on the data.

     Normally only servers that require maximum compatibility with
     everything out there, need to call this function.

gnutls_record_get_direction
---------------------------

 -- Function: int gnutls_record_get_direction (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function provides information about the internals of the
     record protocol and is only useful if a prior gnutls function call
     (e.g.  `gnutls_handshake()') was interrupted for some reason, that
     is, if a function returned `GNUTLS_E_INTERRUPTED' or
     `GNUTLS_E_AGAIN'.  In such a case, you might want to call
     `select()' or `poll()' before calling the interrupted gnutls
     function again.  To tell you whether a file descriptor should be
     selected for either reading or writing,
     `gnutls_record_get_direction()' returns 0 if the interrupted
     function was trying to read data, and 1 if it was trying to write
     data.

     *Returns:* 0 if trying to read data, 1 if trying to write data.

gnutls_record_get_max_size
--------------------------

 -- Function: size_t gnutls_record_get_max_size (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get the record size.  The maximum record size is negotiated by the
     client after the first handshake message.

     *Returns:* The maximum record packet size in this connection.

gnutls_record_recv
------------------

 -- Function: ssize_t gnutls_record_recv (gnutls_session_t SESSION,
          void * DATA, size_t SIZEOFDATA)
     SESSION: is a `gnutls_session_t' structure.

     DATA: the buffer that the data will be read into

     SIZEOFDATA: the number of requested bytes

     This function has the similar semantics with `recv()'.  The only
     difference is that it accepts a GnuTLS session, and uses different
     error codes.

     In the special case that a server requests a renegotiation, the
     client may receive an error code of `GNUTLS_E_REHANDSHAKE'.  This
     message may be simply ignored, replied with an alert
     `GNUTLS_A_NO_RENEGOTIATION', or replied with a new handshake,
     depending on the client's will.

     If `EINTR' is returned by the internal push function (the default
     is `recv()') then `GNUTLS_E_INTERRUPTED' will be returned.  If
     `GNUTLS_E_INTERRUPTED' or `GNUTLS_E_AGAIN' is returned, you must
     call this function again to get the data.  See also
     `gnutls_record_get_direction()'.

     A server may also receive `GNUTLS_E_REHANDSHAKE' when a client has
     initiated a handshake. In that case the server can only initiate a
     handshake or terminate the connection.

     *Returns:* the number of bytes received and zero on EOF.  A
     negative error code is returned in case of an error.  The number
     of bytes received might be less than `sizeofdata'.

gnutls_record_send
------------------

 -- Function: ssize_t gnutls_record_send (gnutls_session_t SESSION,
          const void * DATA, size_t SIZEOFDATA)
     SESSION: is a `gnutls_session_t' structure.

     DATA: contains the data to send

     SIZEOFDATA: is the length of the data

     This function has the similar semantics with `send()'.  The only
     difference is that it accepts a GnuTLS session, and uses different
     error codes.

     Note that if the send buffer is full, `send()' will block this
     function.  See the `send()' documentation for full information.
     You can replace the default push function by using
     `gnutls_transport_set_ptr2()' with a call to `send()' with a
     MSG_DONTWAIT flag if blocking is a problem.

     If the EINTR is returned by the internal push function (the
     default is `send()'} then `GNUTLS_E_INTERRUPTED' will be returned.
     If `GNUTLS_E_INTERRUPTED' or `GNUTLS_E_AGAIN' is returned, you must
     call this function again, with the same parameters; alternatively
     you could provide a `NULL' pointer for data, and 0 for size. cf.
     `gnutls_record_get_direction()'.

     *Returns:* the number of bytes sent, or a negative error code.  The
     number of bytes sent might be less than `sizeofdata'.  The maximum
     number of bytes this function can send in a single call depends on
     the negotiated maximum record size.

gnutls_record_set_max_size
--------------------------

 -- Function: ssize_t gnutls_record_set_max_size (gnutls_session_t
          SESSION, size_t SIZE)
     SESSION: is a `gnutls_session_t' structure.

     SIZE: is the new size

     This function sets the maximum record packet size in this
     connection.  This property can only be set to clients.  The server
     may choose not to accept the requested size.

     Acceptable values are 512(=2^9), 1024(=2^10), 2048(=2^11) and
     4096(=2^12).  The requested record size does get in effect
     immediately only while sending data. The receive part will take
     effect after a successful handshake.

     This function uses a TLS extension called 'max record size'.  Not
     all TLS implementations use or even understand this extension.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_rehandshake
------------------

 -- Function: int gnutls_rehandshake (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function will renegotiate security parameters with the
     client.  This should only be called in case of a server.

     This message informs the peer that we want to renegotiate
     parameters (perform a handshake).

     If this function succeeds (returns 0), you must call the
     `gnutls_handshake()' function in order to negotiate the new
     parameters.

     Since TLS is full duplex some application data might have been
     sent during peer's processing of this message. In that case one
     should call `gnutls_record_recv()' until GNUTLS_E_REHANDSHAKE is
     returned to clear any pending data. Care must be taken if
     rehandshake is mandatory to terminate if it does not start after
     some threshold.

     If the client does not wish to renegotiate parameters he will
     should with an alert message, thus the return code will be
     `GNUTLS_E_WARNING_ALERT_RECEIVED' and the alert will be
     `GNUTLS_A_NO_RENEGOTIATION'.  A client may also choose to ignore
     this message.

     *Returns:* `GNUTLS_E_SUCCESS' on success, otherwise an error.

gnutls_rnd
----------

 -- Function: int gnutls_rnd (gnutls_rnd_level_t LEVEL, void * DATA,
          size_t LEN)
     LEVEL: a security level

     DATA: place to store random bytes

     LEN: The requested size

     This function will generate random data and store it to output
     buffer.

     *Returns:* Zero or a negative value on error.

gnutls_rsa_export_get_modulus_bits
----------------------------------

 -- Function: int gnutls_rsa_export_get_modulus_bits (gnutls_session_t
          SESSION)
     SESSION: is a gnutls session

     Get the export RSA parameter's modulus size.

     *Returns:* the bits used in the last RSA-EXPORT key exchange with
     the peer, or a negative value in case of error.

gnutls_rsa_export_get_pubkey
----------------------------

 -- Function: int gnutls_rsa_export_get_pubkey (gnutls_session_t
          SESSION, gnutls_datum_t * EXPONENT, gnutls_datum_t * MODULUS)
     SESSION: is a gnutls session

     EXPONENT: will hold the exponent.

     MODULUS: will hold the modulus.

     This function will return the peer's public key exponent and
     modulus used in the last RSA-EXPORT authentication.  The output
     parameters must be freed with `gnutls_free()'.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_rsa_params_cpy
---------------------

 -- Function: int gnutls_rsa_params_cpy (gnutls_rsa_params_t DST,
          gnutls_rsa_params_t SRC)
     DST: Is the destination structure, which should be initialized.

     SRC: Is the source structure

     This function will copy the RSA parameters structure from source
     to destination.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_rsa_params_deinit
------------------------

 -- Function: void gnutls_rsa_params_deinit (gnutls_rsa_params_t
          RSA_PARAMS)
     RSA_PARAMS: Is a structure that holds the parameters

     This function will deinitialize the RSA parameters structure.

gnutls_rsa_params_export_pkcs1
------------------------------

 -- Function: int gnutls_rsa_params_export_pkcs1 (gnutls_rsa_params_t
          PARAMS, gnutls_x509_crt_fmt_t FORMAT, unsigned char *
          PARAMS_DATA, size_t * PARAMS_DATA_SIZE)
     PARAMS: Holds the RSA parameters

     FORMAT: the format of output params. One of PEM or DER.

     PARAMS_DATA: will contain a PKCS1 RSAPublicKey structure PEM or
     DER encoded

     PARAMS_DATA_SIZE: holds the size of params_data (and will be
     replaced by the actual size of parameters)

     This function will export the given RSA parameters to a PKCS1
     RSAPublicKey structure. If the buffer provided is not long enough
     to hold the output, then GNUTLS_E_SHORT_MEMORY_BUFFER will be
     returned.

     If the structure is PEM encoded, it will have a header of "BEGIN
     RSA PRIVATE KEY".

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_rsa_params_export_raw
----------------------------

 -- Function: int gnutls_rsa_params_export_raw (gnutls_rsa_params_t
          PARAMS, gnutls_datum_t * M, gnutls_datum_t * E,
          gnutls_datum_t * D, gnutls_datum_t * P, gnutls_datum_t * Q,
          gnutls_datum_t * U, unsigned int * BITS)
     PARAMS: a structure that holds the rsa parameters

     M: will hold the modulus

     E: will hold the public exponent

     D: will hold the private exponent

     P: will hold the first prime (p)

     Q: will hold the second prime (q)

     U: will hold the coefficient

     BITS: if non null will hold the prime's number of bits

     This function will export the RSA parameters found in the given
     structure. The new parameters will be allocated using
     `gnutls_malloc()' and will be stored in the appropriate datum.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_rsa_params_generate2
---------------------------

 -- Function: int gnutls_rsa_params_generate2 (gnutls_rsa_params_t
          PARAMS, unsigned int BITS)
     PARAMS: The structure where the parameters will be stored

     BITS: is the prime's number of bits

     This function will generate new temporary RSA parameters for use in
     RSA-EXPORT ciphersuites.  This function is normally slow.

     Note that if the parameters are to be used in export cipher suites
     the bits value should be 512 or less.  Also note that the
     generation of new RSA parameters is only useful to servers.
     Clients use the parameters sent by the server, thus it's no use
     calling this in client side.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_rsa_params_import_pkcs1
------------------------------

 -- Function: int gnutls_rsa_params_import_pkcs1 (gnutls_rsa_params_t
          PARAMS, const gnutls_datum_t * PKCS1_PARAMS,
          gnutls_x509_crt_fmt_t FORMAT)
     PARAMS: A structure where the parameters will be copied to

     PKCS1_PARAMS: should contain a PKCS1 RSAPublicKey structure PEM or
     DER encoded

     FORMAT: the format of params. PEM or DER.

     This function will extract the RSAPublicKey found in a PKCS1
     formatted structure.

     If the structure is PEM encoded, it should have a header of "BEGIN
     RSA PRIVATE KEY".

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_rsa_params_import_raw
----------------------------

 -- Function: int gnutls_rsa_params_import_raw (gnutls_rsa_params_t
          RSA_PARAMS, const gnutls_datum_t * M, const gnutls_datum_t *
          E, const gnutls_datum_t * D, const gnutls_datum_t * P, const
          gnutls_datum_t * Q, const gnutls_datum_t * U)
     RSA_PARAMS: Is a structure will hold the parameters

     M: holds the modulus

     E: holds the public exponent

     D: holds the private exponent

     P: holds the first prime (p)

     Q: holds the second prime (q)

     U: holds the coefficient

     This function will replace the parameters in the given structure.
     The new parameters should be stored in the appropriate
     gnutls_datum.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_rsa_params_init
----------------------

 -- Function: int gnutls_rsa_params_init (gnutls_rsa_params_t *
          RSA_PARAMS)
     RSA_PARAMS: Is a structure that will hold the parameters

     This function will initialize the temporary RSA parameters
     structure.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an negative error
     code.

gnutls_safe_renegotiation_status
--------------------------------

 -- Function: int gnutls_safe_renegotiation_status (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Can be used to check whether safe renegotiation is being used in
     the current session.

     *Returns:* 0 when safe renegotiation is not used and non zero when
     safe renegotiation is used.

     *Since:* 2.10.0

gnutls_sec_param_get_name
-------------------------

 -- Function: const char * gnutls_sec_param_get_name
          (gnutls_sec_param_t PARAM)
     PARAM: is a security parameter

     Convert a `gnutls_sec_param_t' value to a string.

     *Returns:* a pointer to a string that contains the name of the
     specified public key algorithm, or `NULL'.

gnutls_sec_param_to_pk_bits
---------------------------

 -- Function: unsigned int gnutls_sec_param_to_pk_bits
          (gnutls_pk_algorithm_t ALGO, gnutls_sec_param_t PARAM)
     ALGO: is a public key algorithm

     PARAM: is a security parameter

     When generating private and public key pairs a difficult question
     is which size of "bits" the modulus will be in RSA and the group
     size in DSA. The easy answer is 1024, which is also wrong. This
     function will convert a human understandable security parameter to
     an appropriate size for the specific algorithm.

     *Returns:* The number of bits, or zero.

gnutls_server_name_get
----------------------

 -- Function: int gnutls_server_name_get (gnutls_session_t SESSION,
          void * DATA, size_t * DATA_LENGTH, unsigned int * TYPE,
          unsigned int INDX)
     SESSION: is a `gnutls_session_t' structure.

     DATA: will hold the data

     DATA_LENGTH: will hold the data length. Must hold the maximum size
     of data.

     TYPE: will hold the server name indicator type

     INDX: is the index of the server_name

     This function will allow you to get the name indication (if any), a
     client has sent.  The name indication may be any of the enumeration
     gnutls_server_name_type_t.

     If `type' is GNUTLS_NAME_DNS, then this function is to be used by
     servers that support virtual hosting, and the data will be a null
     terminated UTF-8 string.

     If `data' has not enough size to hold the server name
     GNUTLS_E_SHORT_MEMORY_BUFFER is returned, and `data_length' will
     hold the required size.

     `index' is used to retrieve more than one server names (if sent by
     the client).  The first server name has an index of 0, the second 1
     and so on.  If no name with the given index exists
     GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE is returned.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_server_name_set
----------------------

 -- Function: int gnutls_server_name_set (gnutls_session_t SESSION,
          gnutls_server_name_type_t TYPE, const void * NAME, size_t
          NAME_LENGTH)
     SESSION: is a `gnutls_session_t' structure.

     TYPE: specifies the indicator type

     NAME: is a string that contains the server name.

     NAME_LENGTH: holds the length of name

     This function is to be used by clients that want to inform (via a
     TLS extension mechanism) the server of the name they connected to.
     This should be used by clients that connect to servers that do
     virtual hosting.

     The value of `name' depends on the `type' type.  In case of
     `GNUTLS_NAME_DNS', an ASCII zero-terminated domain name string,
     without the trailing dot, is expected.  IPv4 or IPv6 addresses are
     not permitted.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (zero) is returned,
     otherwise an error code is returned.

gnutls_session_channel_binding
------------------------------

 -- Function: int gnutls_session_channel_binding (gnutls_session_t
          SESSION, gnutls_channel_binding_t CBTYPE, gnutls_datum_t * CB)
     SESSION: is a `gnutls_session_t' structure.

     CBTYPE: an `gnutls_channel_binding_t' enumeration type

     CB: output buffer array with data

     Extract given channel binding data of the `cbtype' (e.g.,
     `GNUTLS_CB_TLS_UNIQUE') type.

     *Returns:* `GNUTLS_E_SUCCESS' on success,
     `GNUTLS_E_UNIMPLEMENTED_FEATURE' if the `cbtype' is unsupported,
     `GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE' if the data is not
     currently available, or an error code.

     *Since:* 2.12.0

gnutls_session_enable_compatibility_mode
----------------------------------------

 -- Function: void gnutls_session_enable_compatibility_mode
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     This function can be used to disable certain (security) features in
     TLS in order to maintain maximum compatibility with buggy clients.
     It is equivalent to calling: `gnutls_record_disable_padding()'

     Normally only servers that require maximum compatibility with
     everything out there, need to call this function.

gnutls_session_get_data2
------------------------

 -- Function: int gnutls_session_get_data2 (gnutls_session_t SESSION,
          gnutls_datum_t * DATA)
     SESSION: is a `gnutls_session_t' structure.

     DATA: is a pointer to a datum that will hold the session.

     Returns all session parameters, in order to support resuming.  The
     client should call this, and keep the returned session, if he wants
     to resume that current version later by calling
     `gnutls_session_set_data()'.  This function must be called after a
     successful handshake.  The returned datum must be freed with
     `gnutls_free()'.

     Resuming sessions is really useful and speedups connections after
     a successful one.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_session_get_data
-----------------------

 -- Function: int gnutls_session_get_data (gnutls_session_t SESSION,
          void * SESSION_DATA, size_t * SESSION_DATA_SIZE)
     SESSION: is a `gnutls_session_t' structure.

     SESSION_DATA: is a pointer to space to hold the session.

     SESSION_DATA_SIZE: is the session_data's size, or it will be set
     by the function.

     Returns all session parameters, in order to support resuming.  The
     client should call this, and keep the returned session, if he
     wants to resume that current version later by calling
     `gnutls_session_set_data()' This function must be called after a
     successful handshake.

     Resuming sessions is really useful and speedups connections after
     a successful one.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_session_get_id
---------------------

 -- Function: int gnutls_session_get_id (gnutls_session_t SESSION, void
          * SESSION_ID, size_t * SESSION_ID_SIZE)
     SESSION: is a `gnutls_session_t' structure.

     SESSION_ID: is a pointer to space to hold the session id.

     SESSION_ID_SIZE: is the session id's size, or it will be set by
     the function.

     Returns the current session id. This can be used if you want to
     check if the next session you tried to resume was actually
     resumed.  This is because resumed sessions have the same sessionID
     with the original session.

     Session id is some data set by the server, that identify the
     current session.  In TLS 1.0 and SSL 3.0 session id is always less
     than 32 bytes.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_session_get_ptr
----------------------

 -- Function: void * gnutls_session_get_ptr (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Get user pointer for session.  Useful in callbacks.  This is the
     pointer set with `gnutls_session_set_ptr()'.

     *Returns:* the user given pointer from the session structure, or
     `NULL' if it was never set.

gnutls_session_is_resumed
-------------------------

 -- Function: int gnutls_session_is_resumed (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Check whether session is resumed or not.

     *Returns:* non zero if this session is resumed, or a zero if this
     is a new session.

gnutls_session_set_data
-----------------------

 -- Function: int gnutls_session_set_data (gnutls_session_t SESSION,
          const void * SESSION_DATA, size_t SESSION_DATA_SIZE)
     SESSION: is a `gnutls_session_t' structure.

     SESSION_DATA: is a pointer to space to hold the session.

     SESSION_DATA_SIZE: is the session's size

     Sets all session parameters, in order to resume a previously
     established session.  The session data given must be the one
     returned by `gnutls_session_get_data()'.  This function should be
     called before `gnutls_handshake()'.

     Keep in mind that session resuming is advisory. The server may
     choose not to resume the session, thus a full handshake will be
     performed.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

gnutls_session_set_ptr
----------------------

 -- Function: void gnutls_session_set_ptr (gnutls_session_t SESSION,
          void * PTR)
     SESSION: is a `gnutls_session_t' structure.

     PTR: is the user pointer

     This function will set (associate) the user given pointer `ptr' to
     the session structure.  This is pointer can be accessed with
     `gnutls_session_get_ptr()'.

gnutls_session_ticket_enable_client
-----------------------------------

 -- Function: int gnutls_session_ticket_enable_client (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Request that the client should attempt session resumption using
     SessionTicket.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

     *Since:* 2.10.0

gnutls_session_ticket_enable_server
-----------------------------------

 -- Function: int gnutls_session_ticket_enable_server (gnutls_session_t
          SESSION, const gnutls_datum_t * KEY)
     SESSION: is a `gnutls_session_t' structure.

     KEY: key to encrypt session parameters.

     Request that the server should attempt session resumption using
     SessionTicket.  `key' must be initialized with
     `gnutls_session_ticket_key_generate()'.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

     *Since:* 2.10.0

gnutls_session_ticket_key_generate
----------------------------------

 -- Function: int gnutls_session_ticket_key_generate (gnutls_datum_t *
          KEY)
     KEY: is a pointer to a `gnutls_datum_t' which will contain a newly
     created key.

     Generate a random key to encrypt security parameters within
     SessionTicket.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

     *Since:* 2.10.0

gnutls_set_default_export_priority
----------------------------------

 -- Function: int gnutls_set_default_export_priority (gnutls_session_t
          SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Sets some default priority on the ciphers, key exchange methods,
     macs and compression methods.  This function also includes weak
     algorithms.

     *This is the same as calling:* gnutls_priority_set_direct
     (session, "EXPORT", NULL);

     This function is kept around for backwards compatibility, but
     because of its wide use it is still fully supported.  If you wish
     to allow users to provide a string that specify which ciphers to
     use (which is recommended), you should use
     `gnutls_priority_set_direct()' or `gnutls_priority_set()' instead.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_set_default_priority
---------------------------

 -- Function: int gnutls_set_default_priority (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Sets some default priority on the ciphers, key exchange methods,
     macs and compression methods.

     *This is the same as calling:* gnutls_priority_set_direct
     (session, "NORMAL", NULL);

     This function is kept around for backwards compatibility, but
     because of its wide use it is still fully supported.  If you wish
     to allow users to provide a string that specify which ciphers to
     use (which is recommended), you should use
     `gnutls_priority_set_direct()' or `gnutls_priority_set()' instead.

     *Returns:* `GNUTLS_E_SUCCESS' on success, or an error code.

gnutls_sign_algorithm_get_name
------------------------------

 -- Function: const char * gnutls_sign_algorithm_get_name
          (gnutls_sign_algorithm_t SIGN)
     SIGN: is a sign algorithm

     Convert a `gnutls_sign_algorithm_t' value to a string.

     *Returns:* a string that contains the name of the specified sign
     algorithm, or `NULL'.

gnutls_sign_algorithm_get_requested
-----------------------------------

 -- Function: int gnutls_sign_algorithm_get_requested (gnutls_session_t
          SESSION, size_t INDX, gnutls_sign_algorithm_t * ALGO)
     SESSION: is a `gnutls_session_t' structure.

     INDX: is an index of the signature algorithm to return

     ALGO: the returned certificate type will be stored there

     Returns the signature algorithm specified by index that was
     requested by the peer. If the specified index has no data available
     this function returns `GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE'.  If
     the negotiated TLS version does not support signature algorithms
     then `GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE' will be returned even
     for the first index.  The first index is 0.

     This function is useful in the certificate callback functions to
     assist in selecting the correct certificate.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned,
     otherwise an error code is returned.

     *Since:* 2.10.0

gnutls_sign_callback_get
------------------------

 -- Function: gnutls_sign_func gnutls_sign_callback_get
          (gnutls_session_t SESSION, void ** USERDATA)
     SESSION: is a gnutls session

     USERDATA: if non-`NULL', will be set to abstract callback pointer.

     Retrieve the callback function, and its userdata pointer.

     *Returns:* The function pointer set by
     `gnutls_sign_callback_set()', or if not set, `NULL'.

     *Deprecated:* Use the PKCS 11 interfaces instead.

gnutls_sign_callback_set
------------------------

 -- Function: void gnutls_sign_callback_set (gnutls_session_t SESSION,
          gnutls_sign_func SIGN_FUNC, void * USERDATA)
     SESSION: is a gnutls session

     SIGN_FUNC: function pointer to application's sign callback.

     USERDATA: void pointer that will be passed to sign callback.

     Set the callback function.  The function must have this prototype:

     typedef int (*gnutls_sign_func) (gnutls_session_t session, void
     *userdata, gnutls_certificate_type_t cert_type, const
     gnutls_datum_t * cert, const gnutls_datum_t * hash, gnutls_datum_t
     * signature);

     The `userdata' parameter is passed to the `sign_func' verbatim, and
     can be used to store application-specific data needed in the
     callback function.  See also `gnutls_sign_callback_get()'.

     *Deprecated:* Use the PKCS 11 interfaces instead.

gnutls_sign_get_id
------------------

 -- Function: gnutls_sign_algorithm_t gnutls_sign_get_id (const char *
          NAME)
     NAME: is a MAC algorithm name

     The names are compared in a case insensitive way.

     *Returns:* return a `gnutls_sign_algorithm_t' value corresponding
     to the specified cipher, or `GNUTLS_SIGN_UNKNOWN' on error.

gnutls_sign_get_name
--------------------

 -- Function: const char * gnutls_sign_get_name
          (gnutls_sign_algorithm_t ALGORITHM)
     ALGORITHM: is a public key signature algorithm

     Convert a `gnutls_sign_algorithm_t' value to a string.

     *Returns:* a pointer to a string that contains the name of the
     specified public key signature algorithm, or `NULL'.

     *Since:* 2.6.0

gnutls_sign_list
----------------

 -- Function: const gnutls_sign_algorithm_t * gnutls_sign_list ( VOID)
     Get a list of supported public key signature algorithms.

     *Returns:* a zero-terminated list of `gnutls_sign_algorithm_t'
     integers indicating the available ciphers.

gnutls_srp_allocate_client_credentials
--------------------------------------

 -- Function: int gnutls_srp_allocate_client_credentials
          (gnutls_srp_client_credentials_t * SC)
     SC: is a pointer to a `gnutls_srp_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to allocate it.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

gnutls_srp_allocate_server_credentials
--------------------------------------

 -- Function: int gnutls_srp_allocate_server_credentials
          (gnutls_srp_server_credentials_t * SC)
     SC: is a pointer to a `gnutls_srp_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to allocate it.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

gnutls_srp_base64_decode_alloc
------------------------------

 -- Function: int gnutls_srp_base64_decode_alloc (const gnutls_datum_t
          * B64_DATA, gnutls_datum_t * RESULT)
     B64_DATA: contains the encoded data

     RESULT: the place where decoded data lie

     This function will decode the given encoded data. The decoded data
     will be allocated, and stored into result.  It will decode using
     the base64 algorithm as used in libsrp.

     You should use `gnutls_free()' to free the returned data.

     Warning!  This base64 encoding is not the "standard" encoding, so
     do not use it for non-SRP purposes.

     *Returns:* 0 on success, or an error code.

gnutls_srp_base64_decode
------------------------

 -- Function: int gnutls_srp_base64_decode (const gnutls_datum_t *
          B64_DATA, char * RESULT, size_t * RESULT_SIZE)
     B64_DATA: contain the encoded data

     RESULT: the place where decoded data will be copied

     RESULT_SIZE: holds the size of the result

     This function will decode the given encoded data, using the base64
     encoding found in libsrp.

     Note that `b64_data' should be null terminated.

     Warning!  This base64 encoding is not the "standard" encoding, so
     do not use it for non-SRP purposes.

     *Returns:* `GNUTLS_E_SHORT_MEMORY_BUFFER' if the buffer given is
     not long enough, or 0 on success.

gnutls_srp_base64_encode_alloc
------------------------------

 -- Function: int gnutls_srp_base64_encode_alloc (const gnutls_datum_t
          * DATA, gnutls_datum_t * RESULT)
     DATA: contains the raw data

     RESULT: will hold the newly allocated encoded data

     This function will convert the given data to printable data, using
     the base64 encoding.  This is the encoding used in SRP password
     files.  This function will allocate the required memory to hold
     the encoded data.

     You should use `gnutls_free()' to free the returned data.

     Warning!  This base64 encoding is not the "standard" encoding, so
     do not use it for non-SRP purposes.

     *Returns:* 0 on success, or an error code.

gnutls_srp_base64_encode
------------------------

 -- Function: int gnutls_srp_base64_encode (const gnutls_datum_t *
          DATA, char * RESULT, size_t * RESULT_SIZE)
     DATA: contain the raw data

     RESULT: the place where base64 data will be copied

     RESULT_SIZE: holds the size of the result

     This function will convert the given data to printable data, using
     the base64 encoding, as used in the libsrp.  This is the encoding
     used in SRP password files.  If the provided buffer is not long
     enough GNUTLS_E_SHORT_MEMORY_BUFFER is returned.

     Warning!  This base64 encoding is not the "standard" encoding, so
     do not use it for non-SRP purposes.

     *Returns:* `GNUTLS_E_SHORT_MEMORY_BUFFER' if the buffer given is
     not long enough, or 0 on success.

gnutls_srp_free_client_credentials
----------------------------------

 -- Function: void gnutls_srp_free_client_credentials
          (gnutls_srp_client_credentials_t SC)
     SC: is a `gnutls_srp_client_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to free (deallocate) it.

gnutls_srp_free_server_credentials
----------------------------------

 -- Function: void gnutls_srp_free_server_credentials
          (gnutls_srp_server_credentials_t SC)
     SC: is a `gnutls_srp_server_credentials_t' structure.

     This structure is complex enough to manipulate directly thus this
     helper function is provided in order to free (deallocate) it.

gnutls_srp_server_get_username
------------------------------

 -- Function: const char * gnutls_srp_server_get_username
          (gnutls_session_t SESSION)
     SESSION: is a gnutls session

     This function will return the username of the peer.  This should
     only be called in case of SRP authentication and in case of a
     server.  Returns NULL in case of an error.

     *Returns:* SRP username of the peer, or NULL in case of error.

gnutls_srp_set_client_credentials_function
------------------------------------------

 -- Function: void gnutls_srp_set_client_credentials_function
          (gnutls_srp_client_credentials_t CRED,
          gnutls_srp_client_credentials_function * FUNC)
     CRED: is a `gnutls_srp_server_credentials_t' structure.

     FUNC: is the callback function

     This function can be used to set a callback to retrieve the
     username and password for client SRP authentication.  The
     callback's function form is:

     int (*callback)(gnutls_session_t, char** username, char**password);

     The `username' and `password' must be allocated using
     `gnutls_malloc()'.  `username' and `password' should be ASCII
     strings or UTF-8 strings prepared using the "SASLprep" profile of
     "stringprep".

     The callback function will be called once per handshake before the
     initial hello message is sent.

     The callback should not return a negative error code the second
     time called, since the handshake procedure will be aborted.

     The callback function should return 0 on success.  -1 indicates an
     error.

gnutls_srp_set_client_credentials
---------------------------------

 -- Function: int gnutls_srp_set_client_credentials
          (gnutls_srp_client_credentials_t RES, const char * USERNAME,
          const char * PASSWORD)
     RES: is a `gnutls_srp_client_credentials_t' structure.

     USERNAME: is the user's userid

     PASSWORD: is the user's password

     This function sets the username and password, in a
     `gnutls_srp_client_credentials_t' structure.  Those will be used in
     SRP authentication.  `username' and `password' should be ASCII
     strings or UTF-8 strings prepared using the "SASLprep" profile of
     "stringprep".

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

gnutls_srp_set_prime_bits
-------------------------

 -- Function: void gnutls_srp_set_prime_bits (gnutls_session_t SESSION,
          unsigned int BITS)
     SESSION: is a `gnutls_session_t' structure.

     BITS: is the number of bits

     This function sets the minimum accepted number of bits, for use in
     an SRP key exchange.  If zero, the default 2048 bits will be used.

     In the client side it sets the minimum accepted number of bits.  If
     a server sends a prime with less bits than that
     `GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER' will be returned by the
     handshake.

     This function has no effect in server side.

     *Since:* 2.6.0

gnutls_srp_set_server_credentials_file
--------------------------------------

 -- Function: int gnutls_srp_set_server_credentials_file
          (gnutls_srp_server_credentials_t RES, const char *
          PASSWORD_FILE, const char * PASSWORD_CONF_FILE)
     RES: is a `gnutls_srp_server_credentials_t' structure.

     PASSWORD_FILE: is the SRP password file (tpasswd)

     PASSWORD_CONF_FILE: is the SRP password conf file (tpasswd.conf)

     This function sets the password files, in a
     `gnutls_srp_server_credentials_t' structure.  Those password files
     hold usernames and verifiers and will be used for SRP
     authentication.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

gnutls_srp_set_server_credentials_function
------------------------------------------

 -- Function: void gnutls_srp_set_server_credentials_function
          (gnutls_srp_server_credentials_t CRED,
          gnutls_srp_server_credentials_function * FUNC)
     CRED: is a `gnutls_srp_server_credentials_t' structure.

     FUNC: is the callback function

     This function can be used to set a callback to retrieve the user's
     SRP credentials.  The callback's function form is:

     int (*callback)(gnutls_session_t, const char* username,
     gnutls_datum_t* salt, gnutls_datum_t *verifier, gnutls_datum_t* g,
     gnutls_datum_t* n);

     `username' contains the actual username.  The `salt', `verifier',
     `generator' and `prime' must be filled in using the
     `gnutls_malloc()'. For convenience `prime' and `generator' may
     also be one of the static parameters defined in extra.h.

     In case the callback returned a negative number then gnutls will
     assume that the username does not exist.

     In order to prevent attackers from guessing valid usernames, if a
     user does not exist, g and n values should be filled in using a
     random user's parameters. In that case the callback must return
     the special value (1).

     The callback function will only be called once per handshake.  The
     callback function should return 0 on success, while -1 indicates
     an error.

gnutls_srp_verifier
-------------------

 -- Function: int gnutls_srp_verifier (const char * USERNAME, const
          char * PASSWORD, const gnutls_datum_t * SALT, const
          gnutls_datum_t * GENERATOR, const gnutls_datum_t * PRIME,
          gnutls_datum_t * RES)
     USERNAME: is the user's name

     PASSWORD: is the user's password

     SALT: should be some randomly generated bytes

     GENERATOR: is the generator of the group

     PRIME: is the group's prime

     RES: where the verifier will be stored.

     This function will create an SRP verifier, as specified in
     RFC2945.  The `prime' and `generator' should be one of the static
     parameters defined in gnutls/extra.h or may be generated using the
     libgcrypt functions `gcry_prime_generate()' and
     `gcry_prime_group_generator()'.

     The verifier will be allocated with `malloc' and will be stored in
     `res' using binary format.

     *Returns:* On success, `GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

gnutls_strerror_name
--------------------

 -- Function: const char * gnutls_strerror_name (int ERROR)
     ERROR: is an error returned by a gnutls function.

     Return the GnuTLS error code define as a string.  For example,
     gnutls_strerror_name (GNUTLS_E_DH_PRIME_UNACCEPTABLE) will return
     the string "GNUTLS_E_DH_PRIME_UNACCEPTABLE".

     *Returns:* A string corresponding to the symbol name of the error
     code.

     *Since:* 2.6.0

gnutls_strerror
---------------

 -- Function: const char * gnutls_strerror (int ERROR)
     ERROR: is a GnuTLS error code, a negative value

     This function is similar to strerror.  The difference is that it
     accepts an error number returned by a gnutls function; In case of
     an unknown error a descriptive string is sent instead of `NULL'.

     Error codes are always a negative value.

     *Returns:* A string explaining the GnuTLS error message.

gnutls_supplemental_get_name
----------------------------

 -- Function: const char * gnutls_supplemental_get_name
          (gnutls_supplemental_data_format_type_t TYPE)
     TYPE: is a supplemental data format type

     Convert a `gnutls_supplemental_data_format_type_t' value to a
     string.

     *Returns:* a string that contains the name of the specified
     supplemental data format type, or `NULL' for unknown types.

gnutls_transport_get_ptr2
-------------------------

 -- Function: void gnutls_transport_get_ptr2 (gnutls_session_t SESSION,
          gnutls_transport_ptr_t * RECV_PTR, gnutls_transport_ptr_t *
          SEND_PTR)
     SESSION: is a `gnutls_session_t' structure.

     RECV_PTR: will hold the value for the pull function

     SEND_PTR: will hold the value for the push function

     Used to get the arguments of the transport functions (like PUSH
     and PULL).  These should have been set using
     `gnutls_transport_set_ptr2()'.

gnutls_transport_get_ptr
------------------------

 -- Function: gnutls_transport_ptr_t gnutls_transport_get_ptr
          (gnutls_session_t SESSION)
     SESSION: is a `gnutls_session_t' structure.

     Used to get the first argument of the transport function (like
     PUSH and PULL).  This must have been set using
     `gnutls_transport_set_ptr()'.

     *Returns:* first argument of the transport function.

gnutls_transport_set_errno_function
-----------------------------------

 -- Function: void gnutls_transport_set_errno_function
          (gnutls_session_t SESSION, gnutls_errno_func ERRNO_FUNC)
     SESSION: is a `gnutls_session_t' structure.

     ERRNO_FUNC: a callback function similar to `write()'

     This is the function where you set a function to retrieve errno
     after a failed push or pull operation.

     errno_func is of the form, int
     (*gnutls_errno_func)(gnutls_transport_ptr_t); and should return
     the errno.

gnutls_transport_set_errno
--------------------------

 -- Function: void gnutls_transport_set_errno (gnutls_session_t
          SESSION, int ERR)
     SESSION: is a `gnutls_session_t' structure.

     ERR: error value to store in session-specific errno variable.

     Store `err' in the session-specific errno variable.  Useful values
     for `err' is EAGAIN and EINTR, other values are treated will be
     treated as real errors in the push/pull function.

     This function is useful in replacement push/pull functions set by
     gnutls_transport_set_push_function and
     gnutls_transport_set_pullpush_function under Windows, where the
     replacement push/pull may not have access to the same `errno'
     variable that is used by GnuTLS (e.g., the application is linked to
     msvcr71.dll and gnutls is linked to msvcrt.dll).

     If you don't have the `session' variable easily accessible from the
     push/pull function, and don't worry about thread conflicts, you can
     also use `gnutls_transport_set_global_errno()'.

gnutls_transport_set_global_errno
---------------------------------

 -- Function: void gnutls_transport_set_global_errno (int ERR)
     ERR: error value to store in global errno variable.

     Store `err' in the global errno variable.  Useful values for `err'
     is EAGAIN and EINTR, other values are treated will be treated as
     real errors in the push/pull function.

     This function is useful in replacement push/pull functions set by
     gnutls_transport_set_push_function and
     gnutls_transport_set_pullpush_function under Windows, where the
     replacement push/pull may not have access to the same `errno'
     variable that is used by GnuTLS (e.g., the application is linked to
     msvcr71.dll and gnutls is linked to msvcrt.dll).

     Whether this function is thread safe or not depends on whether the
     global variable errno is thread safe, some system libraries make it
     a thread-local variable.  When feasible, using the guaranteed
     thread-safe `gnutls_transport_set_errno()' may be better.

gnutls_transport_set_lowat
--------------------------

 -- Function: void gnutls_transport_set_lowat (gnutls_session_t
          SESSION, int NUM)
     SESSION: is a `gnutls_session_t' structure.

     NUM: is the low water value.

     Used to set the lowat value in order for select to check if there
     are pending data to socket buffer. Used only if you have changed
     the default low water value (default is 1).  Normally you will not
     need that function.  This function is only useful if using
     berkeley style sockets.  Otherwise it must be called and set lowat
     to zero.

gnutls_transport_set_ptr2
-------------------------

 -- Function: void gnutls_transport_set_ptr2 (gnutls_session_t SESSION,
          gnutls_transport_ptr_t RECV_PTR, gnutls_transport_ptr_t
          SEND_PTR)
     SESSION: is a `gnutls_session_t' structure.

     RECV_PTR: is the value for the pull function

     SEND_PTR: is the value for the push function

     Used to set the first argument of the transport function (like PUSH
     and PULL). In berkeley style sockets this function will set the
     connection handle.  With this function you can use two different
     pointers for receiving and sending.

gnutls_transport_set_ptr
------------------------

 -- Function: void gnutls_transport_set_ptr (gnutls_session_t SESSION,
          gnutls_transport_ptr_t PTR)
     SESSION: is a `gnutls_session_t' structure.

     PTR: is the value.

     Used to set the first argument of the transport function (like PUSH
     and PULL).  In berkeley style sockets this function will set the
     connection handle.

gnutls_transport_set_pull_function
----------------------------------

 -- Function: void gnutls_transport_set_pull_function (gnutls_session_t
          SESSION, gnutls_pull_func PULL_FUNC)
     SESSION: is a `gnutls_session_t' structure.

     PULL_FUNC: a callback function similar to `read()'

     This is the function where you set a function for gnutls to receive
     data.  Normally, if you use berkeley style sockets, do not need to
     use this function since the default (recv(2)) will probably be ok.

     PULL_FUNC is of the form, ssize_t
     (*gnutls_pull_func)(gnutls_transport_ptr_t, void*, size_t);

gnutls_transport_set_push_function
----------------------------------

 -- Function: void gnutls_transport_set_push_function (gnutls_session_t
          SESSION, gnutls_push_func PUSH_FUNC)
     SESSION: is a `gnutls_session_t' structure.

     PUSH_FUNC: a callback function similar to `write()'

     This is the function where you set a push function for gnutls to
     use in order to send data.  If you are going to use berkeley style
     sockets, you do not need to use this function since the default
     (send(2)) will probably be ok.  Otherwise you should specify this
     function for gnutls to be able to send data.

     PUSH_FUNC is of the form, ssize_t
     (*gnutls_push_func)(gnutls_transport_ptr_t, const void*, size_t);

gnutls_transport_set_vec_push_function
--------------------------------------

 -- Function: void gnutls_transport_set_vec_push_function
          (gnutls_session_t SESSION, gnutls_vec_push_func VEC_FUNC)
     SESSION: is a `gnutls_session_t' structure.

     VEC_FUNC: a callback function similar to `writev()'

     This is the function where you set a push function for gnutls to
     use in order to send data.  If you are going to use berkeley style
     sockets, you do not need to use this function since the default
     (send(2)) will probably be ok.  Otherwise you should specify this
     function for gnutls to be able to send data.

     PUSH_FUNC is of the form, ssize_t
     (*gnutls_push_func)(gnutls_transport_ptr_t, const void*, size_t);

gnutls_x509_crq_set_pubkey
--------------------------

 -- Function: int gnutls_x509_crq_set_pubkey (gnutls_x509_crq_t CRQ,
          gnutls_pubkey_t KEY)
     CRQ: should contain a `gnutls_x509_crq_t' structure

     KEY: holds a public key

     This function will set the public parameters from the given public
     key to the request.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_x509_crt_import_pkcs11_url
---------------------------------

 -- Function: int gnutls_x509_crt_import_pkcs11_url (gnutls_x509_crt_t
          CRT, const char * URL, unsigned int FLAGS)
     CRT: A certificate of type `gnutls_x509_crt_t'

     URL: A PKCS 11 url

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will import a PKCS 11 certificate directly from a
     token without involving the `gnutls_pkcs11_obj_t' structure. This
     function will fail if the certificate stored is not of X.509 type.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_x509_crt_import_pkcs11
-----------------------------

 -- Function: int gnutls_x509_crt_import_pkcs11 (gnutls_x509_crt_t CRT,
          gnutls_pkcs11_obj_t PKCS11_CRT)
     CRT: A certificate of type `gnutls_x509_crt_t'

     PKCS11_CRT: A PKCS 11 object that contains a certificate

     This function will import a PKCS 11 certificate to a
     `gnutls_x509_crt_t' structure.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_x509_crt_list_import_pkcs11
----------------------------------

 -- Function: int gnutls_x509_crt_list_import_pkcs11 (gnutls_x509_crt_t
          * CERTS, unsigned int CERT_MAX, gnutls_pkcs11_obj_t * const
          OBJS, unsigned int FLAGS)
     CERTS: A list of certificates of type `gnutls_x509_crt_t'

     CERT_MAX: The maximum size of the list

     OBJS: A list of PKCS 11 objects

     FLAGS: 0 for now

     This function will import a PKCS 11 certificate list to a list of
     `gnutls_x509_crt_t' structure. These must not be initialized.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

gnutls_x509_crt_set_pubkey
--------------------------

 -- Function: int gnutls_x509_crt_set_pubkey (gnutls_x509_crt_t CRT,
          gnutls_pubkey_t KEY)
     CRT: should contain a `gnutls_x509_crt_t' structure

     KEY: holds a public key

     This function will set the public parameters from the given public
     key to the request.

     *Returns:* On success, `GNUTLS_E_SUCCESS' is returned, otherwise a
     negative error value.

