GnuTLS
******

This manual is last updated 19 April 2021 for version 3.7.2 of GnuTLS.

Copyright (C) 2001-2021 Free Software Foundation, Inc.\\ Copyright (C)
2001-2021 Nikos Mavrogiannopoulos

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

1 Preface
*********

This document demonstrates and explains 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 it is likely to only obtain a false sense of
security.  The term of security is very broad even if restricted to
computer software, and cannot be confined to a single cryptographic
library.  For that reason, do not consider any 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 public key infrastructure (PKI) knowledge is assumed in
most of it.  A good introduction to networking can be found in [see
STEVENS], to public key infrastructure in [see GUTPKI] and to
security engineering in [see ANDERSON].

Updated versions of the GnuTLS software and this document will be
available from <https://www.gnutls.org/>.

2 Introduction to GnuTLS
************************

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.3 (see Introduction to TLS,
for a 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.3, TLS 1.2, TLS 1.1, TLS 1.0 and optionally SSL
     3.0 protocols.

   * Support for Datagram TLS 1.0 and 1.2.

   * Support for handling and verification of X.509 certificates.

   * Support for password authentication using TLS-SRP.

   * Support for keyed authentication using TLS-PSK.

   * Support for TPM, PKCS #11 tokens and smart-cards.

The GnuTLS library consists of three independent parts, namely the "TLS
protocol part", the "Certificate part", and the "Cryptographic back-end"
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
and it uses functionality from the libtasn1 library.  The "Cryptographic
back-end" is provided by the nettle and gmplib libraries.

2.1 Downloading and installing
==============================

GnuTLS is available for download at:
<https://www.gnutls.org/download.html>

GnuTLS uses a development cycle where even minor version numbers
indicate a stable release and a odd minor version number indicate 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 'nettle' and 'gmplib', and you will need to install it
before installing GnuTLS. The 'nettle' library is available from
<https://www.lysator.liu.se/~nisse/nettle/>, while 'gmplib' is available
from <https://www.gmplib.org/>.  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.

Several parts of GnuTLS require ASN.1 functionality, which is provided
by 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
<https://www.gnu.org/software/libtasn1/>.

The compression library, 'libz', the PKCS #11 helper library 'p11-kit',
the TPM library 'trousers', as well as the IDN library 'libidn'(1) are
optional dependencies.  Check the README file in the distribution on how
to obtain these libraries.

A few 'configure' options may be relevant, summarized below.  They
disable or enable particular features, to create a smaller library with
only the required features.  Note however, that although a smaller
library is generated, the included programs are not guaranteed to
compile if some of these options are given.

--disable-srp-authentication
--disable-psk-authentication
--disable-anon-authentication
--disable-dhe
--disable-ecdhe
--disable-openssl-compatibility
--disable-dtls-srtp-support
--disable-alpn-support
--disable-heartbeat-support
--disable-libdane
--without-p11-kit
--without-tpm
--without-zlib

For the complete list, refer to the output from 'configure --help'.

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

   (1) Needed to use RFC6125 name comparison in internationalized
domains.

2.2 Installing for a software distribution
==========================================

When installing for a software distribution, it is often desirable to
preconfigure GnuTLS with the system-wide paths and files.  There two
important configuration options, one sets the trust store in system,
which are the CA certificates to be used by programs by default (if they
don't override it), and the other sets to DNSSEC root key file used by
unbound for DNSSEC verification.

For the latter the following configuration option is available, and if
not specified GnuTLS will try to auto-detect the location of that file.
--with-unbound-root-key-file

To set the trust store the following options are available.
--with-default-trust-store-file
--with-default-trust-store-dir
--with-default-trust-store-pkcs11

The first option is used to set a PEM file which contains a list of
trusted certificates, while the second will read all certificates in the
given path.  The recommended option is the last, which allows to use a
PKCS #11 trust policy module.  That module not only provides the trusted
certificates, but allows the categorization of them using purpose, e.g.,
CAs can be restricted for e-mail usage only, or administrative
restrictions of CAs, for examples by restricting a CA to only issue
certificates for a given DNS domain using NameConstraints.  A publicly
available PKCS #11 trust module is p11-kit's trust module(1).

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

   (1) <https://p11-glue.github.io/p11-glue/trust-module.html>

2.3 Overview
============

In this document we present an overview of the supported security
protocols in Introduction to TLS, and continue by providing more
information on the certificate authentication in Certificate authentication,
and shared-key as well anonymous authentication in
Shared-key and anonymous authentication.  We elaborate on
certificate authentication by demonstrating advanced usage of the API in
More on certificate authentication.  The core of the TLS library
is presented in How to use GnuTLS in applications and example
applications are listed in GnuTLS application examples.  In
Other included programs the usage of few included programs that
may assist debugging is presented.  The last chapter is Internal architecture of GnuTLS
that provides a short introduction to GnuTLS'
internal architecture.

3 Introduction to TLS and DTLS
******************************

TLS stands for "Transport Layer Security" and is the successor of SSL,
the Secure Sockets Layer protocol [see SSL3] designed by Netscape.
TLS is an Internet protocol, defined by IETF(1), described in [see
RFC5246].  The protocol provides confidentiality, and authentication
layers over any reliable transport layer.  The description, above,
refers to TLS 1.0 but applies to all other TLS versions as the
differences between the protocols are not major.

The DTLS protocol, or "Datagram TLS" [see RFC4347] is a protocol
with identical goals as TLS, but can operate under unreliable transport
layers such as UDP.  The discussions below apply to this protocol as
well, except when noted otherwise.

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

   (1) IETF, or Internet Engineering Task Force, is a large open
international community of network designers, operators, vendors, and
researchers concerned with the evolution of the Internet architecture
and the smooth operation of the Internet.  It is open to any interested
individual.

3.1 TLS Layers
==============

TLS is a layered protocol, and consists of the record protocol, the
handshake protocol and the alert protocol.  The record protocol is to
serve all other protocols and is above the transport layer.  The record
protocol offers symmetric encryption, and data authenticity(1).  The
alert protocol offers some signaling to the other protocols.  It can
help informing the peer for the cause of failures and other error
conditions.  See 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.  See The Handshake Protocol,
for more information about the handshake protocol.
The protocol layering in TLS is shown in Figure 3.1.

Figure 3.1: The TLS protocol layers.

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

   (1) In early versions of TLS compression was optionally available as
well.  This is no longer the case in recent versions of the protocol.

3.2 The Transport Layer
=======================

TLS is not limited to any transport layer and can be used above any
transport layer, as long as it is a reliable one.  DTLS can be used over
reliable and unreliable transport layers.  GnuTLS supports TCP and UDP
layers transparently using the Berkeley sockets API. However, any
transport layer can be used by providing callbacks for GnuTLS to access
the transport layer (for details see Setting up the transport layer).

3.3 The TLS record protocol
===========================

The record protocol is the secure communications provider.  Its purpose
is to encrypt, and authenticate packets.  The record layer functions can
be called at any time after the handshake process is finished, when
there is need to receive or send data.  In DTLS however, due to
re-transmission timers used in the handshake out-of-order handshake data
might be received for some time (maximum 60 seconds) after the handshake
process is finished.

The functions to access the record protocol are limited to send and
receive functions, which might, given the importance of this protocol in
TLS, seem awkward.  This is because the record protocol's parameters are
all set by the handshake protocol.  The record protocol initially starts
with NULL parameters, which means no encryption, and no MAC is used.
Encryption and authentication begin just after the handshake protocol
has finished.

3.3.1 Encryption algorithms used in the record layer
----------------------------------------------------

Confidentiality in the record layer is achieved by using symmetric
ciphers like 'AES' or 'CHACHA20'.  Ciphers are encryption algorithms
that use a single, secret, key to encrypt and decrypt data.  Early
versions of TLS separated between block and stream ciphers and had
message authentication plugged in to them by the protocol, though later
versions switched to using authenticated-encryption (AEAD) ciphers.  The
AEAD ciphers are defined to combine encryption and authentication, and
as such they are not only more efficient, as the primitives used are
designed to interoperate nicely, but they are also known to interoperate
in a secure way.

The supported in GnuTLS ciphers and MAC algorithms are shown in
Table 3.1 and Table 3.2.

Algorithm      Type    Applicable  Description
                       Protocols
----------------------------------------------------------------------------
AES-128-GCM,   AEAD    TLS 1.2,    This is the AES algorithm in the
AES-256-GCM            TLS 1.3     authenticated encryption GCM mode.
                                   This mode combines message
                                   authentication and encryption and can
                                   be extremely fast on CPUs that support
                                   hardware acceleration.

AES-128-CCM,   AEAD    TLS 1.2,    This is the AES algorithm in the
AES-256-CCM            TLS 1.3     authenticated encryption CCM mode.
                                   This mode combines message
                                   authentication and encryption and is
                                   often used by systems without AES or
                                   GCM acceleration support.

CHACHA20-POLY1305AEAD  TLS 1.2,    CHACHA20-POLY1305 is an authenticated
                       TLS 1.3     encryption algorithm based on CHACHA20
                                   cipher and POLY1305 MAC. CHACHA20 is a
                                   refinement of SALSA20 algorithm, an
                                   approved cipher by the European
                                   ESTREAM project.  POLY1305 is
                                   Wegman-Carter, one-time authenticator.
                                   The combination provides a fast stream
                                   cipher suitable for systems where a
                                   hardware AES accelerator is not
                                   available.

AES-128-CCM-8, AEAD    TLS 1.2,    This is the AES algorithm in the
AES-256-CCM-8          TLS 1.3     authenticated encryption CCM mode with
                                   a truncated to 64-bit authentication
                                   tag.  This mode is for communication
                                   with restricted systems.

CAMELLIA-128-GCM,AEAD  TLS 1.2     This is the CAMELLIA algorithm in the
CAMELLIA-256-GCM                   authenticated encryption GCM mode.

AES-128-CBC,   Legacy  TLS 1.0,    AES or RIJNDAEL is the block cipher
AES-256-CBC    (block) TLS 1.1,    algorithm that replaces the old DES
                       TLS 1.2     algorithm.  It has 128 bits block size
                                   and is used in CBC mode.

CAMELLIA-128-CBC,LegacyTLS 1.0,    This is an 128-bit block cipher
CAMELLIA-256-CBC(block)TLS 1.1,    developed by Mitsubishi and NTT. It is
                       TLS 1.2     one of the approved ciphers of the
                                   European NESSIE and Japanese CRYPTREC
                                   projects.

3DES-CBC       Legacy  TLS 1.0,    This is the DES block cipher algorithm
               (block) TLS 1.1,    used with triple encryption (EDE). Has
                       TLS 1.2     64 bits block size and is used in CBC
                                   mode.

ARCFOUR-128    Legacy  TLS 1.0,    ARCFOUR-128 is a compatible algorithm
               (stream)TLS 1.1,    with RSA's RC4 algorithm, which is
                       TLS 1.2     considered to be a trade secret.  It
                                   is a considered to be broken, and is
                                   only used for compatibility purposed.
                                   For this reason it is not enabled by
                                   default.

GOST28147-TC26Z-CNTLegacyTLS 1.2   This is a 64-bit block cipher GOST
               (stream)            28147-89 with TC26Z S-Box working in
                                   CNT mode.  It is one of the approved
                                   ciphers in Russia.  It is not enabled
                                   by default.

NULL           Legacy  TLS 1.0,    NULL is the empty/identity cipher
               (stream)TLS 1.1,    which doesn't encrypt any data.  It
                       TLS 1.2     can be combined with data
                                   authentication under TLS 1.2 or
                                   earlier, but is only used transiently
                                   under TLS 1.3 until encryption starts.
                                   This cipher cannot be negotiated by
                                   default (need to be explicitly
                                   enabled) under TLS 1.2, and cannot be
                                   negotiated at all under TLS 1.3.  When
                                   enabled, TLS 1.3 (or later) support
                                   will be implicitly disabled.

Table 3.1: Supported ciphers in TLS.

Algorithm      Description
------------------------------------------------------------------
MAC-MD5        This is an HMAC based on MD5 a cryptographic
               hash algorithm designed by Ron Rivest.  Outputs
               128 bits of data.

MAC-SHA1       An HMAC based on the SHA1 cryptographic hash
               algorithm designed by NSA. Outputs 160 bits of
               data.

MAC-SHA256     An HMAC based on SHA2-256.  Outputs 256 bits of
               data.

MAC-SHA384     An HMAC based on SHA2-384.  Outputs 384 bits of
               data.

GOST28147-TC26Z-IMITThis is a 64-bit block cipher GOST 28147-89 with
               TC26Z S-Box working in special MAC mode called
               Imitovstavks.  It is one of the approved MAC
               algorithms in Russia.  Outputs 32 bits of data.
               It is not enabled by default.

MAC-AEAD       This indicates that an authenticated encryption
               algorithm, such as GCM, is in use.

Table 3.2: Supported MAC algorithms in TLS.

3.3.2 Compression algorithms and the record layer
-------------------------------------------------

In early versions of TLS the record layer supported compression.
However, that proved to be problematic in many ways, and enabled several
attacks based on traffic analysis on the transported data.  For that
newer versions of the protocol no longer offer compression, and GnuTLS
since 3.6.0 no longer implements any support for compression.

3.3.3 On record padding
-----------------------

The TLS 1.3 protocol allows for extra padding of records to prevent
statistical analysis based on the length of exchanged messages.  GnuTLS
takes advantage of this feature, by allowing the user to specify the
amount of padding for a particular message.  The simplest interface is
provided by gnutls_record_send2, and is made available when
under TLS1.3; alternatively gnutls_record_can_use_length_hiding
can be queried.

Note that this interface is not sufficient to completely hide the length
of the data.  The application code may reveal the data transferred by
leaking its data processing time, or by leaking the TLS1.3 record
processing time by GnuTLS. That is because under TLS1.3 the padding
removal time depends on the padding data for an efficient
implementation.  To make that processing constant time the
gnutls_init function must be called with the flag
'GNUTLS_SAFE_PADDING_CHECK'.

 -- Function: ssize_t gnutls_record_send2 (gnutls_session_t SESSION,
          const void * DATA, size_t DATA_SIZE, size_t PAD, unsigned
          FLAGS)
     SESSION: is a 'gnutls_session_t' type.

     DATA: contains the data to send

     DATA_SIZE: is the length of the data

     PAD: padding to be added to the record

     FLAGS: must be zero

     This function is identical to 'gnutls_record_send()' except that it
     takes an extra argument to specify padding to be added the record.
     To determine the maximum size of padding, use
     'gnutls_record_get_max_size()' and 'gnutls_record_overhead_size()'
     .

     Note that in order for GnuTLS to provide constant time processing
     of padding and data in TLS1.3, the flag 'GNUTLS_SAFE_PADDING_CHECK'
     must be used in 'gnutls_init()' .

     *Returns:* The number of bytes sent, or a negative error code.  The
     number of bytes sent might be less than 'data_size' .  The maximum
     number of bytes this function can send in a single call depends on
     the negotiated maximum record size.

     *Since:* 3.6.3

Older GnuTLS versions provided an API suitable for cases where the
sender sends data that are always within a given range.  That API is
still available, and consists of the following functions.

'UNSIGNED gnutls_record_can_use_length_hiding (gnutls_session_t SESSION)'
'SSIZE_T gnutls_record_send_range (gnutls_session_t SESSION, const void * DATA, size_t DATA_SIZE, const gnutls_range_st * RANGE)'

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
(e.g.  'GNUTLS_A_CLOSE_NOTIFY'), and others refer to the application
protocol solely (e.g.  'GNUTLS_A_USER_CANCELLED').  An alert signal
includes a level indication which may be either fatal or warning (under
TLS1.3 all alerts are fatal).  Fatal alerts always terminate the current
connection, and prevent future re-negotiations using the current session
ID. All supported alert messages are summarized in the table below.

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.

Alert                                    ID      Description
------------------------------------------------------------------------
GNUTLS_A_CLOSE_NOTIFY                    0       Close notify
GNUTLS_A_UNEXPECTED_MESSAGE              10      Unexpected message
GNUTLS_A_BAD_RECORD_MAC                  20      Bad record MAC
GNUTLS_A_DECRYPTION_FAILED               21      Decryption failed
GNUTLS_A_RECORD_OVERFLOW                 22      Record overflow
GNUTLS_A_DECOMPRESSION_FAILURE           30      Decompression failed
GNUTLS_A_HANDSHAKE_FAILURE               40      Handshake failed
GNUTLS_A_SSL3_NO_CERTIFICATE             41      No certificate (SSL
                                                 3.0)
GNUTLS_A_BAD_CERTIFICATE                 42      Certificate is bad
GNUTLS_A_UNSUPPORTED_CERTIFICATE         43      Certificate is not
                                                 supported
GNUTLS_A_CERTIFICATE_REVOKED             44      Certificate was
                                                 revoked
GNUTLS_A_CERTIFICATE_EXPIRED             45      Certificate is
                                                 expired
GNUTLS_A_CERTIFICATE_UNKNOWN             46      Unknown certificate
GNUTLS_A_ILLEGAL_PARAMETER               47      Illegal parameter
GNUTLS_A_UNKNOWN_CA                      48      CA is unknown
GNUTLS_A_ACCESS_DENIED                   49      Access was denied
GNUTLS_A_DECODE_ERROR                    50      Decode error
GNUTLS_A_DECRYPT_ERROR                   51      Decrypt error
GNUTLS_A_EXPORT_RESTRICTION              60      Export restriction
GNUTLS_A_PROTOCOL_VERSION                70      Error in protocol
                                                 version
GNUTLS_A_INSUFFICIENT_SECURITY           71      Insufficient
                                                 security
GNUTLS_A_INTERNAL_ERROR                  80      Internal error
GNUTLS_A_INAPPROPRIATE_FALLBACK          86      Inappropriate
                                                 fallback
GNUTLS_A_USER_CANCELED                   90      User canceled
GNUTLS_A_NO_RENEGOTIATION                100     No renegotiation is
                                                 allowed
GNUTLS_A_MISSING_EXTENSION               109     An extension was
                                                 expected but was not
                                                 seen
GNUTLS_A_UNSUPPORTED_EXTENSION           110     An unsupported
                                                 extension was sent
GNUTLS_A_CERTIFICATE_UNOBTAINABLE        111     Could not retrieve
                                                 the specified
                                                 certificate
GNUTLS_A_UNRECOGNIZED_NAME               112     The server name sent
                                                 was not recognized
GNUTLS_A_UNKNOWN_PSK_IDENTITY            115     The SRP/PSK username
                                                 is missing or not
                                                 known
GNUTLS_A_CERTIFICATE_REQUIRED            116     Certificate is
                                                 required
GNUTLS_A_NO_APPLICATION_PROTOCOL         120     No supported
                                                 application protocol
                                                 could be negotiated

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.  The main handshake function is
gnutls_handshake.  In the next paragraphs we elaborate on the
handshake protocol, i.e., the ciphersuite negotiation.

3.5.1 TLS ciphersuites
----------------------

The TLS cipher suites have slightly different meaning under different
protocols.  Under TLS 1.3, a cipher suite indicates the symmetric
encryption algorithm in use, as well as the pseudo-random function (PRF)
used in the TLS session.

Under TLS 1.2 or early the handshake protocol negotiates cipher suites
of a special form illustrated by the 'TLS_DHE_RSA_WITH_3DES_CBC_SHA'
cipher suite name.  A typical cipher suite contains 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 listed in ciphersuites.

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

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

3.5.2 Authentication
--------------------

The key exchange algorithms of the TLS protocol offer authentication,
which is a prerequisite for a secure connection.  The available
authentication methods in GnuTLS, under TLS 1.3 or earlier versions,
follow.

   * Certificate authentication: Authenticated key exchange using public
     key infrastructure and X.509 certificates.
   * PSK authentication: Authenticated key exchange using a pre-shared
     key.

Under TLS 1.2 or earlier versions, the following authentication methods
are also available.

   * SRP authentication: Authenticated key exchange using a password.
   * Anonymous authentication: Key exchange without peer authentication.

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
gnutls_certificate_server_set_request function.  We elaborate in
Certificate credentials.

3.5.4 Resuming sessions
-----------------------

The TLS handshake process performs expensive calculations and a busy
server might easily be put under load.  To reduce the load, session
resumption may be used.  This 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 re-using the
previously established keys, meaning the server needs to store the state
of established connections (unless session tickets are used - see
Session tickets).

Session resumption is an integral part of GnuTLS, and Session resumption,
see ex-resume-client illustrate typical uses of it.

3.6 TLS extensions
==================

A number of extensions to the TLS protocol have been proposed mainly in
[see TLSEXT].  The extensions supported in GnuTLS are 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.  The functions shown below can be
used to control this extension.

'SIZE_T gnutls_record_get_max_size (gnutls_session_t SESSION)'
'SSIZE_T gnutls_record_set_max_size (gnutls_session_t SESSION, size_t SIZE)'

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

'INT gnutls_server_name_set (gnutls_session_t SESSION, gnutls_server_name_type_t TYPE, const void * NAME, size_t NAME_LENGTH)'
'INT gnutls_server_name_get (gnutls_session_t SESSION, void * DATA, size_t * DATA_LENGTH, unsigned int * TYPE, unsigned int INDX)'

3.6.3 Session tickets
---------------------

To resume a TLS session, the server normally stores session parameters.
This complicates deployment, and can be avoided by delegating the
storage to the client.  Because session parameters are sensitive they
are encrypted and authenticated with a key only known to the server and
then sent to the client.  The Session Tickets extension is described in
RFC 5077 [see TLSTKT].

A disadvantage of session tickets is that they eliminate the effects of
forward secrecy when a server uses the same key for long time.  That is,
the secrecy of all sessions on a server using tickets depends on the
ticket key being kept secret.  For that reason server keys should be
rotated and discarded regularly.

Since version 3.1.3 GnuTLS clients transparently support session
tickets, unless forward secrecy is explicitly requested (with the PFS
priority string).

Under TLS 1.3 session tickets are mandatory for session resumption, and
they do not share the forward secrecy concerns as with TLS 1.2 or
earlier.

3.6.4 HeartBeat
---------------

This is a TLS extension that allows to ping and receive confirmation
from the peer, and is described in [see RFC6520].  The extension is
disabled by default and gnutls_heartbeat_enable can be used to
enable it.  A policy may be negotiated to only allow sending heartbeat
messages or sending and receiving.  The current session policy can be
checked with gnutls_heartbeat_allowed.  The requests coming from
the peer result to 'GNUTLS_E_HEARTBEAT_PING_RECEIVED' being returned
from the receive function.  Ping requests to peer can be send via
gnutls_heartbeat_ping.

'UNSIGNED gnutls_heartbeat_allowed (gnutls_session_t SESSION, unsigned int TYPE)'
'VOID gnutls_heartbeat_enable (gnutls_session_t SESSION, unsigned int TYPE)'

'INT gnutls_heartbeat_ping (gnutls_session_t SESSION, size_t DATA_SIZE, unsigned int MAX_TRIES, unsigned int FLAGS)'
'INT gnutls_heartbeat_pong (gnutls_session_t SESSION, unsigned int FLAGS)'
'VOID gnutls_heartbeat_set_timeouts (gnutls_session_t SESSION, unsigned int RETRANS_TIMEOUT, unsigned int TOTAL_TIMEOUT)'
'UNSIGNED INT gnutls_heartbeat_get_timeout (gnutls_session_t SESSION)'

3.6.5 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
occurred 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 use
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 [see
RFC5746].

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 behavior would prevent interoperability against
the majority of deployed servers out there.  We will reconsider this
default behavior 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.

To modify the default behavior, we have introduced some new priority
strings (see Priority Strings).  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 trade-off
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 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.

3.6.6 OCSP status request
-------------------------

The Online Certificate Status Protocol (OCSP) is a protocol that allows
the client to verify the server certificate for revocation without
messing with certificate revocation lists.  Its drawback is that it
requires the client to connect to the server's CA OCSP server and
request the status of the certificate.  This extension however, enables
a TLS server to include its CA OCSP server response in the handshake.
That is an HTTPS server may periodically run 'ocsptool' (see
ocsptool Invocation) to obtain its certificate revocation status and
serve it to the clients.  That way a client avoids an additional
connection to the OCSP server.

See OCSP stapling for further information.

Since version 3.1.3 GnuTLS clients transparently support the certificate
status request.

3.6.7 SRTP
----------

The TLS protocol was extended in [see RFC5764] to provide keying
material to the Secure RTP (SRTP) protocol.  The SRTP protocol provides
an encapsulation of encrypted data that is optimized for voice data.
With the SRTP TLS extension two peers can negotiate keys using TLS or
DTLS and obtain keying material for use with SRTP. The available SRTP
profiles are listed below.

'GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80'
     128 bit AES with a 80 bit HMAC-SHA1
'GNUTLS_SRTP_AES128_CM_HMAC_SHA1_32'
     128 bit AES with a 32 bit HMAC-SHA1
'GNUTLS_SRTP_NULL_HMAC_SHA1_80'
     NULL cipher with a 80 bit HMAC-SHA1
'GNUTLS_SRTP_NULL_HMAC_SHA1_32'
     NULL cipher with a 32 bit HMAC-SHA1

Figure 3.2: Supported SRTP profiles

To enable use the following functions.

'INT gnutls_srtp_set_profile (gnutls_session_t SESSION, gnutls_srtp_profile_t PROFILE)'
'INT gnutls_srtp_set_profile_direct (gnutls_session_t SESSION, const char * PROFILES, const char ** ERR_POS)'

To obtain the negotiated keys use the function below.

 -- Function: int gnutls_srtp_get_keys (gnutls_session_t SESSION, void *
          KEY_MATERIAL, unsigned int KEY_MATERIAL_SIZE, gnutls_datum_t *
          CLIENT_KEY, gnutls_datum_t * CLIENT_SALT, gnutls_datum_t *
          SERVER_KEY, gnutls_datum_t * SERVER_SALT)
     SESSION: is a 'gnutls_session_t' type.

     KEY_MATERIAL: Space to hold the generated key material

     KEY_MATERIAL_SIZE: The maximum size of the key material

     CLIENT_KEY: The master client write key, pointing inside the key
     material

     CLIENT_SALT: The master client write salt, pointing inside the key
     material

     SERVER_KEY: The master server write key, pointing inside the key
     material

     SERVER_SALT: The master server write salt, pointing inside the key
     material

     This is a helper function to generate the keying material for SRTP.
     It requires the space of the key material to be pre-allocated
     (should be at least 2x the maximum key size and salt size).  The
     'client_key' , 'client_salt' , 'server_key' and 'server_salt' are
     convenience datums that point inside the key material.  They may be
     'NULL' .

     *Returns:* On success the size of the key material is returned,
     otherwise, 'GNUTLS_E_SHORT_MEMORY_BUFFER' if the buffer given is
     not sufficient, or a negative error code.

     Since 3.1.4

Other helper functions are listed below.

'INT gnutls_srtp_get_selected_profile (gnutls_session_t SESSION, gnutls_srtp_profile_t * PROFILE)'
'CONST CHAR * See gnutls_srtp_get_profile_name (gnutls_srtp_profile_t PROFILE)'
'INT gnutls_srtp_get_profile_id (const char * NAME, gnutls_srtp_profile_t * PROFILE)'

3.6.8 False Start
-----------------

The TLS protocol was extended in [see RFC7918] to allow the client
to send data to server in a single round trip.  This change however
operates on the borderline of the TLS protocol security guarantees and
should be used for the cases where the reduced latency outperforms the
risk of an adversary intercepting the transferred data.  In GnuTLS
applications can use the GNUTLS_ENABLE_FALSE_START as option to
gnutls_init to request an early return of the gnutls_handshake
function.  After that early return the application is expected to
transfer any data to be piggybacked on the last handshake message.

After handshake's early termination, the application is expected to
transmit data using gnutls_record_send, and call
gnutls_record_recv on any received data as soon, to ensure that
handshake completes timely.  That is, especially relevant for
applications which set an explicit time limit for the handshake process
via gnutls_handshake_set_timeout.

Note however, that the API ensures that the early return will not happen
if the false start requirements are not satisfied.  That is, on
ciphersuites which are not whitelisted for false start or on
insufficient key sizes, the handshake process will complete properly
(i.e., no early return).  To verify that false start was used you may
use gnutls_session_get_flags and check for the
GNUTLS_SFLAGS_FALSE_START flag.  For GnuTLS the false start is
whitelisted for the following key exchange methods (see [see
RFC7918] for rationale)
   * DHE
   * ECDHE
but only when the negotiated parameters exceed 'GNUTLS_SEC_PARAM_HIGH'
-see Table 6.7, and when under (D)TLS 1.2 or later.

3.6.9 Application Layer Protocol Negotiation (ALPN)
---------------------------------------------------

The TLS protocol was extended in 'RFC7301' to provide the application
layer a method of negotiating the application protocol version.  This
allows for negotiation of the application protocol during the TLS
handshake, thus reducing round-trips.  The application protocol is
described by an opaque string.  To enable, use the following functions.

'INT gnutls_alpn_set_protocols (gnutls_session_t SESSION, const gnutls_datum_t * PROTOCOLS, unsigned PROTOCOLS_SIZE, unsigned int FLAGS)'
'INT gnutls_alpn_get_selected_protocol (gnutls_session_t SESSION, gnutls_datum_t * PROTOCOL)'

Note that these functions are intended to be used with protocols that
are registered in the Application Layer Protocol Negotiation IANA
registry.  While you can use them for other protocols (at the risk of
collisions), it is preferable to register them.

3.6.10 Extensions and Supplemental Data
---------------------------------------

It is possible to transfer supplemental data during the TLS handshake,
following [see RFC4680].  This is for "custom" protocol
modifications for applications which may want to transfer additional
data (e.g.  additional authentication messages).  Such an exchange
requires a custom extension to be registered.  The provided API for this
functionality is low-level and described in TLS Hello Extension Handling.

3.7 How to use TLS in application protocols
===========================================

This chapter is intended to provide some hints on how to use 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.

3.7.1 Separate ports
--------------------

Traditionally SSL was used in application protocols by assigning a new
port number for the secure services.  By doing this two separate ports
were assigned, one for the non-secure sessions, and one for the secure
sessions.  This method ensures that if a user requests a secure session
then the client will attempt to connect to the secure port and fail
otherwise.  The only possible attack with this method is to perform a
denial of service attack.  The most famous example of this method is
"HTTP over TLS" or HTTPS protocol [see RFC2818].

Despite its wide use, this method has several issues.  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
deprecated in favor of upward negotiation.

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

   (1) See also the Server Name Indication extension on
serverind.

3.7.2 Upward negotiation
------------------------

Other application protocols(1) use a different approach to enable the
secure layer.  They use something often called as 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 approach does not require any extra port to be
reserved.  There is even an extension to HTTP protocol to support this
method [see RFC2817].

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 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 naïve enough to send
the confidential data in the clear, despite the server telling the
client that it does not support "STARTTLS".

How do we avoid the above attack?  As you may have already noticed this
situation 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, or anything
else!

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

   (1) See LDAP, IMAP etc.

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 uses the same weak key, which isn't
     necessary.

Other protocols such as Microsoft's PCT 1 and PCT 2 were not implemented
because they were also abandoned and deprecated by SSL 3.0 and later TLS
1.0.

4 Authentication methods
************************

The initial key exchange of the TLS protocol performs authentication of
the peers.  In typical scenarios the server is authenticated to the
client, and optionally the client to the server.

While many associate TLS with X.509 certificates and public key
authentication, the protocol supports various authentication methods,
including pre-shared keys, and passwords.  In this chapter a description
of the existing authentication methods is provided, as well as some
guidance on which use-cases each method can be used at.

4.1 Certificate authentication
==============================

The most known authentication method of TLS are certificates.  The PKIX
[see PKIX] public key infrastructure is daily used by anyone using a
browser today.  GnuTLS provides a simple API to verify the X.509
certificates as in [see PKIX].

The key exchange algorithms supported by certificate authentication are
shown in Table 4.1.

Key exchange   Description

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

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.

ECDHE_RSA      The RSA algorithm is used to sign ephemeral
               elliptic curve Diffie-Hellman parameters which
               are sent to the peer.  The key in the
               certificate must allow the key to be used for
               signing.  It also offers 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 DSA 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.
               DSA is the algorithm of the Digital Signature
               Standard (DSS).

ECDHE_ECDSA    The Elliptic curve DSA algorithm is used to sign
               ephemeral elliptic curve Diffie-Hellman
               parameters which are sent to the peer.  The
               certificate must contain ECDSA parameters (i.e.,
               EC and marked for signing) to use this key
               exchange algorithm.

Table 4.1: Supported key exchange algorithms.

4.1.1 X.509 certificates
------------------------

The X.509 protocols rely on a hierarchical trust model.  In this trust
model Certification Authorities (CAs) are used to certify entities.
Usually more than one certification authorities exist, and certification
authorities may certify other authorities to issue certificates as well,
following a hierarchical model.

Figure 4.1: An example of the X.509 hierarchical trust model.

One needs to trust one or more CAs for his secure communications.  In
that case only the certificates issued by the trusted authorities are
acceptable.  The framework is illustrated on Figure 4.1.

4.1.1.1 X.509 certificate structure
...................................

An X.509 certificate usually contains information about the certificate
holder, the signer, a unique serial number, expiration dates and some
other fields [see PKIX] as shown in Table 4.2.

Field          Description

------------------------------------------------------------------
version        The field that indicates the version of the
               certificate.

serialNumber   This field holds a unique serial number per
               certificate.

signature      The issuing authority's signature.

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.

Table 4.2: X.509 certificate fields.

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

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 in ex-x509-info.

4.1.1.2 Importing an X.509 certificate
......................................

The certificate structure should be initialized using
gnutls_x509_crt_init, and a certificate structure can be imported
using gnutls_x509_crt_import.

'INT gnutls_x509_crt_init (gnutls_x509_crt_t * CERT)'
'INT gnutls_x509_crt_import (gnutls_x509_crt_t CERT, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
'VOID gnutls_x509_crt_deinit (gnutls_x509_crt_t CERT)'

In several functions an array of certificates is required.  To assist in
initialization and import the following two functions are provided.

'INT gnutls_x509_crt_list_import (gnutls_x509_crt_t * CERTS, unsigned int * CERT_MAX, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)'
'INT gnutls_x509_crt_list_import2 (gnutls_x509_crt_t ** CERTS, unsigned int * SIZE, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)'

In all cases after use a certificate must be deinitialized using
gnutls_x509_crt_deinit.  Note that although the functions above apply
to 'gnutls_x509_crt_t' structure, similar functions exist for the CRL
structure 'gnutls_x509_crl_t'.

4.1.1.3 X.509 certificate names
...............................

X.509 certificates allow for multiple names and types of names to be
specified.  CA certificates often rely on X.509 distinguished names (see
X.509 distinguished names) for unique identification, while
end-user and server certificates rely on the 'subject alternative
names'.  The subject alternative names provide a typed name, e.g., a DNS
name, or an email address, which identifies the owner of the
certificate.  The following functions provide access to that names.

'INT gnutls_x509_crt_get_subject_alt_name2 (gnutls_x509_crt_t CERT, unsigned int SEQ, void * SAN, size_t * SAN_SIZE, unsigned int * SAN_TYPE, unsigned int * CRITICAL)'
'INT gnutls_x509_crt_set_subject_alt_name (gnutls_x509_crt_t CRT, gnutls_x509_subject_alt_name_t TYPE, const void * DATA, unsigned int DATA_SIZE, unsigned int FLAGS)'
'INT gnutls_subject_alt_names_init (gnutls_subject_alt_names_t * SANS)'
'INT gnutls_subject_alt_names_get (gnutls_subject_alt_names_t SANS, unsigned int SEQ, unsigned int * SAN_TYPE, gnutls_datum_t * SAN, gnutls_datum_t * OTHERNAME_OID)'
'INT gnutls_subject_alt_names_set (gnutls_subject_alt_names_t SANS, unsigned int SAN_TYPE, const gnutls_datum_t * SAN, const char * OTHERNAME_OID)'

Note however, that server certificates often used the Common Name (CN),
part of the certificate DistinguishedName to place a single DNS address.
That practice is discouraged (see [see RFC6125]), because only a
single address can be specified, and the CN field is free-form making
matching ambiguous.

4.1.1.4 X.509 distinguished names
.................................

The "subject" of an X.509 certificate is not described by a single name,
but rather with a distinguished name.  This in X.509 terminology is a
list of strings each associated an object identifier.  To make things
simple GnuTLS provides gnutls_x509_crt_get_dn2 which follows the
rules in [see RFC4514] and returns a single string.  Access to each
string by individual object identifiers can be accessed using
gnutls_x509_crt_get_dn_by_oid.

 -- Function: int gnutls_x509_crt_get_dn2 (gnutls_x509_crt_t CERT,
          gnutls_datum_t * DN)
     CERT: should contain a 'gnutls_x509_crt_t' type

     DN: a pointer to a structure to hold the name; must be freed using
     'gnutls_free()'

     This function will allocate buffer and copy the name of the
     Certificate.  The name will be in the form "C=xxxx,O=yyyy,CN=zzzz"
     as described in RFC4514.  The output string will be ASCII or UTF-8
     encoded, depending on the certificate data.

     This function does not output a fully RFC4514 compliant string, if
     that is required see 'gnutls_x509_crt_get_dn3()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.10
'INT gnutls_x509_crt_get_dn (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)'
'INT gnutls_x509_crt_get_dn_by_oid (gnutls_x509_crt_t CERT, const char * OID, unsigned INDX, unsigned int RAW_FLAG, void * BUF, size_t * BUF_SIZE)'
'INT gnutls_x509_crt_get_dn_oid (gnutls_x509_crt_t CERT, unsigned INDX, void * OID, size_t * OID_SIZE)'

Similar functions exist to access the distinguished name of the issuer
of the certificate.

'INT gnutls_x509_crt_get_issuer_dn (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)'
'INT gnutls_x509_crt_get_issuer_dn2 (gnutls_x509_crt_t CERT, gnutls_datum_t * DN)'
'INT gnutls_x509_crt_get_issuer_dn_by_oid (gnutls_x509_crt_t CERT, const char * OID, unsigned INDX, unsigned int RAW_FLAG, void * BUF, size_t * BUF_SIZE)'
'INT gnutls_x509_crt_get_issuer_dn_oid (gnutls_x509_crt_t CERT, unsigned INDX, void * OID, size_t * OID_SIZE)'
'INT gnutls_x509_crt_get_issuer (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'

The more powerful gnutls_x509_crt_get_subject and
gnutls_x509_dn_get_rdn_ava provide efficient but low-level access to
the contents of the distinguished name structure.

'INT gnutls_x509_crt_get_subject (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'
'INT gnutls_x509_crt_get_issuer (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'

 -- Function: int gnutls_x509_dn_get_rdn_ava (gnutls_x509_dn_t DN, int
          IRDN, int IAVA, gnutls_x509_ava_st * AVA)
     DN: a pointer to DN

     IRDN: index of RDN

     IAVA: index of AVA.

     AVA: Pointer to structure which will hold output information.

     Get pointers to data within the DN. The format of the 'ava'
     structure is shown below.

     struct gnutls_x509_ava_st { gnutls_datum_t oid; gnutls_datum_t
     value; unsigned long value_tag; };

     The X.509 distinguished name is a sequence of sequences of strings
     and this is what the 'irdn' and 'iava' indexes model.

     Note that 'ava' will contain pointers into the 'dn' structure which
     in turns points to the original certificate.  Thus you should not
     modify any data or deallocate any of those.

     This is a low-level function that requires the caller to do the
     value conversions when necessary (e.g.  from UCS-2).

     *Returns:* Returns 0 on success, or an error code.

4.1.1.5 X.509 extensions
........................

X.509 version 3 certificates include a list of extensions that can be
used to obtain additional information on the subject or the issuer of
the certificate.  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 Table 4.3.

The certificate extensions access is split into two parts.  The first
requires to retrieve the extension, and the second is the parsing part.

To enumerate and retrieve the DER-encoded extension data available in a
certificate the following two functions are available.
'INT gnutls_x509_crt_get_extension_info (gnutls_x509_crt_t CERT, unsigned INDX, void * OID, size_t * OID_SIZE, unsigned int * CRITICAL)'
'INT gnutls_x509_crt_get_extension_data2 (gnutls_x509_crt_t CERT, unsigned INDX, gnutls_datum_t * DATA)'
'INT gnutls_x509_crt_get_extension_by_oid2 (gnutls_x509_crt_t CERT, const char * OID, unsigned INDX, gnutls_datum_t * OUTPUT, unsigned int * CRITICAL)'

After a supported DER-encoded extension is retrieved it can be parsed
using the APIs in 'x509-ext.h'.  Complex extensions may require
initializing an intermediate structure that holds the parsed extension
data.  Examples of simple parsing functions are shown below.
'INT gnutls_x509_ext_import_basic_constraints (const gnutls_datum_t * EXT, unsigned int * CA, int * PATHLEN)'
'INT gnutls_x509_ext_export_basic_constraints (unsigned int CA, int PATHLEN, gnutls_datum_t * EXT)'
'INT gnutls_x509_ext_import_key_usage (const gnutls_datum_t * EXT, unsigned int * KEY_USAGE)'
'INT gnutls_x509_ext_export_key_usage (unsigned int USAGE, gnutls_datum_t * EXT)'

More complex extensions, such as Name Constraints, require an
intermediate structure, in that case 'gnutls_x509_name_constraints_t' to
be initialized in order to store the parsed extension data.
'INT gnutls_x509_ext_import_name_constraints (const gnutls_datum_t * EXT, gnutls_x509_name_constraints_t NC, unsigned int FLAGS)'
'INT gnutls_x509_ext_export_name_constraints (gnutls_x509_name_constraints_t NC, gnutls_datum_t * EXT)'

After the name constraints are extracted in the structure, the following
functions can be used to access them.

'INT gnutls_x509_name_constraints_get_permitted (gnutls_x509_name_constraints_t NC, unsigned IDX, unsigned * TYPE, gnutls_datum_t * NAME)'
'INT gnutls_x509_name_constraints_get_excluded (gnutls_x509_name_constraints_t NC, unsigned IDX, unsigned * TYPE, gnutls_datum_t * NAME)'
'INT gnutls_x509_name_constraints_add_permitted (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
'INT gnutls_x509_name_constraints_add_excluded (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
'UNSIGNED gnutls_x509_name_constraints_check (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
'UNSIGNED gnutls_x509_name_constraints_check_crt (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, gnutls_x509_crt_t CERT)'

Other utility functions are listed below.
'INT gnutls_x509_name_constraints_init (gnutls_x509_name_constraints_t * NC)'
'VOID gnutls_x509_name_constraints_deinit (gnutls_x509_name_constraints_t NC)'

Similar functions exist for all of the other supported extensions,
listed in Table 4.3.

Extension              OID            Description

--------------------------------------------------------------------
Subject key id         2.5.29.14      An identifier of the key of
                                      the subject.

Key usage              2.5.29.15      Constraints the key's usage
                                      of the certificate.

Private key usage      2.5.29.16      Constraints the validity
period                                time of the private key.

Subject alternative    2.5.29.17      Alternative names to
name                                  subject's distinguished
                                      name.

Issuer alternative     2.5.29.18      Alternative names to the
name                                  issuer's distinguished
                                      name.

Basic constraints      2.5.29.19      Indicates whether this is a
                                      CA certificate or not, and
                                      specify the maximum path
                                      lengths of certificate
                                      chains.

Name constraints       2.5.29.30      A field in CA certificates
                                      that restricts the scope of
                                      the name of issued
                                      certificates.

CRL distribution       2.5.29.31      This extension is set by
points                                the CA, in order to inform
                                      about the location of
                                      issued Certificate
                                      Revocation Lists.

Certificate policy     2.5.29.32      This extension is set to
                                      indicate the certificate
                                      policy as object identifier
                                      and may contain a
                                      descriptive string or URL.

Extended key usage     2.5.29.54      Inhibit any policy
                                      extension.  Constraints the
                                      any policy OID
                                      ('GNUTLS_X509_OID_POLICY_ANY')
                                      use in the policy
                                      extension.

Authority key          2.5.29.35      An identifier of the key of
identifier                            the issuer of the
                                      certificate.  That is used
                                      to distinguish between
                                      different keys of the same
                                      issuer.

Extended key usage     2.5.29.37      Constraints the purpose of
                                      the certificate.

Authority              1.3.6.1.5.5.7.1.1Information on services by
information access                    the issuer of the
                                      certificate.

Proxy Certification    1.3.6.1.5.5.7.1.14Proxy Certificates includes
Information                           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 [see RFC3820].

Table 4.3: Supported X.509 certificate extensions.

Note, that there are also direct APIs to access extensions that may be
simpler to use for non-complex extensions.  They are available in
'x509.h' and some examples are listed below.
'INT gnutls_x509_crt_get_basic_constraints (gnutls_x509_crt_t CERT, unsigned int * CRITICAL, unsigned int * CA, int * PATHLEN)'
'INT gnutls_x509_crt_set_basic_constraints (gnutls_x509_crt_t CRT, unsigned int CA, int PATHLENCONSTRAINT)'
'INT gnutls_x509_crt_get_key_usage (gnutls_x509_crt_t CERT, unsigned int * KEY_USAGE, unsigned int * CRITICAL)'
'INT gnutls_x509_crt_set_key_usage (gnutls_x509_crt_t CRT, unsigned int USAGE)'

4.1.1.6 Accessing public and private keys
.........................................

Each X.509 certificate contains a public key that corresponds to a
private key.  To get a unique identifier of the public key the
gnutls_x509_crt_get_key_id function is provided.  To export the public
key or its parameters you may need to convert the X.509 structure to a
'gnutls_pubkey_t'.  See Abstract public keys for more
information.

 -- Function: int gnutls_x509_crt_get_key_id (gnutls_x509_crt_t CRT,
          unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t *
          OUTPUT_DATA_SIZE)
     CRT: Holds the certificate

     FLAGS: should be one of the flags from 'gnutls_keyid_flags_t'

     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 that depends on the public
     key parameters.  This ID can be used in checking whether a
     certificate corresponds to the given private 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.

     *Returns:* In case of failure a negative error code will be
     returned, and 0 on success.

The private key parameters may be directly accessed by using one of the
following functions.

'INT gnutls_x509_privkey_get_pk_algorithm2 (gnutls_x509_privkey_t KEY, unsigned int * BITS)'
'INT gnutls_x509_privkey_export_rsa_raw2 (gnutls_x509_privkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E, gnutls_datum_t * D, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * U, gnutls_datum_t * E1, gnutls_datum_t * E2)'
'INT gnutls_x509_privkey_export_ecc_raw (gnutls_x509_privkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y, gnutls_datum_t * K)'
'INT gnutls_x509_privkey_export_dsa_raw (gnutls_x509_privkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y, gnutls_datum_t * X)'
'INT gnutls_x509_privkey_get_key_id (gnutls_x509_privkey_t KEY, unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'

4.1.1.7 Verifying X.509 certificate paths
.........................................

Verifying certificate paths is important in X.509 authentication.  For
this purpose the following functions are provided.

 -- Function: int gnutls_x509_trust_list_add_cas
          (gnutls_x509_trust_list_t LIST, const gnutls_x509_crt_t *
          CLIST, unsigned CLIST_SIZE, unsigned int FLAGS)
     LIST: The list

     CLIST: A list of CAs

     CLIST_SIZE: The length of the CA list

     FLAGS: flags from 'gnutls_trust_list_flags_t'

     This function will add the given certificate authorities to the
     trusted list.  The CAs in 'clist' must not be deinitialized during
     the lifetime of 'list' .

     If the flag 'GNUTLS_TL_NO_DUPLICATES' is specified, then this
     function will ensure that no duplicates will be present in the
     final trust list.

     If the flag 'GNUTLS_TL_NO_DUPLICATE_KEY' is specified, then this
     function will ensure that no certificates with the same key are
     present in the final trust list.

     If either 'GNUTLS_TL_NO_DUPLICATE_KEY' or 'GNUTLS_TL_NO_DUPLICATES'
     are given, 'gnutls_x509_trust_list_deinit()' must be called with
     parameter 'all' being 1.

     *Returns:* The number of added elements is returned; that includes
     duplicate entries.

     *Since:* 3.0.0

 -- Function: int gnutls_x509_trust_list_add_named_crt
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t CERT, const
          void * NAME, size_t NAME_SIZE, unsigned int FLAGS)
     LIST: The list

     CERT: A certificate

     NAME: An identifier for the certificate

     NAME_SIZE: The size of the identifier

     FLAGS: should be 0.

     This function will add the given certificate to the trusted list
     and associate it with a name.  The certificate will not be be used
     for verification with 'gnutls_x509_trust_list_verify_crt()' but
     with 'gnutls_x509_trust_list_verify_named_crt()' or
     'gnutls_x509_trust_list_verify_crt2()' - the latter only since
     GnuTLS 3.4.0 and if a hostname is provided.

     In principle this function can be used to set individual "server"
     certificates that are trusted by the user for that specific server
     but for no other purposes.

     The certificate 'cert' must not be deinitialized during the
     lifetime of the 'list' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0.0

 -- Function: int gnutls_x509_trust_list_add_crls
          (gnutls_x509_trust_list_t LIST, const gnutls_x509_crl_t *
          CRL_LIST, unsigned CRL_SIZE, unsigned int FLAGS, unsigned int
          VERIFICATION_FLAGS)
     LIST: The list

     CRL_LIST: A list of CRLs

     CRL_SIZE: The length of the CRL list

     FLAGS: flags from 'gnutls_trust_list_flags_t'

     VERIFICATION_FLAGS: gnutls_certificate_verify_flags if flags
     specifies GNUTLS_TL_VERIFY_CRL

     This function will add the given certificate revocation lists to
     the trusted list.  The CRLs in 'crl_list' must not be deinitialized
     during the lifetime of 'list' .

     This function must be called after
     'gnutls_x509_trust_list_add_cas()' to allow verifying the CRLs for
     validity.  If the flag 'GNUTLS_TL_NO_DUPLICATES' is given, then the
     final CRL list will not contain duplicate entries.

     If the flag 'GNUTLS_TL_NO_DUPLICATES' is given,
     'gnutls_x509_trust_list_deinit()' must be called with parameter
     'all' being 1.

     If flag 'GNUTLS_TL_VERIFY_CRL' is given the CRLs will be verified
     before being added, and if verification fails, they will be
     skipped.

     *Returns:* The number of added elements is returned; that includes
     duplicate entries.

     *Since:* 3.0

 -- Function: int gnutls_x509_trust_list_verify_crt
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t * CERT_LIST,
          unsigned int CERT_LIST_SIZE, unsigned int FLAGS, unsigned int
          * VOUTPUT, gnutls_verify_output_function FUNC)
     LIST: The list

     CERT_LIST: is the certificate list to be verified

     CERT_LIST_SIZE: is the certificate list size

     FLAGS: Flags that may be used to change the verification algorithm.
     Use OR of the gnutls_certificate_verify_flags enumerations.

     VOUTPUT: will hold the certificate verification output.

     FUNC: If non-null will be called on each chain element verification
     with the output.

     This function will try to verify the given certificate and return
     its status.  The 'voutput' parameter will hold an OR'ed sequence of
     'gnutls_certificate_status_t' flags.

     The details of the verification are the same as in
     'gnutls_x509_trust_list_verify_crt2()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0

 -- Function: int gnutls_x509_trust_list_verify_crt2
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t * CERT_LIST,
          unsigned int CERT_LIST_SIZE, gnutls_typed_vdata_st * DATA,
          unsigned int ELEMENTS, unsigned int FLAGS, unsigned int *
          VOUTPUT, gnutls_verify_output_function FUNC)
     LIST: The list

     CERT_LIST: is the certificate list to be verified

     CERT_LIST_SIZE: is the certificate list size

     DATA: an array of typed data

     ELEMENTS: the number of data elements

     FLAGS: Flags that may be used to change the verification algorithm.
     Use OR of the gnutls_certificate_verify_flags enumerations.

     VOUTPUT: will hold the certificate verification output.

     FUNC: If non-null will be called on each chain element verification
     with the output.

     This function will attempt to verify the given certificate chain
     and return its status.  The 'voutput' parameter will hold an OR'ed
     sequence of 'gnutls_certificate_status_t' flags.

     When a certificate chain of 'cert_list_size' with more than one
     certificates is provided, the verification status will apply to the
     first certificate in the chain that failed verification.  The
     verification process starts from the end of the chain (from CA to
     end certificate).  The first certificate in the chain must be the
     end-certificate while the rest of the members may be sorted or not.

     Additionally a certificate verification profile can be specified
     from the ones in 'gnutls_certificate_verification_profiles_t' by
     ORing the result of 'GNUTLS_PROFILE_TO_VFLAGS()' to the
     verification flags.

     Additional verification parameters are possible via the 'data'
     types; the acceptable types are 'GNUTLS_DT_DNS_HOSTNAME' ,
     'GNUTLS_DT_IP_ADDRESS' and 'GNUTLS_DT_KEY_PURPOSE_OID' .  The
     former accepts as data a null-terminated hostname, and the latter a
     null-terminated object identifier (e.g., 'GNUTLS_KP_TLS_WWW_SERVER'
     ).  If a DNS hostname is provided then this function will compare
     the hostname in the end certificate against the given.  If names do
     not match the 'GNUTLS_CERT_UNEXPECTED_OWNER' status flag will be
     set.  In addition it will consider certificates provided with
     'gnutls_x509_trust_list_add_named_crt()' .

     If a key purpose OID is provided and the end-certificate contains
     the extended key usage PKIX extension, it will be required to match
     the provided OID or be marked for any purpose, otherwise
     verification will fail with 'GNUTLS_CERT_PURPOSE_MISMATCH' status.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.  Note that verification failure
     will not result to an error code, only 'voutput' will be updated.

     *Since:* 3.3.8

 -- Function: int gnutls_x509_trust_list_verify_named_crt
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t CERT, const
          void * NAME, size_t NAME_SIZE, unsigned int FLAGS, unsigned
          int * VOUTPUT, gnutls_verify_output_function FUNC)
     LIST: The list

     CERT: is the certificate to be verified

     NAME: is the certificate's name

     NAME_SIZE: is the certificate's name size

     FLAGS: Flags that may be used to change the verification algorithm.
     Use OR of the gnutls_certificate_verify_flags enumerations.

     VOUTPUT: will hold the certificate verification output.

     FUNC: If non-null will be called on each chain element verification
     with the output.

     This function will try to find a certificate that is associated
     with the provided name -see
     'gnutls_x509_trust_list_add_named_crt()' .  If a match is found the
     certificate is considered valid.  In addition to that this function
     will also check CRLs.  The 'voutput' parameter will hold an OR'ed
     sequence of 'gnutls_certificate_status_t' flags.

     Additionally a certificate verification profile can be specified
     from the ones in 'gnutls_certificate_verification_profiles_t' by
     ORing the result of 'GNUTLS_PROFILE_TO_VFLAGS()' to the
     verification flags.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0.0

 -- Function: int gnutls_x509_trust_list_add_trust_file
          (gnutls_x509_trust_list_t LIST, const char * CA_FILE, const
          char * CRL_FILE, gnutls_x509_crt_fmt_t TYPE, unsigned int
          TL_FLAGS, unsigned int TL_VFLAGS)
     LIST: The list

     CA_FILE: A file containing a list of CAs (optional)

     CRL_FILE: A file containing a list of CRLs (optional)

     TYPE: The format of the certificates

     TL_FLAGS: flags from 'gnutls_trust_list_flags_t'

     TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
     GNUTLS_TL_VERIFY_CRL

     This function will add the given certificate authorities to the
     trusted list.  PKCS '11' URLs are also accepted, instead of files,
     by this function.  A PKCS '11' URL implies a trust database (a
     specially marked module in p11-kit); the URL "pkcs11:" implies all
     trust databases in the system.  Only a single URL specifying trust
     databases can be set; they cannot be stacked with multiple calls.

     *Returns:* The number of added elements is returned.

     *Since:* 3.1

 -- Function: int gnutls_x509_trust_list_add_trust_mem
          (gnutls_x509_trust_list_t LIST, const gnutls_datum_t * CAS,
          const gnutls_datum_t * CRLS, gnutls_x509_crt_fmt_t TYPE,
          unsigned int TL_FLAGS, unsigned int TL_VFLAGS)
     LIST: The list

     CAS: A buffer containing a list of CAs (optional)

     CRLS: A buffer containing a list of CRLs (optional)

     TYPE: The format of the certificates

     TL_FLAGS: flags from 'gnutls_trust_list_flags_t'

     TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
     GNUTLS_TL_VERIFY_CRL

     This function will add the given certificate authorities to the
     trusted list.

     If this function is used 'gnutls_x509_trust_list_deinit()' must be
     called with parameter 'all' being 1.

     *Returns:* The number of added elements is returned.

     *Since:* 3.1

 -- Function: int gnutls_x509_trust_list_add_system_trust
          (gnutls_x509_trust_list_t LIST, unsigned int TL_FLAGS,
          unsigned int TL_VFLAGS)
     LIST: The structure of the list

     TL_FLAGS: GNUTLS_TL_*

     TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
     GNUTLS_TL_VERIFY_CRL

     This function adds the system's default trusted certificate
     authorities to the trusted list.  Note that on unsupported systems
     this function returns 'GNUTLS_E_UNIMPLEMENTED_FEATURE' .

     This function implies the flag 'GNUTLS_TL_NO_DUPLICATES' .

     *Returns:* The number of added elements or a negative error code on
     error.

     *Since:* 3.1

The verification function will verify a given certificate chain against
a list of certificate authorities and certificate revocation lists, and
output a bit-wise OR of elements of the 'gnutls_certificate_status_t'
enumeration shown in Figure 4.2.  The
'GNUTLS_CERT_INVALID' flag is always set on a verification error and
more detailed flags will also be set when appropriate.

'GNUTLS_CERT_INVALID'
     The certificate is not signed by one of the known authorities or
     the signature is invalid (deprecated by the flags
     'GNUTLS_CERT_SIGNATURE_FAILURE' and 'GNUTLS_CERT_SIGNER_NOT_FOUND'
     ).
'GNUTLS_CERT_REVOKED'
     Certificate is revoked by its authority.  In X.509 this will be set
     only if CRLs are checked.
'GNUTLS_CERT_SIGNER_NOT_FOUND'
     The certificate's issuer is not known.  This is the case if the
     issuer is not included in the trusted certificate 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.
'GNUTLS_CERT_NOT_ACTIVATED'
     The certificate is not yet activated.
'GNUTLS_CERT_EXPIRED'
     The certificate has expired.
'GNUTLS_CERT_SIGNATURE_FAILURE'
     The signature verification failed.
'GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED'
     The revocation data are old and have been superseded.
'GNUTLS_CERT_UNEXPECTED_OWNER'
     The owner is not the expected one.
'GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE'
     The revocation data have a future issue date.
'GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE'
     The certificate's signer constraints were violated.
'GNUTLS_CERT_MISMATCH'
     The certificate presented isn't the expected one (TOFU)
'GNUTLS_CERT_PURPOSE_MISMATCH'
     The certificate or an intermediate does not match the intended
     purpose (extended key usage).
'GNUTLS_CERT_MISSING_OCSP_STATUS'
     The certificate requires the server to send the certifiate status,
     but no status was received.
'GNUTLS_CERT_INVALID_OCSP_STATUS'
     The received OCSP status response is invalid.
'GNUTLS_CERT_UNKNOWN_CRIT_EXTENSIONS'
     The certificate has extensions marked as critical which are not
     supported.

Figure 4.2: The 'gnutls_certificate_status_t' enumeration.

An example of certificate verification is shown in ex-verify2.
It is also possible to have a set of certificates that are trusted for a
particular server but not to authorize other certificates.  This purpose
is served by the functions gnutls_x509_trust_list_add_named_crt
and gnutls_x509_trust_list_verify_named_crt.

4.1.1.8 Verifying a certificate in the context of TLS session
.............................................................

When operating in the context of a TLS session, the trusted certificate
authority list may also be set using:
'INT gnutls_certificate_set_x509_trust_file (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)'
'INT gnutls_certificate_set_x509_trust_dir (gnutls_certificate_credentials_t CRED, const char * CA_DIR, gnutls_x509_crt_fmt_t TYPE)'
'INT gnutls_certificate_set_x509_crl_file (gnutls_certificate_credentials_t RES, const char * CRLFILE, gnutls_x509_crt_fmt_t TYPE)'
'INT gnutls_certificate_set_x509_system_trust (gnutls_certificate_credentials_t CRED)'

These functions allow the specification of the trusted certificate
authorities, either via a file, a directory or use the system-specified
certificate authorities.  Unless the authorities are application
specific, it is generally recommended to use the system trust storage
(see gnutls_certificate_set_x509_system_trust).

Unlike the previous section it is not required to setup a trusted list,
and there are two approaches to verify the peer's certificate and
identity.  The recommended in GnuTLS 3.5.0 and later is via the
gnutls_session_set_verify_cert, but for older GnuTLS versions you may
use an explicit callback set via
gnutls_certificate_set_verify_function and then utilize
gnutls_certificate_verify_peers3 for verification.  The reported
verification status is identical to the verification functions described
in the previous section.

Note that in certain cases it is required to check the marked purpose of
the end certificate (e.g.  'GNUTLS_KP_TLS_WWW_SERVER'); in these cases
the more advanced gnutls_session_set_verify_cert2 and
gnutls_certificate_verify_peers should be used instead.

There is also the possibility to pass some input to the verification
functions in the form of flags.  For
gnutls_x509_trust_list_verify_crt2 the flags are passed directly, but
for gnutls_certificate_verify_peers3, the flags are set using
gnutls_certificate_set_verify_flags.  All the available flags
are part of the enumeration 'gnutls_certificate_verify_flags' shown in
Figure 4.3.

'GNUTLS_VERIFY_DISABLE_CA_SIGN'
     If set a signer does not have to be a certificate authority.  This
     flag should normally be disabled, unless you know what this means.
'GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES'
     When verifying a hostname prevent textual IP addresses from
     matching IP addresses in the certificate.  Treat the input only as
     a DNS name.
'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_ANY_X509_V1_CA_CRT'
     Allow CA certificates that have version 1 (both root and
     intermediate).  This might be dangerous since those haven't the
     basicConstraints extension.
'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2'
     Allow certificates to be signed using the broken MD2 algorithm.
'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5'
     Allow certificates to be signed using the broken MD5 algorithm.
'GNUTLS_VERIFY_DISABLE_TIME_CHECKS'
     Disable checking of activation and expiration validity periods of
     certificate chains.  Don't set this unless you understand the
     security implications.
'GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS'
     If set a signer in the trusted list is never checked for expiration
     or activation.
'GNUTLS_VERIFY_DO_NOT_ALLOW_X509_V1_CA_CRT'
     Do not allow trusted CA certificates that have version 1.  This
     option is to be used to deprecate all certificates of version 1.
'GNUTLS_VERIFY_DISABLE_CRL_CHECKS'
     Disable checking for validity using certificate revocation lists or
     the available OCSP data.
'GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN'
     A certificate chain is tolerated if unsorted (the case with many
     TLS servers out there).  This is the default since GnuTLS 3.1.4.
'GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN'
     Do not tolerate an unsorted certificate chain.
'GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS'
     When including a hostname check in the verification, do not
     consider any wildcards.
'GNUTLS_VERIFY_USE_TLS1_RSA'
     This indicates that a (raw) RSA signature is provided as in the TLS
     1.0 protocol.  Not all functions accept this flag.
'GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS'
     This signals the verification process, not to fail on unknown
     critical extensions.
'GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1'
     Allow certificates to be signed using the broken SHA1 hash
     algorithm.

Figure 4.3: The 'gnutls_certificate_verify_flags' enumeration.

4.1.1.9 Verifying a certificate using PKCS #11
..............................................

Some systems provide a system wide trusted certificate storage
accessible using the PKCS #11 API. That is, the trusted certificates are
queried and accessed using the PKCS #11 API, and trusted certificate
properties, such as purpose, are marked using attached extensions.  One
example is the p11-kit trust module(1).

These special PKCS #11 modules can be used for GnuTLS certificate
verification if marked as trust policy modules, i.e., with
'trust-policy: yes' in the p11-kit module file.  The way to use them is
by specifying to the file verification function (e.g., see
gnutls_certificate_set_x509_trust_file), a pkcs11 URL, or simply
'pkcs11:' to use all the marked with trust policy modules.

The trust modules of p11-kit assign a purpose to trusted authorities
using the extended key usage object identifiers.  The common purposes
are shown in Table 4.4.  Note that typically
according to [see RFC5280] the extended key usage object identifiers
apply to end certificates.  Their application to CA certificates is an
extension used by the trust modules.

Purpose        OID            Description

--------------------------------------------------------------------------
GNUTLS_KP_TLS_WWW_SERVER1.3.6.1.5.5.7.3.1The certificate is to be used for TLS WWW
                              authentication.  When in a CA
                              certificate, it indicates that the CA is
                              allowed to sign certificates for TLS WWW
                              authentication.

GNUTLS_KP_TLS_WWW_CLIENT1.3.6.1.5.5.7.3.2The certificate is to be used for TLS WWW
                              client authentication.  When in a CA
                              certificate, it indicates that the CA is
                              allowed to sign certificates for TLS WWW
                              client authentication.

GNUTLS_KP_CODE_SIGNING1.3.6.1.5.5.7.3.3The certificate is to be used for code
                              signing.  When in a CA certificate, it
                              indicates that the CA is allowed to sign
                              certificates for code signing.

GNUTLS_KP_EMAIL_PROTECTION1.3.6.1.5.5.7.3.4The certificate is to be used for email
                              protection.  When in a CA certificate, it
                              indicates that the CA is allowed to sign
                              certificates for email users.

GNUTLS_KP_OCSP_SIGNING1.3.6.1.5.5.7.3.9The certificate is to be used for signing
                              OCSP responses.  When in a CA
                              certificate, it indicates that the CA is
                              allowed to sign certificates which sign
                              OCSP responses.

GNUTLS_KP_ANY  2.5.29.37.0    The certificate is to be used for any
                              purpose.  When in a CA certificate, it
                              indicates that the CA is allowed to sign
                              any kind of certificates.

Table 4.4: Key purpose object identifiers.

With such modules, it is recommended to use the verification functions
gnutls_x509_trust_list_verify_crt2, or
gnutls_certificate_verify_peers, which allow to explicitly specify the
key purpose.  The other verification functions which do not allow
setting a purpose, would operate as if 'GNUTLS_KP_TLS_WWW_SERVER' was
requested from the trusted authorities.

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

   (1) see <https://p11-glue.github.io/p11-glue/trust-module.html>.

4.1.2 OpenPGP certificates
--------------------------

Previous versions of GnuTLS supported limited OpenPGP key
authentication.  That functionality has been deprecated and is no longer
made available.  The reason is that, supporting alternative
authentication methods, when X.509 and PKIX were new on the Internet and
not well established, seemed like a good idea, in today's Internet X.509
is unquestionably the main container for certificates.  As such
supporting more options with no clear use-cases, is a distraction that
consumes considerable resources for improving and testing the library.
For that we have decided to drop this functionality completely in 3.6.0.

4.1.3 Raw public-keys
---------------------

There are situations in which a rather large certificate / certificate
chain is undesirable or impractical.  An example could be a resource
constrained sensor network in which you do want to use authentication of
and encryption between your devices but where your devices lack loads of
memory or processing power.  Furthermore, there are situations in which
you don't want to or can't rely on a PKIX. TLS is, next to a PKIX
environment, also commonly used with self-signed certificates in smaller
deployments where the self-signed certificates are distributed to all
involved protocol endpoints out-of-band.  This practice does, however,
still require the overhead of the certificate generation even though
none of the information found in the certificate is actually used.

With raw public-keys, only a subset of the information found in typical
certificates is utilized: namely, the SubjectPublicKeyInfo structure (in
ASN.1 format) of a PKIX certificate that carries the parameters
necessary to describe the public-key.  Other parameters found in PKIX
certificates are omitted.  By omitting various certificate-related
structures, the resulting raw public-key is kept fairly small in
comparison to the original certificate, and the code to process the keys
can be simpler.

It should be noted however, that the authenticity of these raw keys must
be verified by an out-of-band mechanism or something like TOFU.

4.1.3.1 Importing raw public-keys
.................................

Raw public-keys and their private counterparts can best be handled by
using the abstract types 'gnutls_pubkey_t' and 'gnutls_privkey_t'
respectively.  To learn how to use these see Abstract key types.

4.1.4 Advanced certificate verification
---------------------------------------

The verification of X.509 certificates in the HTTPS and other Internet
protocols is typically done by loading a trusted list of commercial
Certificate Authorities (see
gnutls_certificate_set_x509_system_trust), and using them as trusted
anchors.  However, there are several examples (eg.  the Diginotar
incident) where one of these authorities was compromised.  This risk can
be mitigated by using in addition to CA certificate verification, other
verification methods.  In this section we list the available in GnuTLS
methods.

4.1.4.1 Verifying a certificate using trust on first use authentication
.......................................................................

It is possible to use a trust on first use (TOFU) authentication method
in GnuTLS. That is the concept used by the SSH programs, where the
public key of the peer is not verified, or verified in an out-of-bound
way, but subsequent connections to the same peer require the public key
to remain the same.  Such a system in combination with the typical CA
verification of a certificate, and OCSP revocation checks, can help to
provide multiple factor verification, where a single point of failure is
not enough to compromise the system.  For example a server compromise
may be detected using OCSP, and a CA compromise can be detected using
the trust on first use method.  Such a hybrid system with X.509 and
trust on first use authentication is shown in Client example with SSH-style certificate verification.

See Certificate verification on how to use the available
functionality.

4.1.4.2 Verifying a certificate using DANE (DNSSEC)
...................................................

The DANE protocol is a protocol that can be used to verify TLS
certificates using the DNS (or better DNSSEC) protocols.  The DNS
security extensions (DNSSEC) provide an alternative public key
infrastructure to the commercial CAs that are typically used to sign TLS
certificates.  The DANE protocol takes advantage of the DNSSEC
infrastructure to verify TLS certificates.  This can be in addition to
the verification by CA infrastructure or may even replace it where
DNSSEC is fully deployed.  Note however, that DNSSEC deployment is
fairly new and it would be better to use it as an additional
verification method rather than the only one.

The DANE functionality is provided by the 'libgnutls-dane' library that
is shipped with GnuTLS and the function prototypes are in
'gnutls/dane.h'.  See Certificate verification for information
on how to use the library.

Note however, that the DANE RFC mandates the verification methods one
should use in addition to the validation via DNSSEC TLSA entries.
GnuTLS doesn't follow that RFC requirement, and the term DANE
verification in this manual refers to the TLSA entry verification.  In
GnuTLS any other verification methods can be used (e.g., PKIX or TOFU)
on top of DANE.

4.1.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 they 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 [see WEGER].

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.

4.1.5.1 Trading security for interoperability
.............................................

If you connect to a server and use GnuTLS' functions to verify the
certificate chain, and get a 'GNUTLS_CERT_INSECURE_ALGORITHM' validation
error (see 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 fails verifying 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.

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
self-signed using 'RSA-MD2' or 'RSA-MD5'.  The certificates in the
trusted list are considered trusted irrespective of the signature.

If you are using gnutls_certificate_verify_peers3 to verify the
certificate chain, you can call
gnutls_certificate_set_verify_flags with the flags:
   * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2'
   * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5'
   * 'GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1'
   * 'GNUTLS_VERIFY_ALLOW_BROKEN'
as in the following example:

       gnutls_certificate_set_verify_flags (x509cred,
                                            GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5);

This will signal the verifier algorithm to enable 'RSA-MD5' when
verifying the certificates.

If you are using gnutls_x509_crt_verify or
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 gnutls_certificate_get_peers to extract
the raw server's certificate chain, see gnutls_x509_crt_list_import
to parse each of the certificates, and then
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.

4.2 More on certificate authentication
======================================

Certificates are not the only structures involved in a public key
infrastructure.  Several other structures that are used for certificate
requests, encrypted private keys, revocation lists, GnuTLS abstract key
structures, etc., are discussed in this chapter.

4.2.1 PKCS #10 certificate requests
-----------------------------------

A certificate request is a structure, which contain information about an
applicant of a certificate service.  It typically contains a public key,
a distinguished name and secondary data such as a challenge password.
GnuTLS supports the requests defined in PKCS #10 [see RFC2986].
Other formats of certificate requests are not currently supported by
GnuTLS.

A certificate request can be generated by associating it with a private
key, setting the subject's information and finally self signing it.  The
last step ensures that the requester is in possession of the private
key.

'INT gnutls_x509_crq_set_version (gnutls_x509_crq_t CRQ, unsigned int VERSION)'
'INT gnutls_x509_crq_set_dn (gnutls_x509_crq_t CRQ, const char * DN, const char ** ERR)'
'INT gnutls_x509_crq_set_dn_by_oid (gnutls_x509_crq_t CRQ, const char * OID, unsigned int RAW_FLAG, const void * DATA, unsigned int SIZEOF_DATA)'
'INT gnutls_x509_crq_set_key_usage (gnutls_x509_crq_t CRQ, unsigned int USAGE)'
'INT gnutls_x509_crq_set_key_purpose_oid (gnutls_x509_crq_t CRQ, const void * OID, unsigned int CRITICAL)'
'INT gnutls_x509_crq_set_basic_constraints (gnutls_x509_crq_t CRQ, unsigned int CA, int PATHLENCONSTRAINT)'

The gnutls_x509_crq_set_key and gnutls_x509_crq_sign2
functions associate the request with a private key and sign it.  If a
request is to be signed with a key residing in a PKCS #11 token it is
recommended to use the signing functions shown in Abstract key types.

 -- Function: int gnutls_x509_crq_set_key (gnutls_x509_crq_t CRQ,
          gnutls_x509_privkey_t KEY)
     CRQ: should contain a 'gnutls_x509_crq_t' type

     KEY: holds a private key

     This function will set the public parameters from the given private
     key to the request.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

 -- Function: int gnutls_x509_crq_sign2 (gnutls_x509_crq_t CRQ,
          gnutls_x509_privkey_t KEY, gnutls_digest_algorithm_t DIG,
          unsigned int FLAGS)
     CRQ: should contain a 'gnutls_x509_crq_t' type

     KEY: holds a private key

     DIG: The message digest to use, i.e., 'GNUTLS_DIG_SHA256'

     FLAGS: must be 0

     This function will sign the certificate request with a private key.
     This must be the same key as the one used in
     'gnutls_x509_crt_set_key()' since a certificate request is self
     signed.

     This must be the last step in a certificate request generation
     since all the previously set parameters are now signed.

     A known limitation of this function is, that a newly-signed request
     will not be fully functional (e.g., for signature verification),
     until it is exported an re-imported.

     After GnuTLS 3.6.1 the value of 'dig' may be 'GNUTLS_DIG_UNKNOWN' ,
     and in that case, a suitable but reasonable for the key algorithm
     will be selected.

     *Returns:* 'GNUTLS_E_SUCCESS' on success, otherwise a negative
     error code.  'GNUTLS_E_ASN1_VALUE_NOT_FOUND' is returned if you
     didn't set all information in the certificate request (e.g., the
     version using 'gnutls_x509_crq_set_version()' ).

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

        /* Generate an RSA key of moderate security.
         */
        bits =
            gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA,
                                        GNUTLS_SEC_PARAM_MEDIUM);
        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_x509_crq_sign2(crq, key, 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;

}

4.2.2 PKIX certificate revocation lists
---------------------------------------

A certificate revocation list (CRL) is a structure issued by an
authority periodically containing a list of revoked certificates serial
numbers.  The CRL structure is signed with the issuing authorities'
keys.  A typical CRL contains the fields as shown in Table 4.5.
Certificate revocation lists are used to complement the
expiration date of a certificate, in order to account for other reasons
of revocation, such as compromised keys, etc.

Each CRL is valid for limited amount of time and is required to provide,
except for the current issuing time, also the issuing time of the next
update.

Field          Description

------------------------------------------------------------------
version        The field that indicates the version of the CRL
               structure.

signature      A signature by the issuing authority.

issuer         Holds the issuer's distinguished name.

thisUpdate     The issuing time of the revocation list.

nextUpdate     The issuing time of the revocation list that
               will update that one.

revokedCertificatesList of revoked certificates serial numbers.

extensions     Optional CRL structure extensions.

Table 4.5: Certificate revocation list fields.

The basic CRL structure functions follow.

'INT gnutls_x509_crl_init (gnutls_x509_crl_t * CRL)'
'INT gnutls_x509_crl_import (gnutls_x509_crl_t CRL, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
'INT gnutls_x509_crl_export (gnutls_x509_crl_t CRL, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
'INT gnutls_x509_crl_export (gnutls_x509_crl_t CRL, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'

Reading a CRL
.............

The most important function that extracts the certificate revocation
information from a CRL is gnutls_x509_crl_get_crt_serial.  Other
functions that return other fields of the CRL structure are also
provided.

 -- Function: int gnutls_x509_crl_get_crt_serial (gnutls_x509_crl_t CRL,
          unsigned INDX, unsigned char * SERIAL, size_t * SERIAL_SIZE,
          time_t * T)
     CRL: should contain a 'gnutls_x509_crl_t' type

     INDX: the index of the certificate to extract (starting from 0)

     SERIAL: where the serial number will be copied

     SERIAL_SIZE: initially holds the size of serial

     T: if non null, will hold the time this certificate was revoked

     This function will retrieve the serial number of the specified, by
     the index, revoked certificate.

     Note that this function will have performance issues in large
     sequences of revoked certificates.  In that case use
     'gnutls_x509_crl_iter_crt_serial()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

'INT gnutls_x509_crl_get_version (gnutls_x509_crl_t CRL)'
'INT gnutls_x509_crl_get_issuer_dn (gnutls_x509_crl_t CRL, char * BUF, size_t * SIZEOF_BUF)'
'INT gnutls_x509_crl_get_issuer_dn2 (gnutls_x509_crl_t CRL, gnutls_datum_t * DN)'
'TIME_T gnutls_x509_crl_get_this_update (gnutls_x509_crl_t CRL)'
'TIME_T gnutls_x509_crl_get_next_update (gnutls_x509_crl_t CRL)'
'INT gnutls_x509_crl_get_crt_count (gnutls_x509_crl_t CRL)'

Generation of a CRL
...................

The following functions can be used to generate a CRL.

'INT gnutls_x509_crl_set_version (gnutls_x509_crl_t CRL, unsigned int VERSION)'
'INT gnutls_x509_crl_set_crt_serial (gnutls_x509_crl_t CRL, const void * SERIAL, size_t SERIAL_SIZE, time_t REVOCATION_TIME)'
'INT gnutls_x509_crl_set_crt (gnutls_x509_crl_t CRL, gnutls_x509_crt_t CRT, time_t REVOCATION_TIME)'
'INT gnutls_x509_crl_set_next_update (gnutls_x509_crl_t CRL, time_t EXP_TIME)'
'INT gnutls_x509_crl_set_this_update (gnutls_x509_crl_t CRL, time_t ACT_TIME)'

The gnutls_x509_crl_sign2 and
gnutls_x509_crl_privkey_sign functions sign the revocation list with a
private key.  The latter function can be used to sign with a key
residing in a PKCS #11 token.

 -- Function: int gnutls_x509_crl_sign2 (gnutls_x509_crl_t CRL,
          gnutls_x509_crt_t ISSUER, gnutls_x509_privkey_t ISSUER_KEY,
          gnutls_digest_algorithm_t DIG, unsigned int FLAGS)
     CRL: should contain a gnutls_x509_crl_t type

     ISSUER: is the certificate of the certificate issuer

     ISSUER_KEY: holds the issuer's private key

     DIG: The message digest to use.  GNUTLS_DIG_SHA256 is the safe
     choice unless you know what you're doing.

     FLAGS: must be 0

     This function will sign the CRL with the issuer's private key, and
     will copy the issuer's information into the CRL.

     This must be the last step in a certificate CRL since all the
     previously set parameters are now signed.

     A known limitation of this function is, that a newly-signed CRL
     will not be fully functional (e.g., for signature verification),
     until it is exported an re-imported.

     After GnuTLS 3.6.1 the value of 'dig' may be 'GNUTLS_DIG_UNKNOWN' ,
     and in that case, a suitable but reasonable for the key algorithm
     will be selected.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

 -- Function: int gnutls_x509_crl_privkey_sign (gnutls_x509_crl_t CRL,
          gnutls_x509_crt_t ISSUER, gnutls_privkey_t ISSUER_KEY,
          gnutls_digest_algorithm_t DIG, unsigned int FLAGS)
     CRL: should contain a gnutls_x509_crl_t type

     ISSUER: is the certificate of the certificate issuer

     ISSUER_KEY: holds the issuer's private key

     DIG: The message digest to use.  GNUTLS_DIG_SHA256 is the safe
     choice unless you know what you're doing.

     FLAGS: must be 0

     This function will sign the CRL with the issuer's private key, and
     will copy the issuer's information into the CRL.

     This must be the last step in a certificate CRL since all the
     previously set parameters are now signed.

     A known limitation of this function is, that a newly-signed CRL
     will not be fully functional (e.g., for signature verification),
     until it is exported an re-imported.

     After GnuTLS 3.6.1 the value of 'dig' may be 'GNUTLS_DIG_UNKNOWN' ,
     and in that case, a suitable but reasonable for the key algorithm
     will be selected.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     Since 2.12.0

Few extensions on the CRL structure are supported, including the CRL
number extension and the authority key identifier.

'INT gnutls_x509_crl_set_number (gnutls_x509_crl_t CRL, const void * NR, size_t NR_SIZE)'
'INT gnutls_x509_crl_set_authority_key_id (gnutls_x509_crl_t CRL, const void * ID, size_t ID_SIZE)'

4.2.3 OCSP certificate status checking
--------------------------------------

Certificates may be revoked before their expiration time has been
reached.  There are several reasons for revoking certificates, but a
typical situation is when the private key associated with a certificate
has been compromised.  Traditionally, Certificate Revocation Lists
(CRLs) have been used by application to implement revocation checking,
however, several problems with CRLs have been identified [see
RIVESTCRL].

The Online Certificate Status Protocol, or OCSP [see RFC2560], is a
widely implemented protocol which performs certificate revocation status
checking.  An application that wish to verify the identity of a peer
will verify the certificate against a set of trusted certificates and
then check whether the certificate is listed in a CRL and/or perform an
OCSP check for the certificate.

Applications are typically expected to contact the OCSP server in order
to request the certificate validity status.  The OCSP server replies
with an OCSP response.  This section describes this online communication
(which can be avoided when using OCSP stapled responses, for that, see
OCSP stapling).

Before performing the OCSP query, the application will need to figure
out the address of the OCSP server.  The OCSP server address can be
provided by the local user in manual configuration or may be stored in
the certificate that is being checked.  When stored in a certificate the
OCSP server is in the extension field called the Authority Information
Access (AIA). The following function extracts this information from a
certificate.

'INT gnutls_x509_crt_get_authority_info_access (gnutls_x509_crt_t CRT, unsigned int SEQ, int WHAT, gnutls_datum_t * DATA, unsigned int * CRITICAL)'

There are several functions in GnuTLS for creating and manipulating OCSP
requests and responses.  The general idea is that a client application
creates an OCSP request object, stores some information about the
certificate to check in the request, and then exports the request in DER
format.  The request will then need to be sent to the OCSP responder,
which needs to be done by the application (GnuTLS does not send and
receive OCSP packets).  Normally an OCSP response is received that the
application will need to import into an OCSP response object.  The
digital signature in the OCSP response needs to be verified against a
set of trust anchors before the information in the response can be
trusted.

The ASN.1 structure of OCSP requests are briefly as follows.  It is
useful to review the structures to get an understanding of which fields
are modified by GnuTLS functions.

     OCSPRequest     ::=     SEQUENCE {
         tbsRequest                  TBSRequest,
         optionalSignature   [0]     EXPLICIT Signature OPTIONAL }

     TBSRequest      ::=     SEQUENCE {
         version             [0]     EXPLICIT Version DEFAULT v1,
         requestorName       [1]     EXPLICIT GeneralName OPTIONAL,
         requestList                 SEQUENCE OF Request,
         requestExtensions   [2]     EXPLICIT Extensions OPTIONAL }

     Request         ::=     SEQUENCE {
         reqCert                     CertID,
         singleRequestExtensions     [0] EXPLICIT Extensions OPTIONAL }

     CertID          ::=     SEQUENCE {
         hashAlgorithm       AlgorithmIdentifier,
         issuerNameHash      OCTET STRING, -- Hash of Issuer's DN
         issuerKeyHash       OCTET STRING, -- Hash of Issuers public key
         serialNumber        CertificateSerialNumber }

The basic functions to initialize, import, export and deallocate OCSP
requests are the following.

'INT gnutls_ocsp_req_init (gnutls_ocsp_req_t * REQ)'
'VOID gnutls_ocsp_req_deinit (gnutls_ocsp_req_t REQ)'
'INT gnutls_ocsp_req_import (gnutls_ocsp_req_t REQ, const gnutls_datum_t * DATA)'
'INT gnutls_ocsp_req_export (gnutls_ocsp_req_const_t REQ, gnutls_datum_t * DATA)'
'INT gnutls_ocsp_req_print (gnutls_ocsp_req_const_t REQ, gnutls_ocsp_print_formats_t FORMAT, gnutls_datum_t * OUT)'

To generate an OCSP request the issuer name hash, issuer key hash, and
the checked certificate's serial number are required.  There are two
interfaces available for setting those in an OCSP request.  The is a
low-level function when you have the issuer name hash, issuer key hash,
and certificate serial number in binary form.  The second is more useful
if you have the certificate (and its issuer) in a 'gnutls_x509_crt_t'
type.  There is also a function to extract this information from
existing an OCSP request.

'INT gnutls_ocsp_req_add_cert_id (gnutls_ocsp_req_t REQ, gnutls_digest_algorithm_t DIGEST, const gnutls_datum_t * ISSUER_NAME_HASH, const gnutls_datum_t * ISSUER_KEY_HASH, const gnutls_datum_t * SERIAL_NUMBER)'
'INT gnutls_ocsp_req_add_cert (gnutls_ocsp_req_t REQ, gnutls_digest_algorithm_t DIGEST, gnutls_x509_crt_t ISSUER, gnutls_x509_crt_t CERT)'
'INT gnutls_ocsp_req_get_cert_id (gnutls_ocsp_req_const_t REQ, unsigned INDX, gnutls_digest_algorithm_t * DIGEST, gnutls_datum_t * ISSUER_NAME_HASH, gnutls_datum_t * ISSUER_KEY_HASH, gnutls_datum_t * SERIAL_NUMBER)'

Each OCSP request may contain a number of extensions.  Extensions are
identified by an Object Identifier (OID) and an opaque data buffer whose
syntax and semantics is implied by the OID. You can extract or set those
extensions using the following functions.

'INT gnutls_ocsp_req_get_extension (gnutls_ocsp_req_const_t REQ, unsigned INDX, gnutls_datum_t * OID, unsigned int * CRITICAL, gnutls_datum_t * DATA)'
'INT gnutls_ocsp_req_set_extension (gnutls_ocsp_req_t REQ, const char * OID, unsigned int CRITICAL, const gnutls_datum_t * DATA)'

A common OCSP Request extension is the nonce extension (OID
1.3.6.1.5.5.7.48.1.2), which is used to avoid replay attacks of earlier
recorded OCSP responses.  The nonce extension carries a value that is
intended to be sufficiently random and unique so that an attacker will
not be able to give a stale response for the same nonce.

'INT gnutls_ocsp_req_get_nonce (gnutls_ocsp_req_const_t REQ, unsigned int * CRITICAL, gnutls_datum_t * NONCE)'
'INT gnutls_ocsp_req_set_nonce (gnutls_ocsp_req_t REQ, unsigned int CRITICAL, const gnutls_datum_t * NONCE)'
'INT gnutls_ocsp_req_randomize_nonce (gnutls_ocsp_req_t REQ)'

The OCSP response structures is a complex structure.  A simplified
overview of it is in Table 4.6.  Note that a
response may contain information on multiple certificates.

Field          Description

------------------------------------------------------------------
version        The OCSP response version number (typically 1).

responder ID   An identifier of the responder (DN name or a
               hash of its key).

issue time     The time the response was generated.

thisUpdate     The issuing time of the revocation information.

nextUpdate     The issuing time of the revocation information
               that will update that one.

               Revoked certificates

certificate    The status of the certificate.
status
certificate    The certificate's serial number.
serial
revocationTime The time the certificate was revoked.

revocationReasonThe reason the certificate was revoked.

Table 4.6: The most important OCSP response fields.

We provide basic functions for initialization, importing, exporting and
deallocating OCSP responses.

'INT gnutls_ocsp_resp_init (gnutls_ocsp_resp_t * RESP)'
'VOID gnutls_ocsp_resp_deinit (gnutls_ocsp_resp_t RESP)'
'INT gnutls_ocsp_resp_import (gnutls_ocsp_resp_t RESP, const gnutls_datum_t * DATA)'
'INT gnutls_ocsp_resp_export (gnutls_ocsp_resp_const_t RESP, gnutls_datum_t * DATA)'
'INT gnutls_ocsp_resp_print (gnutls_ocsp_resp_const_t RESP, gnutls_ocsp_print_formats_t FORMAT, gnutls_datum_t * OUT)'

The utility function that extracts the revocation as well as other
information from a response is shown below.

 -- Function: int gnutls_ocsp_resp_get_single (gnutls_ocsp_resp_const_t
          RESP, unsigned INDX, gnutls_digest_algorithm_t * DIGEST,
          gnutls_datum_t * ISSUER_NAME_HASH, gnutls_datum_t *
          ISSUER_KEY_HASH, gnutls_datum_t * SERIAL_NUMBER, unsigned int
          * CERT_STATUS, time_t * THIS_UPDATE, time_t * NEXT_UPDATE,
          time_t * REVOCATION_TIME, unsigned int * REVOCATION_REASON)
     RESP: should contain a 'gnutls_ocsp_resp_t' type

     INDX: Specifies response number to get.  Use (0) to get the first
     one.

     DIGEST: output variable with 'gnutls_digest_algorithm_t' hash
     algorithm

     ISSUER_NAME_HASH: output buffer with hash of issuer's DN

     ISSUER_KEY_HASH: output buffer with hash of issuer's public key

     SERIAL_NUMBER: output buffer with serial number of certificate to
     check

     CERT_STATUS: a certificate status, a 'gnutls_ocsp_cert_status_t'
     enum.

     THIS_UPDATE: time at which the status is known to be correct.

     NEXT_UPDATE: when newer information will be available, or
     (time_t)-1 if unspecified

     REVOCATION_TIME: when 'cert_status' is 'GNUTLS_OCSP_CERT_REVOKED' ,
     holds time of revocation.

     REVOCATION_REASON: revocation reason, a 'gnutls_x509_crl_reason_t'
     enum.

     This function will return the certificate information of the 'indx'
     'ed response in the Basic OCSP Response 'resp' .  The information
     returned corresponds to the OCSP SingleResponse structure except
     the final singleExtensions.

     Each of the pointers to output variables may be NULL to indicate
     that the caller is not interested in that value.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error code is returned.  If you have reached
     the last CertID available 'GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE'
     will be returned.

The possible revocation reasons available in an OCSP response are shown
below.

'GNUTLS_X509_CRLREASON_UNSPECIFIED'
     Unspecified reason.
'GNUTLS_X509_CRLREASON_KEYCOMPROMISE'
     Private key compromised.
'GNUTLS_X509_CRLREASON_CACOMPROMISE'
     CA compromised.
'GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED'
     Affiliation has changed.
'GNUTLS_X509_CRLREASON_SUPERSEDED'
     Certificate superseded.
'GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION'
     Operation has ceased.
'GNUTLS_X509_CRLREASON_CERTIFICATEHOLD'
     Certificate is on hold.
'GNUTLS_X509_CRLREASON_REMOVEFROMCRL'
     Will be removed from delta CRL.
'GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN'
     Privilege withdrawn.
'GNUTLS_X509_CRLREASON_AACOMPROMISE'
     AA compromised.

Figure 4.4: The revocation reasons

Note, that the OCSP response needs to be verified against some set of
trust anchors before it can be relied upon.  It is also important to
check whether the received OCSP response corresponds to the certificate
being checked.

'INT gnutls_ocsp_resp_verify (gnutls_ocsp_resp_const_t RESP, gnutls_x509_trust_list_t TRUSTLIST, unsigned int * VERIFY, unsigned int FLAGS)'
'INT gnutls_ocsp_resp_verify_direct (gnutls_ocsp_resp_const_t RESP, gnutls_x509_crt_t ISSUER, unsigned int * VERIFY, unsigned int FLAGS)'
'INT gnutls_ocsp_resp_check_crt (gnutls_ocsp_resp_const_t RESP, unsigned int INDX, gnutls_x509_crt_t CRT)'

4.2.4 OCSP stapling
-------------------

To avoid applications contacting the OCSP server directly, TLS servers
can provide a "stapled" OCSP response in the TLS handshake.  That way
the client application needs to do nothing more.  GnuTLS will
automatically consider the stapled OCSP response during the TLS
certificate verification (see gnutls_certificate_verify_peers2).
To disable the automatic OCSP verification the flag
'GNUTLS_VERIFY_DISABLE_CRL_CHECKS' should be specified to
gnutls_certificate_set_verify_flags.

Since GnuTLS 3.5.1 the client certificate verification will consider the
[see RFC7633] OCSP-Must-staple certificate extension, and will
consider it while checking for stapled OCSP responses.  If the extension
is present and no OCSP staple is found, the certificate verification
will fail and the status code 'GNUTLS_CERT_MISSING_OCSP_STATUS' will
returned from the verification function.

Under TLS 1.2 only one stapled response can be sent by a server, the
OCSP response associated with the end-certificate.  Under TLS 1.3 a
server can send multiple OCSP responses, typically one for each
certificate in the certificate chain.  The following functions can be
used by a client application to retrieve the OCSP responses as sent by
the server.

'INT gnutls_ocsp_status_request_get (gnutls_session_t SESSION, gnutls_datum_t * RESPONSE)'
'INT gnutls_ocsp_status_request_get2 (gnutls_session_t SESSION, unsigned IDX, gnutls_datum_t * RESPONSE)'

GnuTLS servers can provide OCSP responses to their clients using the
following functions.

'VOID gnutls_certificate_set_retrieve_function3 (gnutls_certificate_credentials_t CRED, gnutls_certificate_retrieve_function3 * FUNC)'
'INT gnutls_certificate_set_ocsp_status_request_file2 (gnutls_certificate_credentials_t SC, const char * RESPONSE_FILE, unsigned IDX, gnutls_x509_crt_fmt_t FMT)'
'UNSIGNED gnutls_ocsp_status_request_is_checked (gnutls_session_t SESSION, unsigned int FLAGS)'

A server is expected to provide the relevant certificate's OCSP
responses using
gnutls_certificate_set_ocsp_status_request_file2, and ensure a
periodic reload/renew of the credentials.  An estimation of the OCSP
responses expiration can be obtained using the
gnutls_certificate_get_ocsp_expiration function.

 -- Function: time_t gnutls_certificate_get_ocsp_expiration
          (gnutls_certificate_credentials_t SC, unsigned IDX, int OIDX,
          unsigned FLAGS)
     SC: is a credentials structure.

     IDX: is a certificate chain index as returned by
     'gnutls_certificate_set_key()' and friends

     OIDX: is an OCSP response index

     FLAGS: should be zero

     This function returns the validity of the loaded OCSP responses, to
     provide information on when to reload/refresh them.

     Note that the credentials structure should be read-only when in
     use, thus when reloading, either the credentials structure must not
     be in use by any sessions, or a new credentials structure should be
     allocated for new sessions.

     When 'oidx' is (-1) then the minimum refresh time for all responses
     is returned.  Otherwise the index specifies the response
     corresponding to the 'odix' certificate in the certificate chain.

     *Returns:* On success, the expiration time of the OCSP response.
     Otherwise (time_t)(-1) on error, or (time_t)-2 on out of bounds.

     *Since:* 3.6.3

Prior to GnuTLS 3.6.4, the functions
gnutls_certificate_set_ocsp_status_request_function2
gnutls_certificate_set_ocsp_status_request_file were provided to set
OCSP responses.  These functions are still functional, but cannot be
used to set multiple OCSP responses as allowed by TLS1.3.

The responses can be updated periodically using the 'ocsptool' command
(see also ocsptool Invocation).

     ocsptool --ask --load-cert server_cert.pem --load-issuer the_issuer.pem
              --load-signer the_issuer.pem --outfile ocsp.resp

In order to allow multiple OCSP responses to be concatenated, GnuTLS
supports PEM-encoded OCSP responses.  These can be generated using
'ocsptool' with the '-no-outder' parameter.

4.2.5 Managing encrypted keys
-----------------------------

Transferring or storing private keys in plain may not be a good idea,
since any compromise is irreparable.  Storing the keys in hardware
security modules (see Smart cards and HSMs) could solve the
storage problem but it is not always practical or efficient enough.
This section describes ways to store and transfer encrypted private
keys.

There are methods for key encryption, namely the PKCS #8, PKCS #12 and
OpenSSL's custom encrypted private key formats.  The PKCS #8 and the
OpenSSL's method allow encryption of the private key, while the PKCS #12
method allows, in addition, the bundling of accompanying data into the
structure.  That is typically the corresponding certificate, as well as
a trusted CA certificate.

High level functionality
........................

Generic and higher level private key import functions are available,
that import plain or encrypted keys and will auto-detect the encrypted
key format.

 -- Function: int gnutls_privkey_import_x509_raw (gnutls_privkey_t PKEY,
          const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT,
          const char * PASSWORD, unsigned int FLAGS)
     PKEY: The private key

     DATA: The private key data to be imported

     FORMAT: The format of the private key

     PASSWORD: A password (optional)

     FLAGS: an ORed sequence of gnutls_pkcs_encrypt_flags_t

     This function will import the given private key to the abstract
     'gnutls_privkey_t' type.

     The supported formats are basic unencrypted key, PKCS8, PKCS12, and
     the openssl format.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.0

 -- Function: int gnutls_x509_privkey_import2 (gnutls_x509_privkey_t
          KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t
          FORMAT, const char * PASSWORD, unsigned int FLAGS)
     KEY: The data to store the parsed key

     DATA: The DER or PEM encoded key.

     FORMAT: One of DER or PEM

     PASSWORD: A password (optional)

     FLAGS: an ORed sequence of gnutls_pkcs_encrypt_flags_t

     This function will import the given DER or PEM encoded key, to the
     native 'gnutls_x509_privkey_t' format, irrespective of the input
     format.  The input format is auto-detected.

     The supported formats are basic unencrypted key, PKCS8, PKCS12, and
     the openssl format.

     If the provided key is encrypted but no password was given, then
     'GNUTLS_E_DECRYPTION_FAILED' is returned.  Since GnuTLS 3.4.0 this
     function will utilize the PIN callbacks if any.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

Any keys imported using those functions can be imported to a certificate
credentials structure using gnutls_certificate_set_key, or
alternatively they can be directly imported using
gnutls_certificate_set_x509_key_file2.

PKCS #8 structures
..................

PKCS #8 keys can be imported and exported as normal private keys using
the functions below.  An addition to the normal import functions, are a
password and a flags argument.  The flags can be any element of the
'gnutls_pkcs_encrypt_flags_t' enumeration.  Note however, that GnuTLS
only supports the PKCS #5 PBES2 encryption scheme.  Keys encrypted with
the obsolete PBES1 scheme cannot be decrypted.

'INT gnutls_x509_privkey_import_pkcs8 (gnutls_x509_privkey_t KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS)'
'INT gnutls_x509_privkey_export_pkcs8 (gnutls_x509_privkey_t KEY, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
'INT gnutls_x509_privkey_export2_pkcs8 (gnutls_x509_privkey_t KEY, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS, gnutls_datum_t * OUT)'

'GNUTLS_PKCS_PLAIN'
     Unencrypted private key.
'GNUTLS_PKCS_PKCS12_3DES'
     PKCS-12 3DES.
'GNUTLS_PKCS_PKCS12_ARCFOUR'
     PKCS-12 ARCFOUR.
'GNUTLS_PKCS_PKCS12_RC2_40'
     PKCS-12 RC2-40.
'GNUTLS_PKCS_PBES2_3DES'
     PBES2 3DES.
'GNUTLS_PKCS_PBES2_AES_128'
     PBES2 AES-128.
'GNUTLS_PKCS_PBES2_AES_192'
     PBES2 AES-192.
'GNUTLS_PKCS_PBES2_AES_256'
     PBES2 AES-256.
'GNUTLS_PKCS_NULL_PASSWORD'
     Some schemas distinguish between an empty and a NULL password.
'GNUTLS_PKCS_PBES2_DES'
     PBES2 single DES.
'GNUTLS_PKCS_PBES1_DES_MD5'
     PBES1 with single DES; for compatibility with openssl only.
'GNUTLS_PKCS_PBES2_GOST_TC26Z'
     PBES2 GOST 28147-89 CFB with TC26-Z S-box.
'GNUTLS_PKCS_PBES2_GOST_CPA'
     PBES2 GOST 28147-89 CFB with CryptoPro-A S-box.
'GNUTLS_PKCS_PBES2_GOST_CPB'
     PBES2 GOST 28147-89 CFB with CryptoPro-B S-box.
'GNUTLS_PKCS_PBES2_GOST_CPC'
     PBES2 GOST 28147-89 CFB with CryptoPro-C S-box.
'GNUTLS_PKCS_PBES2_GOST_CPD'
     PBES2 GOST 28147-89 CFB with CryptoPro-D S-box.

Figure 4.5: Encryption flags

PKCS #12 structures
...................

A PKCS #12 structure [see PKCS12] usually contains a user's private
keys and certificates.  It is commonly used in browsers to export and
import the user's identities.  A file containing such a key can be
directly imported to a certificate credentials structure by using
gnutls_certificate_set_x509_simple_pkcs12_file.

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.
A bag of type encrypted should be decrypted in order for its data to be
accessed.

To reduce the complexity in parsing the structures the simple helper
function gnutls_pkcs12_simple_parse is provided.  For more
advanced uses, manual parsing of the structure is required using the
functions below.

'INT gnutls_pkcs12_get_bag (gnutls_pkcs12_t PKCS12, int INDX, gnutls_pkcs12_bag_t BAG)'
'INT gnutls_pkcs12_verify_mac (gnutls_pkcs12_t PKCS12, const char * PASS)'
'INT gnutls_pkcs12_bag_decrypt (gnutls_pkcs12_bag_t BAG, const char * PASS)'
'INT gnutls_pkcs12_bag_get_count (gnutls_pkcs12_bag_t BAG)'

 -- Function: int gnutls_pkcs12_simple_parse (gnutls_pkcs12_t P12, const
          char * PASSWORD, gnutls_x509_privkey_t * KEY,
          gnutls_x509_crt_t ** CHAIN, unsigned int * CHAIN_LEN,
          gnutls_x509_crt_t ** EXTRA_CERTS, unsigned int *
          EXTRA_CERTS_LEN, gnutls_x509_crl_t * CRL, unsigned int FLAGS)
     P12: A pkcs12 type

     PASSWORD: optional password used to decrypt the structure, bags and
     keys.

     KEY: a structure to store the parsed private key.

     CHAIN: the corresponding to key certificate chain (may be 'NULL' )

     CHAIN_LEN: will be updated with the number of additional (may be
     'NULL' )

     EXTRA_CERTS: optional pointer to receive an array of additional
     certificates found in the PKCS12 structure (may be 'NULL' ).

     EXTRA_CERTS_LEN: will be updated with the number of additional
     certs (may be 'NULL' ).

     CRL: an optional structure to store the parsed CRL (may be 'NULL'
     ).

     FLAGS: should be zero or one of GNUTLS_PKCS12_SP_*

     This function parses a PKCS12 structure in 'pkcs12' and extracts
     the private key, the corresponding certificate chain, any
     additional certificates and a CRL. The structures in 'key' ,
     'chain' 'crl' , and 'extra_certs' must not be initialized.

     The 'extra_certs' and 'extra_certs_len' parameters are optional and
     both may be set to 'NULL' .  If either is non-'NULL' , then both
     must be set.  The value for 'extra_certs' is allocated using
     'gnutls_malloc()' .

     Encrypted PKCS12 bags and PKCS8 private keys are supported, but
     only with password based security and the same password for all
     operations.

     Note that a PKCS12 structure may contain many keys and/or
     certificates, and there is no way to identify which key/certificate
     pair you want.  For this reason this function is useful for PKCS12
     files that contain only one key/certificate pair and/or one CRL.

     If the provided structure has encrypted fields but no password is
     provided then this function returns 'GNUTLS_E_DECRYPTION_FAILED' .

     Note that normally the chain constructed does not include self
     signed certificates, to comply with TLS' requirements.  If,
     however, the flag 'GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED' is
     specified then self signed certificates will be included in the
     chain.

     Prior to using this function the PKCS '12' structure integrity must
     be verified using 'gnutls_pkcs12_verify_mac()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.0
'INT gnutls_pkcs12_bag_get_data (gnutls_pkcs12_bag_t BAG, unsigned INDX, gnutls_datum_t * DATA)'
'INT gnutls_pkcs12_bag_get_key_id (gnutls_pkcs12_bag_t BAG, unsigned INDX, gnutls_datum_t * ID)'
'INT gnutls_pkcs12_bag_get_friendly_name (gnutls_pkcs12_bag_t BAG, unsigned INDX, char ** NAME)'

The functions below are used to generate a PKCS #12 structure.  An
example of their usage is shown at PKCS12 structure generation example.

'INT gnutls_pkcs12_set_bag (gnutls_pkcs12_t PKCS12, gnutls_pkcs12_bag_t BAG)'
'INT gnutls_pkcs12_bag_encrypt (gnutls_pkcs12_bag_t BAG, const char * PASS, unsigned int FLAGS)'
'INT gnutls_pkcs12_generate_mac (gnutls_pkcs12_t PKCS12, const char * PASS)'
'INT gnutls_pkcs12_bag_set_data (gnutls_pkcs12_bag_t BAG, gnutls_pkcs12_bag_type_t TYPE, const gnutls_datum_t * DATA)'
'INT gnutls_pkcs12_bag_set_crl (gnutls_pkcs12_bag_t BAG, gnutls_x509_crl_t CRL)'
'INT gnutls_pkcs12_bag_set_crt (gnutls_pkcs12_bag_t BAG, gnutls_x509_crt_t CRT)'
'INT gnutls_pkcs12_bag_set_key_id (gnutls_pkcs12_bag_t BAG, unsigned INDX, const gnutls_datum_t * ID)'
'INT gnutls_pkcs12_bag_set_friendly_name (gnutls_pkcs12_bag_t BAG, unsigned INDX, const char * NAME)'

OpenSSL encrypted keys
......................

Unfortunately the structures discussed in the previous sections are not
the only structures that may hold an encrypted private key.  For example
the OpenSSL library offers a custom key encryption method.  Those
structures are also supported in GnuTLS with
gnutls_x509_privkey_import_openssl.

 -- Function: int gnutls_x509_privkey_import_openssl
          (gnutls_x509_privkey_t KEY, const gnutls_datum_t * DATA, const
          char * PASSWORD)
     KEY: The data to store the parsed key

     DATA: The DER or PEM encoded key.

     PASSWORD: the password to decrypt the key (if it is encrypted).

     This function will convert the given PEM encrypted to the native
     gnutls_x509_privkey_t format.  The output will be stored in 'key' .

     The 'password' should be in ASCII. If the password is not provided
     or wrong then 'GNUTLS_E_DECRYPTION_FAILED' will be returned.

     If the Certificate is PEM encoded it should have a header of
     "PRIVATE KEY" and the "DEK-Info" header.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

4.2.6 Invoking certtool
-----------------------

Tool to parse and generate X.509 certificates, requests and private
keys.  It can be used interactively or non interactively by specifying
the template command line option.

The tool accepts files or supported URIs via the -infile option.  In
case PIN is required for URI access you can provide it using the
environment variables GNUTLS_PIN and GNUTLS_SO_PIN.

This section was generated by *AutoGen*, using the 'agtexi-cmd' template
and the option descriptions for the 'certtool' program.  This software
is released under the GNU General Public License, version 3 or later.

certtool help/usage ('--help')
..............................

This is the automatically generated usage text for certtool.

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     certtool - GnuTLS certificate tool
     Usage:  certtool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

        -d, --debug=num            Enable debugging
                                     - it must be in the range:
                                       0 to 9999
        -V, --verbose              More verbose output
                                     - may appear multiple times
            --infile=file          Input file
                                     - file must pre-exist
            --outfile=str          Output file

     Certificate related options:

        -i, --certificate-info     Print information on the given certificate
            --pubkey-info          Print information on a public key
        -s, --generate-self-signed  Generate a self-signed certificate
        -c, --generate-certificate  Generate a signed certificate
            --generate-proxy       Generates a proxy certificate
        -u, --update-certificate   Update a signed certificate
            --fingerprint          Print the fingerprint of the given certificate
            --key-id               Print the key ID of the given certificate
            --v1                   Generate an X.509 version 1 certificate (with no extensions)
            --sign-params=str      Sign a certificate with a specific signature algorithm

     Certificate request related options:

            --crq-info             Print information on the given certificate request
        -q, --generate-request     Generate a PKCS #10 certificate request
                                     - prohibits the option 'infile'
            --no-crq-extensions    Do not use extensions in certificate requests

     PKCS#12 file related options:

            --p12-info             Print information on a PKCS #12 structure
            --p12-name=str         The PKCS #12 friendly name to use
            --to-p12               Generate a PKCS #12 structure

     Private key related options:

        -k, --key-info             Print information on a private key
            --p8-info              Print information on a PKCS #8 structure
            --to-rsa               Convert an RSA-PSS key to raw RSA format
        -p, --generate-privkey     Generate a private key
            --key-type=str         Specify the key type to use on key generation
            --bits=num             Specify the number of bits for key generation
            --curve=str            Specify the curve used for EC key generation
            --sec-param=str        Specify the security level [low, legacy, medium, high, ultra]
            --to-p8                Convert a given key to a PKCS #8 structure
        -8, --pkcs8                Use PKCS #8 format for private keys
            --provable             Generate a private key or parameters from a seed using a provable method
            --verify-provable-privkey  Verify a private key generated from a seed using a provable method
            --seed=str             When generating a private key use the given hex-encoded seed

     CRL related options:

        -l, --crl-info             Print information on the given CRL structure
            --generate-crl         Generate a CRL
            --verify-crl           Verify a Certificate Revocation List using a trusted list
                                     - requires the option 'load-ca-certificate'

     Certificate verification related options:

        -e, --verify-chain         Verify a PEM encoded certificate chain
            --verify               Verify a PEM encoded certificate (chain) against a trusted set
            --verify-hostname=str  Specify a hostname to be used for certificate chain verification
            --verify-email=str     Specify a email to be used for certificate chain verification
                                     - prohibits the option 'verify-hostname'
            --verify-purpose=str   Specify a purpose OID to be used for certificate chain verification
            --verify-allow-broken  Allow broken algorithms, such as MD5 for verification
            --verify-profile=str   Specify a security level profile to be used for verification

     PKCS#7 structure options:

            --p7-generate          Generate a PKCS #7 structure
            --p7-sign              Signs using a PKCS #7 structure
            --p7-detached-sign     Signs using a detached PKCS #7 structure
            --p7-include-cert      The signer's certificate will be included in the cert list.
                                     - disabled as '--no-p7-include-cert'
                                     - enabled by default
            --p7-time              Will include a timestamp in the PKCS #7 structure
                                     - disabled as '--no-p7-time'
            --p7-show-data         Will show the embedded data in the PKCS #7 structure
                                     - disabled as '--no-p7-show-data'
            --p7-info              Print information on a PKCS #7 structure
            --p7-verify            Verify the provided PKCS #7 structure
            --smime-to-p7          Convert S/MIME to PKCS #7 structure

     Other options:

            --get-dh-params        List the included PKCS #3 encoded Diffie-Hellman parameters
            --dh-info              Print information PKCS #3 encoded Diffie-Hellman parameters
            --load-privkey=str     Loads a private key file
            --load-pubkey=str      Loads a public key file
            --load-request=str     Loads a certificate request file
            --load-certificate=str Loads a certificate file
            --load-ca-privkey=str  Loads the certificate authority's private key file
            --load-ca-certificate=str Loads the certificate authority's certificate file
            --load-crl=str         Loads the provided CRL
            --load-data=str        Loads auxiliary data
            --password=str         Password to use
            --null-password        Enforce a NULL password
            --empty-password       Enforce an empty password
            --hex-numbers          Print big number in an easier format to parse
            --cprint               In certain operations it prints the information in C-friendly format
            --hash=str             Hash algorithm to use for signing
            --salt-size=num        Specify the RSA-PSS key default salt size
            --inder                Use DER format for input certificates, private keys, and DH parameters
                                     - disabled as '--no-inder'
            --inraw                an alias for the 'inder' option
            --outder               Use DER format for output certificates, private keys, and DH parameters
                                     - disabled as '--no-outder'
            --outraw               an alias for the 'outder' option
            --template=str         Template file to use for non-interactive operation
            --stdout-info          Print information to stdout instead of stderr
            --ask-pass             Enable interaction for entering password when in batch mode.
            --pkcs-cipher=str      Cipher to use for PKCS #8 and #12 operations
            --provider=str         Specify the PKCS #11 provider library
            --text                 Output textual information before PEM-encoded certificates, private
     keys, etc
                                     - disabled as '--no-text'
                                     - enabled by default

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Tool to parse and generate X.509 certificates, requests and private keys.
     It can be used interactively or non interactively by specifying the
     template command line option.

     The tool accepts files or supported URIs via the --infile option.  In case
     PIN is required for URI access you can provide it using the environment
     variables GNUTLS_PIN and GNUTLS_SO_PIN.

Base options
............

debug option (-d).
..................

This is the "enable debugging" option.  This option takes a number
argument.  Specifies the debug level.

cert-options options
....................

Certificate related options.

pubkey-info option.
...................

This is the "print information on a public key" option.  The option
combined with -load-request, -load-pubkey, -load-privkey and
-load-certificate will extract the public key of the object in question.

fingerprint option.
...................

This is the "print the fingerprint of the given certificate" option.
This is a simple hash of the DER encoding of the certificate.  It can be
combined with the -hash parameter.  However, it is recommended for
identification to use the key-id which depends only on the certificate's
key.

key-id option.
..............

This is the "print the key id of the given certificate" option.  This is
a hash of the public key of the given certificate.  It identifies the
key uniquely, remains the same on a certificate renewal and depends only
on signed fields of the certificate.

certificate-pubkey option.
..........................

This is the "print certificate's public key" option.  This option is
deprecated as a duplicate of -pubkey-info

*NOTE**: THIS OPTION IS DEPRECATED*

sign-params option.
...................

This is the "sign a certificate with a specific signature algorithm"
option.  This option takes a string argument.  This option can be
combined with -generate-certificate, to sign the certificate with a
specific signature algorithm variant.  The only option supported is
'RSA-PSS', and should be specified when the signer does not have a
certificate which is marked for RSA-PSS use only.

crq-options options
...................

Certificate request related options.

generate-request option (-q).
.............................

This is the "generate a pkcs #10 certificate request" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     infile.

Will generate a PKCS #10 certificate request.  To specify a private key
use -load-privkey.

pkcs12-options options
......................

PKCS#12 file related options.

p12-info option.
................

This is the "print information on a pkcs #12 structure" option.  This
option will dump the contents and print the metadata of the provided
PKCS #12 structure.

p12-name option.
................

This is the "the pkcs #12 friendly name to use" option.  This option
takes a string argument.  The name to be used for the primary
certificate and private key in a PKCS #12 file.

to-p12 option.
..............

This is the "generate a pkcs #12 structure" option.  It requires a
certificate, a private key and possibly a CA certificate to be
specified.

key-options options
...................

Private key related options.

p8-info option.
...............

This is the "print information on a pkcs #8 structure" option.  This
option will print information about encrypted PKCS #8 structures.  That
option does not require the decryption of the structure.

to-rsa option.
..............

This is the "convert an rsa-pss key to raw rsa format" option.  It
requires an RSA-PSS key as input and will output a raw RSA key.  This
command is necessary for compatibility with applications that cannot
read RSA-PSS keys.

generate-privkey option (-p).
.............................

This is the "generate a private key" option.  When generating RSA-PSS
private keys, the -hash option will restrict the allowed hash for the
key; in the same keys the -salt-size option is also acceptable.

key-type option.
................

This is the "specify the key type to use on key generation" option.
This option takes a string argument.  This option can be combined with
-generate-privkey, to specify the key type to be generated.  Valid
options are, 'rsa', 'rsa-pss', 'dsa', 'ecdsa', 'ed25519, and 'ed448'.'.
When combined with certificate generation it can be used to specify an
RSA-PSS certificate when an RSA key is given.

curve option.
.............

This is the "specify the curve used for ec key generation" option.  This
option takes a string argument.  Supported values are secp192r1,
secp224r1, secp256r1, secp384r1 and secp521r1.

sec-param option.
.................

This is the "specify the security level [low, legacy, medium, high,
ultra]" option.  This option takes a string argument 'Security
parameter'.  This is alternative to the bits option.

to-p8 option.
.............

This is the "convert a given key to a pkcs #8 structure" option.  This
needs to be combined with -load-privkey.

provable option.
................

This is the "generate a private key or parameters from a seed using a
provable method" option.  This will use the FIPS PUB186-4 algorithms
(i.e., Shawe-Taylor) for provable key generation.  When specified the
private keys or parameters will be generated from a seed, and can be
later validated with -verify-provable-privkey to be correctly generated
from the seed.  You may specify -seed or allow GnuTLS to generate one
(recommended).  This option can be combined with -generate-privkey or
-generate-dh-params.

That option applies to RSA and DSA keys.  On the DSA keys the PQG
parameters are generated using the seed, and on RSA the two primes.

verify-provable-privkey option.
...............................

This is the "verify a private key generated from a seed using a provable
method" option.  This will use the FIPS-186-4 algorithms for provable
key generation.  You may specify -seed or use the seed stored in the
private key structure.

seed option.
............

This is the "when generating a private key use the given hex-encoded
seed" option.  This option takes a string argument.  The seed acts as a
security parameter for the private key, and thus a seed size which
corresponds to the security level of the private key should be provided
(e.g., 256-bits seed).

crl-options options
...................

CRL related options.

generate-crl option.
....................

This is the "generate a crl" option.  This option generates a
Certificate Revocation List.  When combined with -load-crl it would use
the loaded CRL as base for the generated (i.e., all revoked certificates
in the base will be copied to the new CRL). To add new certificates to
the CRL use -load-certificate.

verify-crl option.
..................

This is the "verify a certificate revocation list using a trusted list"
option.

This option has some usage constraints.  It:
   * must appear in combination with the following options:
     load-ca-certificate.

The trusted certificate list must be loaded with -load-ca-certificate.

cert-verify-options options
...........................

Certificate verification related options.

verify-chain option (-e).
.........................

This is the "verify a pem encoded certificate chain" option.  Verifies
the validity of a certificate chain.  That is, an ordered set of
certificates where each one is the issuer of the previous, and the first
is the end-certificate to be validated.  In a proper chain the last
certificate is a self signed one.  It can be combined with
-verify-purpose or -verify-hostname.

verify option.
..............

This is the "verify a pem encoded certificate (chain) against a trusted
set" option.  The trusted certificate list can be loaded with
-load-ca-certificate.  If no certificate list is provided, then the
system's trusted certificate list is used.  Note that during
verification multiple paths may be explored.  On a successful
verification the successful path will be the last one.  It can be
combined with -verify-purpose or -verify-hostname.

verify-hostname option.
.......................

This is the "specify a hostname to be used for certificate chain
verification" option.  This option takes a string argument.  This is to
be combined with one of the verify certificate options.

verify-email option.
....................

This is the "specify a email to be used for certificate chain
verification" option.  This option takes a string argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     verify-hostname.

This is to be combined with one of the verify certificate options.

verify-purpose option.
......................

This is the "specify a purpose oid to be used for certificate chain
verification" option.  This option takes a string argument.  This object
identifier restricts the purpose of the certificates to be verified.
Example purposes are 1.3.6.1.5.5.7.3.1 (TLS WWW), 1.3.6.1.5.5.7.3.4
(EMAIL) etc.  Note that a CA certificate without a purpose set (extended
key usage) is valid for any purpose.

verify-allow-broken option.
...........................

This is the "allow broken algorithms, such as md5 for verification"
option.  This can be combined with -p7-verify, -verify or -verify-chain.

verify-profile option.
......................

This is the "specify a security level profile to be used for
verification" option.  This option takes a string argument.  This option
can be used to specify a certificate verification profile.  Certificate
verification profiles correspond to the security level.  This should be
one of 'none', 'very weak', 'low', 'legacy', 'medium', 'high', 'ultra',
'future'.  Note that by default no profile is applied, unless one is set
as minimum in the gnutls configuration file.

pkcs7-options options
.....................

PKCS#7 structure options.

p7-generate option.
...................

This is the "generate a pkcs #7 structure" option.  This option
generates a PKCS #7 certificate container structure.  To add
certificates in the structure use -load-certificate and -load-crl.

p7-sign option.
...............

This is the "signs using a pkcs #7 structure" option.  This option
generates a PKCS #7 structure containing a signature for the provided
data from infile.  The data are stored within the structure.  The signer
certificate has to be specified using -load-certificate and
-load-privkey.  The input to -load-certificate can be a list of
certificates.  In case of a list, the first certificate is used for
signing and the other certificates are included in the structure.

p7-detached-sign option.
........................

This is the "signs using a detached pkcs #7 structure" option.  This
option generates a PKCS #7 structure containing a signature for the
provided data from infile.  The signer certificate has to be specified
using -load-certificate and -load-privkey.  The input to
-load-certificate can be a list of certificates.  In case of a list, the
first certificate is used for signing and the other certificates are
included in the structure.

p7-include-cert option.
.......................

This is the "the signer's certificate will be included in the cert
list."  option.

This option has some usage constraints.  It:
   * can be disabled with -no-p7-include-cert.
   * It is enabled by default.

This options works with -p7-sign or -p7-detached-sign and will include
or exclude the signer's certificate into the generated signature.

p7-time option.
...............

This is the "will include a timestamp in the pkcs #7 structure" option.

This option has some usage constraints.  It:
   * can be disabled with -no-p7-time.

This option will include a timestamp in the generated signature

p7-show-data option.
....................

This is the "will show the embedded data in the pkcs #7 structure"
option.

This option has some usage constraints.  It:
   * can be disabled with -no-p7-show-data.

This option can be combined with -p7-verify or -p7-info and will display
the embedded signed data in the PKCS #7 structure.

p7-verify option.
.................

This is the "verify the provided pkcs #7 structure" option.  This option
verifies the signed PKCS #7 structure.  The certificate list to use for
verification can be specified with -load-ca-certificate.  When no
certificate list is provided, then the system's certificate list is
used.  Alternatively a direct signer can be provided using
-load-certificate.  A key purpose can be enforced with the
-verify-purpose option, and the -load-data option will utilize detached
data.

other-options options
.....................

Other options.

generate-dh-params option.
..........................

This is the "generate pkcs #3 encoded diffie-hellman parameters" option.
The will generate random parameters to be used with Diffie-Hellman key
exchange.  The output parameters will be in PKCS #3 format.  Note that
it is recommended to use the -get-dh-params option instead.

*NOTE**: THIS OPTION IS DEPRECATED*

get-dh-params option.
.....................

This is the "list the included pkcs #3 encoded diffie-hellman
parameters" option.  Returns stored DH parameters in GnuTLS. Those
parameters returned are defined in RFC7919, and can be considered
standard parameters for a TLS key exchange.  This option is provided for
old applications which require DH parameters to be specified; modern
GnuTLS applications should not require them.

load-privkey option.
....................

This is the "loads a private key file" option.  This option takes a
string argument.  This can be either a file or a PKCS #11 URL

load-pubkey option.
...................

This is the "loads a public key file" option.  This option takes a
string argument.  This can be either a file or a PKCS #11 URL

load-request option.
....................

This is the "loads a certificate request file" option.  This option
takes a string argument.  This option can be used with a file

load-certificate option.
........................

This is the "loads a certificate file" option.  This option takes a
string argument.  This option can be used with a file

load-ca-privkey option.
.......................

This is the "loads the certificate authority's private key file" option.
This option takes a string argument.  This can be either a file or a
PKCS #11 URL

load-ca-certificate option.
...........................

This is the "loads the certificate authority's certificate file" option.
This option takes a string argument.  This can be either a file or a
PKCS #11 URL

load-crl option.
................

This is the "loads the provided crl" option.  This option takes a string
argument.  This option can be used with a file

load-data option.
.................

This is the "loads auxiliary data" option.  This option takes a string
argument.  This option can be used with a file

password option.
................

This is the "password to use" option.  This option takes a string
argument.  You can use this option to specify the password in the
command line instead of reading it from the tty.  Note, that the command
line arguments are available for view in others in the system.
Specifying password as " is the same as specifying no password.

null-password option.
.....................

This is the "enforce a null password" option.  This option enforces a
NULL password.  This is different than the empty or no password in
schemas like PKCS #8.

empty-password option.
......................

This is the "enforce an empty password" option.  This option enforces an
empty password.  This is different than the NULL or no password in
schemas like PKCS #8.

cprint option.
..............

This is the "in certain operations it prints the information in
c-friendly format" option.  In certain operations it prints the
information in C-friendly format, suitable for including into C
programs.

rsa option.
...........

This is the "generate rsa key" option.  When combined with
-generate-privkey generates an RSA private key.

*NOTE**: THIS OPTION IS DEPRECATED*

dsa option.
...........

This is the "generate dsa key" option.  When combined with
-generate-privkey generates a DSA private key.

*NOTE**: THIS OPTION IS DEPRECATED*

ecc option.
...........

This is the "generate ecc (ecdsa) key" option.  When combined with
-generate-privkey generates an elliptic curve private key to be used
with ECDSA.

*NOTE**: THIS OPTION IS DEPRECATED*

ecdsa option.
.............

This is an alias for the 'ecc' option, see the ecc option documentation.

hash option.
............

This is the "hash algorithm to use for signing" option.  This option
takes a string argument.  Available hash functions are SHA1, RMD160,
SHA256, SHA384, SHA512, SHA3-224, SHA3-256, SHA3-384, SHA3-512.

salt-size option.
.................

This is the "specify the rsa-pss key default salt size" option.  This
option takes a number argument.  Typical keys shouldn't set or restrict
this option.

inder option.
.............

This is the "use der format for input certificates, private keys, and dh
parameters " option.

This option has some usage constraints.  It:
   * can be disabled with -no-inder.

The input files will be assumed to be in DER or RAW format.  Unlike
options that in PEM input would allow multiple input data (e.g.
multiple certificates), when reading in DER format a single data
structure is read.

inraw option.
.............

This is an alias for the 'inder' option, see the inder option documentation.

outder option.
..............

This is the "use der format for output certificates, private keys, and
dh parameters" option.

This option has some usage constraints.  It:
   * can be disabled with -no-outder.

The output will be in DER or RAW format.

outraw option.
..............

This is an alias for the 'outder' option, see the outder option documentation.

ask-pass option.
................

This is the "enable interaction for entering password when in batch
mode."  option.  This option will enable interaction to enter password
when in batch mode.  That is useful when the template option has been
specified.

pkcs-cipher option.
...................

This is the "cipher to use for pkcs #8 and #12 operations" option.  This
option takes a string argument 'Cipher'.  Cipher may be one of 3des,
3des-pkcs12, aes-128, aes-192, aes-256, rc2-40, arcfour.

provider option.
................

This is the "specify the pkcs #11 provider library" option.  This option
takes a string argument.  This will override the default options in
/etc/gnutls/pkcs11.conf

text option.
............

This is the "output textual information before pem-encoded certificates,
private keys, etc" option.

This option has some usage constraints.  It:
   * can be disabled with -no-text.
   * It is enabled by default.

Output textual information before PEM-encoded data

certtool exit status
....................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

certtool See Also
.................

p11tool (1), psktool (1), srptool (1)

certtool Examples
.................

Generating private keys
.......................

To create an RSA private key, run:
     $ certtool --generate-privkey --outfile key.pem --rsa

To create a DSA or elliptic curves (ECDSA) private key use the above
command combined with 'dsa' or 'ecc' options.

Generating certificate requests
...............................

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

If the private key is stored in a smart card you can generate a request
by specifying the private key object URL.
     $ ./certtool --generate-request --load-privkey "pkcs11:..." \
       --load-pubkey "pkcs11:..." --outfile request.pem

Generating a self-signed certificate
....................................

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.

Generating a certificate
........................

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 generate a certificate using the private key only, 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

Certificate information
.......................

To view the certificate information, use:
     $ certtool --certificate-info --infile cert.pem

Changing the certificate format
...............................

To convert the certificate from PEM to DER format, use:
     $ certtool --certificate-info --infile cert.pem --outder --outfile cert.der

PKCS #12 structure generation
.............................

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

Obtaining Diffie-Hellman parameters
...................................

To obtain the RFC7919 parameters for Diffie-Hellman key exchange, use
the command:
     $ certtool --get-dh-params --outfile dh.pem --sec-param medium

Verifying a certificate
.......................

To verify a certificate in a file against the system's CA trust store
use the following command:
     $ certtool --verify --infile cert.pem

It is also possible to simulate hostname verification with the following
options:
     $ certtool --verify --verify-hostname www.example.com --infile cert.pem

Proxy certificate generation
............................

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

Certificate revocation list generation
......................................

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

Certtool's template file format
...............................

A template file can be used to avoid the interactive questions of
certtool.  Initially create a file named 'cert.cfg' that contains the
information about the certificate.  The template can be used as below:

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

An example certtool template file that can be used to generate a
certificate request or a self signed certificate follows.

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

     # Set domain components
     #dc = "name"
     #dc = "domain"

     # 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."
     #dn_oid = "2.5.4.65 jackal"

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

     # An alternative way to set the certificate's distinguished name directly
     # is with the "dn" option. The attribute names allowed are:
     # C (country), street, O (organization), OU (unit), title, CN (common name),
     # L (locality), ST (state), placeOfBirth, gender, countryOfCitizenship,
     # countryOfResidence, serialNumber, telephoneNumber, surName, initials,
     # generationQualifier, givenName, pseudonym, dnQualifier, postalCode, name,
     # businessCategory, DC, UID, jurisdictionOfIncorporationLocalityName,
     # jurisdictionOfIncorporationStateOrProvinceName,
     # jurisdictionOfIncorporationCountryName, XmppAddr, and numeric OIDs.

     #dn = "cn = Nikos,st = New\, Something,C=GR,surName=Mavrogiannopoulos,2.5.4.9=Arkadias"

     # The serial number of the certificate
     # The value is in decimal (i.e. 1963) or hex (i.e. 0x07ab).
     # Comment the field for a random serial number.
     serial = 007

     # In how many days, counting from today, this certificate will expire.
     # Use -1 if there is no expiration date.
     expiration_days = 700

     # Alternatively you may set concrete dates and time. The GNU date string
     # formats are accepted. See:
     # https://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html

     #activation_date = "2004-02-29 16:21:42"
     #expiration_date = "2025-02-29 16:24:41"

     # X.509 v3 extensions

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

     # An othername defined by an OID and a hex encoded string
     #other_name = "1.3.6.1.5.2.2 302ca00d1b0b56414e5245494e2e4f5247a11b3019a006020400000002a10f300d1b047269636b1b0561646d696e"
     #other_name_utf8 = "1.2.4.5.6 A UTF8 string"
     #other_name_octet = "1.2.4.5.6 A string that will be encoded as ASN.1 octet string"

     # Allows writing an XmppAddr Identifier
     #xmpp_name = juliet@im.example.com

     # Names used in PKINIT
     #krb5_principal = user@REALM.COM
     #krb5_principal = HTTP/user@REALM.COM

     # A subject alternative name URI
     #uri = "https://www.example.com"

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

     # TLS feature (rfc7633) extension. That can is used to indicate mandatory TLS
     # extension features to be provided by the server. In practice this is used
     # to require the Status Request (extid: 5) extension from the server. That is,
     # to require the server holding this certificate to provide a stapled OCSP response.
     # You can have multiple lines for multiple TLS features.

     # To ask for OCSP status request use:
     #tls_feature = 5

     # Challenge password used in certificate requests
     challenge_password = 123456

     # Password when encrypting a private key
     #password = secret

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

     # Whether this is a CA certificate or not
     #ca

     # Subject Unique ID (in hex)
     #subject_unique_id = 00153224

     # Issuer Unique ID (in hex)
     #issuer_unique_id = 00153225

     #### Key usage

     # The following key usage flags are used by CAs and end certificates

     # Whether this certificate will be used to sign data (needed
     # in TLS DHE ciphersuites). This is the digitalSignature flag
     # in RFC5280 terminology.
     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. This is the keyEncipherment flag
     # in RFC5280 terminology.
     encryption_key

     # Whether this key will be used to sign other certificates. The
     # keyCertSign flag in RFC5280 terminology.
     #cert_signing_key

     # Whether this key will be used to sign CRLs. The
     # cRLSign flag in RFC5280 terminology.
     #crl_signing_key

     # The keyAgreement flag of RFC5280. Its purpose is loosely
     # defined. Not use it unless required by a protocol.
     #key_agreement

     # The dataEncipherment flag of RFC5280. Its purpose is loosely
     # defined. Not use it unless required by a protocol.
     #data_encipherment

     # The nonRepudiation flag of RFC5280. Its purpose is loosely
     # defined. Not use it unless required by a protocol.
     #non_repudiation

     #### Extended key usage (key purposes)

     # The following extensions are used in an end certificate
     # to clarify its purpose. Some CAs also use it to indicate
     # the types of certificates they are purposed to sign.

     # Whether this certificate will be used for a TLS client;
     # this sets the id-kp-clientAuth (1.3.6.1.5.5.7.3.2) of
     # extended key usage.
     #tls_www_client

     # Whether this certificate will be used for a TLS server;
     # this sets the id-kp-serverAuth (1.3.6.1.5.5.7.3.1) of
     # extended key usage.
     #tls_www_server

     # Whether this key will be used to sign code. This sets the
     # id-kp-codeSigning (1.3.6.1.5.5.7.3.3) of extended key usage
     # extension.
     #code_signing_key

     # Whether this key will be used to sign OCSP data. This sets the
     # id-kp-OCSPSigning (1.3.6.1.5.5.7.3.9) of extended key usage extension.
     #ocsp_signing_key

     # Whether this key will be used for time stamping. This sets the
     # id-kp-timeStamping (1.3.6.1.5.5.7.3.8) of extended key usage extension.
     #time_stamping_key

     # Whether this key will be used for email protection. This sets the
     # id-kp-emailProtection (1.3.6.1.5.5.7.3.4) of extended key usage extension.
     #email_protection_key

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

     ## adding custom key purpose OIDs

     # for microsoft smart card logon
     # key_purpose_oid = 1.3.6.1.4.1.311.20.2.2

     # for email protection
     # key_purpose_oid = 1.3.6.1.5.5.7.3.4

     # for any purpose (must not be used in intermediate CA certificates)
     # key_purpose_oid = 2.5.29.37.0

     ### end of key purpose OIDs

     ### Adding arbitrary extensions
     # This requires to provide the extension OIDs, as well as the extension data in
     # hex format. The following two options are available since GnuTLS 3.5.3.
     #add_extension = "1.2.3.4 0x0AAB01ACFE"

     # As above but encode the data as an octet string
     #add_extension = "1.2.3.4 octet_string(0x0AAB01ACFE)"

     # For portability critical extensions shouldn't be set to certificates.
     #add_critical_extension = "5.6.7.8 0x1AAB01ACFE"

     # When generating a certificate from a certificate
     # request, then honor the extensions stored in the request
     # and store them in the real certificate.
     #honor_crq_extensions

     # Alternatively only specific extensions can be copied.
     #honor_crq_ext = 2.5.29.17
     #honor_crq_ext = 2.5.29.15

     # Path length constraint. Sets the maximum number of
     # certificates that can be used to certify this certificate.
     # (i.e. the certificate chain length)
     #path_len = -1
     #path_len = 2

     # OCSP URI
     # ocsp_uri = https://my.ocsp.server/ocsp

     # CA issuers URI
     # ca_issuers_uri = https://my.ca.issuer

     # Certificate policies
     #policy1 = 1.3.6.1.4.1.5484.1.10.99.1.0
     #policy1_txt = "This is a long policy to summarize"
     #policy1_url = https://www.example.com/a-policy-to-read

     #policy2 = 1.3.6.1.4.1.5484.1.10.99.1.1
     #policy2_txt = "This is a short policy"
     #policy2_url = https://www.example.com/another-policy-to-read

     # The number of additional certificates that may appear in a
     # path before the anyPolicy is no longer acceptable.
     #inhibit_anypolicy_skip_certs 1

     # Name constraints

     # DNS
     #nc_permit_dns = example.com
     #nc_exclude_dns = test.example.com

     # EMAIL
     #nc_permit_email = "nmav@ex.net"

     # Exclude subdomains of example.com
     #nc_exclude_email = .example.com

     # Exclude all e-mail addresses of example.com
     #nc_exclude_email = example.com

     # IP
     #nc_permit_ip = 192.168.0.0/16
     #nc_exclude_ip = 192.168.5.0/24
     #nc_permit_ip = fc0a:eef2:e7e7:a56e::/64

     # Options for proxy certificates
     #proxy_policy_language = 1.3.6.1.5.5.7.21.1

     # Options for generating a CRL

     # The number of days the next CRL update will be due.
     # next CRL update will be in 43 days
     #crl_next_update = 43

     # this is the 5th CRL by this CA
     # The value is in decimal (i.e. 1963) or hex (i.e. 0x07ab).
     # Comment the field for a time-based number.
     # Time-based CRL numbers generated in GnuTLS 3.6.3 and later
     # are significantly larger than those generated in previous
     # versions. Since CRL numbers need to be monotonic, you need
     # to specify the CRL number here manually if you intend to
     # downgrade to an earlier version than 3.6.3 after publishing
     # the CRL as it is not possible to specify CRL numbers greater
     # than 2**63-2 using hex notation in those versions.
     #crl_number = 5

     # Specify the update dates more precisely.
     #crl_this_update_date = "2004-02-29 16:21:42"
     #crl_next_update_date = "2025-02-29 16:24:41"

     # The date that the certificates will be made seen as
     # being revoked.
     #crl_revocation_date = "2025-02-29 16:24:41"

4.2.7 Invoking ocsptool
-----------------------

On verification
...............

Responses are typically signed/issued by designated certificates or
certificate authorities and thus this tool requires on verification the
certificate of the issuer or the full certificate chain in order to
determine the appropriate signing authority.  The specified certificate
of the issuer is assumed trusted.

This section was generated by *AutoGen*, using the 'agtexi-cmd' template
and the option descriptions for the 'ocsptool' program.  This software
is released under the GNU General Public License, version 3 or later.

ocsptool help/usage ('--help')
..............................

This is the automatically generated usage text for ocsptool.

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     ocsptool - GnuTLS OCSP tool
     Usage:  ocsptool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

        -d, --debug=num            Enable debugging
                                     - it must be in the range:
                                       0 to 9999
        -V, --verbose              More verbose output
                                     - may appear multiple times
            --infile=file          Input file
                                     - file must pre-exist
            --outfile=str          Output file
            --ask[=arg]            Ask an OCSP/HTTP server on a certificate validity
        -e, --verify-response      Verify response
        -i, --request-info         Print information on a OCSP request
        -j, --response-info        Print information on a OCSP response
        -q, --generate-request     Generates an OCSP request
            --nonce                Use (or not) a nonce to OCSP request
                                     - disabled as '--no-nonce'
            --load-chain=file      Reads a set of certificates forming a chain from file
                                     - file must pre-exist
            --load-issuer=file     Reads issuer's certificate from file
                                     - file must pre-exist
            --load-cert=file       Reads the certificate to check from file
                                     - file must pre-exist
            --load-trust=file      Read OCSP trust anchors from file
                                     - prohibits the option 'load-signer'
                                     - file must pre-exist
            --load-signer=file     Reads the OCSP response signer from file
                                     - prohibits the option 'load-trust'
                                     - file must pre-exist
            --inder                Use DER format for input certificates and private keys
                                     - disabled as '--no-inder'
            --outder               Use DER format for output of responses (this is the default)
            --outpem               Use PEM format for output of responses
        -Q, --load-request=file    Reads the DER encoded OCSP request from file
                                     - file must pre-exist
        -S, --load-response=file   Reads the DER encoded OCSP response from file
                                     - file must pre-exist
            --ignore-errors        Ignore any verification errors
            --verify-allow-broken  Allow broken algorithms, such as MD5 for verification
        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     ocsptool is a program that can parse and print information about OCSP
     requests/responses, generate requests and verify responses.  Unlike other
     GnuTLS applications it outputs DER encoded structures by default unless the
     '--outpem' option is specified.

debug option (-d)
.................

This is the "enable debugging" option.  This option takes a number
argument.  Specifies the debug level.

ask option
..........

This is the "ask an ocsp/http server on a certificate validity" option.
This option takes an optional string argument 'server name|url'.
Connects to the specified HTTP OCSP server and queries on the validity
of the loaded certificate.  Its argument can be a URL or a plain server
name.  It can be combined with -load-chain, where it checks all
certificates in the provided chain, or with -load-cert and -load-issuer
options.  The latter checks the provided certificate against its
specified issuer certificate.

verify-response option (-e)
...........................

This is the "verify response" option.  Verifies the provided OCSP
response against the system trust anchors (unless -load-trust is
provided).  It requires the -load-signer or -load-chain options to
obtain the signer of the OCSP response.

request-info option (-i)
........................

This is the "print information on a ocsp request" option.  Display
detailed information on the provided OCSP request.

response-info option (-j)
.........................

This is the "print information on a ocsp response" option.  Display
detailed information on the provided OCSP response.

load-trust option
.................

This is the "read ocsp trust anchors from file" option.  This option
takes a file argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     load-signer.

When verifying an OCSP response read the trust anchors from the provided
file.  When this is not provided, the system's trust anchors will be
used.

outder option
.............

This is the "use der format for output of responses (this is the
default)" option.  The output will be in DER encoded format.  Unlike
other GnuTLS tools, this is the default for this tool

outpem option
.............

This is the "use pem format for output of responses" option.  The output
will be in PEM format.

verify-allow-broken option
..........................

This is the "allow broken algorithms, such as md5 for verification"
option.  This can be combined with -verify-response.

ocsptool exit status
....................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

ocsptool See Also
.................

certtool (1)

ocsptool Examples
.................

Print information about an OCSP request
.......................................

To parse an OCSP request and print information about the content, the
'-i' or '--request-info' parameter may be used as follows.  The '-Q'
parameter specify the name of the file containing the OCSP request, and
it should contain the OCSP request in binary DER format.

     $ ocsptool -i -Q ocsp-request.der

The input file may also be sent to standard input like this:

     $ cat ocsp-request.der | ocsptool --request-info

Print information about an OCSP response
........................................

Similar to parsing OCSP requests, OCSP responses can be parsed using the
'-j' or '--response-info' as follows.

     $ ocsptool -j -Q ocsp-response.der
     $ cat ocsp-response.der | ocsptool --response-info

Generate an OCSP request
........................

The '-q' or '--generate-request' parameters are used to generate an OCSP
request.  By default the OCSP request is written to standard output in
binary DER format, but can be stored in a file using '--outfile'.  To
generate an OCSP request the issuer of the certificate to check needs to
be specified with '--load-issuer' and the certificate to check with
'--load-cert'.  By default PEM format is used for these files, although
'--inder' can be used to specify that the input files are in DER format.

     $ ocsptool -q --load-issuer issuer.pem --load-cert client.pem \
                --outfile ocsp-request.der

When generating OCSP requests, the tool will add an OCSP extension
containing a nonce.  This behaviour can be disabled by specifying
'--no-nonce'.

Verify signature in OCSP response
.................................

To verify the signature in an OCSP response the '-e' or
'--verify-response' parameter is used.  The tool will read an OCSP
response in DER format from standard input, or from the file specified
by '--load-response'.  The OCSP response is verified against a set of
trust anchors, which are specified using '--load-trust'.  The trust
anchors are concatenated certificates in PEM format.  The certificate
that signed the OCSP response needs to be in the set of trust anchors,
or the issuer of the signer certificate needs to be in the set of trust
anchors and the OCSP Extended Key Usage bit has to be asserted in the
signer certificate.

     $ ocsptool -e --load-trust issuer.pem \
                --load-response ocsp-response.der

The tool will print status of verification.

Verify signature in OCSP response against given certificate
...........................................................

It is possible to override the normal trust logic if you know that a
certain certificate is supposed to have signed the OCSP response, and
you want to use it to check the signature.  This is achieved using
'--load-signer' instead of '--load-trust'.  This will load one
certificate and it will be used to verify the signature in the OCSP
response.  It will not check the Extended Key Usage bit.

     $ ocsptool -e --load-signer ocsp-signer.pem \
                --load-response ocsp-response.der

This approach is normally only relevant in two situations.  The first is
when the OCSP response does not contain a copy of the signer
certificate, so the '--load-trust' code would fail.  The second is if
you want to avoid the indirect mode where the OCSP response signer
certificate is signed by a trust anchor.

Real-world example
..................

Here is an example of how to generate an OCSP request for a certificate
and to verify the response.  For illustration we'll use the
'blog.josefsson.org' host, which (as of writing) uses a certificate from
CACert.  First we'll use 'gnutls-cli' to get a copy of the server
certificate chain.  The server is not required to send this information,
but this particular one is configured to do so.

     $ echo | gnutls-cli -p 443 blog.josefsson.org --save-cert chain.pem

The saved certificates normally contain a pointer to where the OCSP
responder is located, in the Authority Information Access Information
extension.  For example, from 'certtool -i < chain.pem' there is this
information:

     Authority Information Access Information (not critical):
     Access Method: 1.3.6.1.5.5.7.48.1 (id-ad-ocsp)
     Access Location URI: https://ocsp.CAcert.org/

This means that ocsptool can discover the servers to contact over HTTP.
We can now request information on the chain certificates.

     $ ocsptool --ask --load-chain chain.pem

The request is sent via HTTP to the OCSP server address found in the
certificates.  It is possible to override the address of the OCSP server
as well as ask information on a particular certificate using -load-cert
and -load-issuer.

     $ ocsptool --ask https://ocsp.CAcert.org/ --load-chain chain.pem

4.2.8 Invoking danetool
-----------------------

Tool to generate and check DNS resource records for the DANE protocol.

This section was generated by *AutoGen*, using the 'agtexi-cmd' template
and the option descriptions for the 'danetool' program.  This software
is released under the GNU General Public License, version 3 or later.

danetool help/usage ('--help')
..............................

This is the automatically generated usage text for danetool.

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     danetool - GnuTLS DANE tool
     Usage:  danetool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

        -d, --debug=num            Enable debugging
                                     - it must be in the range:
                                       0 to 9999
        -V, --verbose              More verbose output
                                     - may appear multiple times
            --infile=file          Input file
                                     - file must pre-exist
            --outfile=str          Output file
            --load-pubkey=str      Loads a public key file
            --load-certificate=str Loads a certificate file
            --dlv=str              Sets a DLV file
            --hash=str             Hash algorithm to use for signing
            --check=str            Check a host's DANE TLSA entry
            --check-ee             Check only the end-entity's certificate
            --check-ca             Check only the CA's certificate
            --tlsa-rr              Print the DANE RR data on a certificate or public key
                                     - requires the option 'host'
            --host=str             Specify the hostname to be used in the DANE RR
            --proto=str            The protocol set for DANE data (tcp, udp etc.)
            --port=str             The port or service to connect to, for DANE data
            --app-proto=str        an alias for the 'starttls-proto' option
            --starttls-proto=str   The application protocol to be used to obtain the server's certificate
     (https, ftp, smtp, imap, ldap, xmpp, lmtp, pop3, nntp, sieve, postgres)
            --ca                   Whether the provided certificate or public key is a Certificate
     Authority
            --x509                 Use the hash of the X.509 certificate, rather than the public key
            --local                an alias for the 'domain' option
                                     - enabled by default
            --domain               The provided certificate or public key is issued by the local domain
                                     - disabled as '--no-domain'
                                     - enabled by default
            --local-dns            Use the local DNS server for DNSSEC resolving
                                     - disabled as '--no-local-dns'
            --insecure             Do not verify any DNSSEC signature
            --inder                Use DER format for input certificates and private keys
                                     - disabled as '--no-inder'
            --inraw                an alias for the 'inder' option
            --print-raw            Print the received DANE data in raw format
                                     - disabled as '--no-print-raw'
            --quiet                Suppress several informational messages
        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Tool to generate and check DNS resource records for the DANE protocol.

debug option (-d)
.................

This is the "enable debugging" option.  This option takes a number
argument.  Specifies the debug level.

load-pubkey option
..................

This is the "loads a public key file" option.  This option takes a
string argument.  This can be either a file or a PKCS #11 URL

load-certificate option
.......................

This is the "loads a certificate file" option.  This option takes a
string argument.  This can be either a file or a PKCS #11 URL

dlv option
..........

This is the "sets a dlv file" option.  This option takes a string
argument.  This sets a DLV file to be used for DNSSEC verification.

hash option
...........

This is the "hash algorithm to use for signing" option.  This option
takes a string argument.  Available hash functions are SHA1, RMD160,
SHA256, SHA384, SHA512.

check option
............

This is the "check a host's dane tlsa entry" option.  This option takes
a string argument.  Obtains the DANE TLSA entry from the given hostname
and prints information.  Note that the actual certificate of the host
can be provided using -load-certificate, otherwise danetool will connect
to the server to obtain it.  The exit code on verification success will
be zero.

check-ee option
...............

This is the "check only the end-entity's certificate" option.  Checks
the end-entity's certificate only.  Trust anchors or CAs are not
considered.

check-ca option
...............

This is the "check only the ca's certificate" option.  Checks the trust
anchor's and CA's certificate only.  End-entities are not considered.

tlsa-rr option
..............

This is the "print the dane rr data on a certificate or public key"
option.

This option has some usage constraints.  It:
   * must appear in combination with the following options: host.

This command prints the DANE RR data needed to enable DANE on a DNS
server.

host option
...........

This is the "specify the hostname to be used in the dane rr" option.
This option takes a string argument 'Hostname'.  This command sets the
hostname for the DANE RR.

proto option
............

This is the "the protocol set for dane data (tcp, udp etc.)"  option.
This option takes a string argument 'Protocol'.  This command specifies
the protocol for the service set in the DANE data.

app-proto option
................

This is an alias for the 'starttls-proto' option, see the starttls-proto option documentation.

starttls-proto option
.....................

This is the "the application protocol to be used to obtain the server's
certificate (https, ftp, smtp, imap, ldap, xmpp, lmtp, pop3, nntp,
sieve, postgres)" option.  This option takes a string argument.  When
the server's certificate isn't provided danetool will connect to the
server to obtain the certificate.  In that case it is required to know
the protocol to talk with the server prior to initiating the TLS
handshake.

ca option
.........

This is the "whether the provided certificate or public key is a
certificate authority" option.  Marks the DANE RR as a CA certificate if
specified.

x509 option
...........

This is the "use the hash of the x.509 certificate, rather than the
public key" option.  This option forces the generated record to contain
the hash of the full X.509 certificate.  By default only the hash of the
public key is used.

local option
............

This is an alias for the 'domain' option, see the domain option documentation.

domain option
.............

This is the "the provided certificate or public key is issued by the
local domain" option.

This option has some usage constraints.  It:
   * can be disabled with -no-domain.
   * It is enabled by default.

DANE distinguishes certificates and public keys offered via the DNSSEC
to trusted and local entities.  This flag indicates that this is a
domain-issued certificate, meaning that there could be no CA involved.

local-dns option
................

This is the "use the local dns server for dnssec resolving" option.

This option has some usage constraints.  It:
   * can be disabled with -no-local-dns.

This option will use the local DNS server for DNSSEC. This is disabled
by default due to many servers not allowing DNSSEC.

insecure option
...............

This is the "do not verify any dnssec signature" option.  Ignores any
DNSSEC signature verification results.

inder option
............

This is the "use der format for input certificates and private keys"
option.

This option has some usage constraints.  It:
   * can be disabled with -no-inder.

The input files will be assumed to be in DER or RAW format.  Unlike
options that in PEM input would allow multiple input data (e.g.
multiple certificates), when reading in DER format a single data
structure is read.

inraw option
............

This is an alias for the 'inder' option, see the inder option documentation.

print-raw option
................

This is the "print the received dane data in raw format" option.

This option has some usage constraints.  It:
   * can be disabled with -no-print-raw.

This option will print the received DANE data.

quiet option
............

This is the "suppress several informational messages" option.  In that
case on the exit code can be used as an indication of verification
success

danetool exit status
....................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

danetool See Also
.................

certtool (1)

danetool Examples
.................

DANE TLSA RR generation
.......................

To create a DANE TLSA resource record for a certificate (or public key)
that was issued localy and may or may not be signed by a CA use the
following command.
     $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem

To create a DANE TLSA resource record for a CA signed certificate, which
will be marked as such use the following command.
     $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem \
       --no-domain

The former is useful to add in your DNS entry even if your certificate
is signed by a CA. That way even users who do not trust your CA will be
able to verify your certificate using DANE.

In order to create a record for the CA signer of your certificate use
the following.
     $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem \
       --ca --no-domain

To read a server's DANE TLSA entry, use:
     $ danetool --check www.example.com --proto tcp --port 443

To verify an HTTPS server's DANE TLSA entry, use:
     $ danetool --check www.example.com --proto tcp --port 443 --load-certificate chain.pem

To verify an SMTP server's DANE TLSA entry, use:
     $ danetool --check www.example.com --proto tcp --starttls-proto=smtp --load-certificate chain.pem

4.3 Shared-key and anonymous authentication
===========================================

In addition to certificate authentication, the TLS protocol may be used
with password, shared-key and anonymous authentication methods.  The
rest of this chapter discusses details of these methods.

4.3.1 PSK authentication
------------------------

4.3.1.1 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.  It is available under all TLS protocol versions.

The implementation in GnuTLS is based on [see TLSPSK].  The
supported PSK key exchange methods are:

'PSK:'
     Authentication using the PSK protocol (no forward secrecy).

'DHE-PSK:'
     Authentication using the PSK protocol and Diffie-Hellman key
     exchange.  This method offers perfect forward secrecy.

'ECDHE-PSK:'
     Authentication using the PSK protocol and Elliptic curve
     Diffie-Hellman key exchange.  This method offers perfect forward
     secrecy.

'RSA-PSK:'
     Authentication using the PSK protocol for the client and an RSA
     certificate for the server.  This is not available under TLS 1.3.

Helper functions to generate and maintain PSK keys are also included in
GnuTLS.

'INT gnutls_key_generate (gnutls_datum_t * KEY, unsigned int KEY_SIZE)'
'INT gnutls_hex_encode (const gnutls_datum_t * DATA, char * RESULT, size_t * RESULT_SIZE)'
'INT gnutls_hex_decode (const gnutls_datum_t * HEX_DATA, void * RESULT, size_t * RESULT_SIZE)'

4.3.1.2 Invoking psktool
........................

Program that generates random keys for use with TLS-PSK. The keys are
stored in hexadecimal format in a key file.

This section was generated by *AutoGen*, using the 'agtexi-cmd' template
and the option descriptions for the 'psktool' program.  This software is
released under the GNU General Public License, version 3 or later.

psktool help/usage ('--help')
.............................

This is the automatically generated usage text for psktool.

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     psktool - GnuTLS PSK tool
     Usage:  psktool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

        -d, --debug=num            Enable debugging
                                     - it must be in the range:
                                       0 to 9999
        -s, --keysize=num          Specify the key size in bytes (default is 32-bytes or 256-bits)
                                     - it must be in the range:
                                       0 to 512
        -u, --username=str         Specify the username to use
        -p, --pskfile=str          Specify a pre-shared key file
        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Program that generates random keys for use with TLS-PSK.  The keys are
     stored in hexadecimal format in a key file.

debug option (-d)
.................

This is the "enable debugging" option.  This option takes a number
argument.  Specifies the debug level.

pskfile option (-p)
...................

This is the "specify a pre-shared key file" option.  This option takes a
string argument.  This option will specify the pre-shared key file to
store the generated keys.

passwd option
.............

This is an alias for the 'pskfile' option, see the pskfile option documentation.

psktool exit status
...................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

psktool See Also
................

gnutls-cli-debug (1), gnutls-serv (1), srptool (1), certtool (1)

psktool Examples
................

To add a user 'psk_identity' in 'keys.psk' for use with GnuTLS run:
     $ ./psktool -u psk_identity -p keys.psk
     Generating a random key for user 'psk_identity'
     Key stored to keys.psk
     $ cat keys.psk
     psk_identity:88f3824b3e5659f52d00e959bacab954b6540344
     $

This command will create 'keys.psk' if it does not exist and will add
user 'psk_identity'.

4.3.2 SRP authentication
------------------------

4.3.2.1 Authentication using SRP
................................

GnuTLS supports authentication via the Secure Remote Password or SRP
protocol (see [see TOMSRP] for a description).  The SRP key
exchange is an extension to the TLS protocol, and it provides an
authenticated with a password key exchange.  The 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.  It is
only available under TLS 1.2 or earlier versions.

The advantage of SRP authentication, over other proposed secure password
authentication schemes, is that SRP is not susceptible to off-line
dictionary attacks.  Moreover, 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.

Typical conventions in SRP are a password file, called 'tpasswd' that
holds the SRP verifiers (encoded passwords) and another file,
'tpasswd.conf', which holds the allowed SRP parameters.  The included in
GnuTLS helper follow those conventions.  The srptool program, discussed
in the next section is a tool to manipulate the SRP parameters.

The implementation in GnuTLS is based on [see TLSSRP].  The
supported key exchange methods are shown below.  Enabling any of these
key exchange methods in a session disables support for TLS1.3.

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

 -- 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/gnutls.h or may be generated.

     The verifier will be allocated with 'gnutls_malloc' () and will be
     stored in 'res' using binary format.

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

'INT gnutls_srp_base64_encode2 (const gnutls_datum_t * DATA, gnutls_datum_t * RESULT)'
'INT gnutls_srp_base64_decode2 (const gnutls_datum_t * B64_DATA, gnutls_datum_t * RESULT)'

4.3.2.2 Invoking srptool
........................

Simple program that emulates the programs in the Stanford SRP (Secure
Remote Password) libraries using GnuTLS. It is intended for use in
places where you don't expect SRP authentication to be the used for
system users.

In brief, to use SRP you need to create two files.  These are the
password file that holds the users and the verifiers associated with
them and the configuration file to hold the group parameters (called
tpasswd.conf).

This section was generated by *AutoGen*, using the 'agtexi-cmd' template
and the option descriptions for the 'srptool' program.  This software is
released under the GNU General Public License, version 3 or later.

srptool help/usage ('--help')
.............................

This is the automatically generated usage text for srptool.

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     srptool - GnuTLS SRP tool
     Usage:  srptool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

        -d, --debug=num            Enable debugging
                                     - it must be in the range:
                                       0 to 9999
        -i, --index=num            specify the index of the group parameters in tpasswd.conf to use
        -u, --username=str         specify a username
        -p, --passwd=str           specify a password file
        -s, --salt=num             specify salt size
            --verify               just verify the password.
        -v, --passwd-conf=str      specify a password conf file.
            --create-conf=str      Generate a password configuration file.
        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Simple program that emulates the programs in the Stanford SRP (Secure
     Remote Password) libraries using GnuTLS.  It is intended for use in places
     where you don't expect SRP authentication to be the used for system users.

     In brief, to use SRP you need to create two files.  These are the password
     file that holds the users and the verifiers associated with them and the
     configuration file to hold the group parameters (called tpasswd.conf).

debug option (-d)
.................

This is the "enable debugging" option.  This option takes a number
argument.  Specifies the debug level.

verify option
.............

This is the "just verify the password."  option.  Verifies the password
provided against the password file.

passwd-conf option (-v)
.......................

This is the "specify a password conf file."  option.  This option takes
a string argument.  Specify a filename or a PKCS #11 URL to read the CAs
from.

create-conf option
..................

This is the "generate a password configuration file."  option.  This
option takes a string argument.  This generates a password configuration
file (tpasswd.conf) containing the required for TLS parameters.

srptool exit status
...................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

srptool See Also
................

gnutls-cli-debug (1), gnutls-serv (1), srptool (1), psktool (1),
certtool (1)

srptool Examples
................

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

4.3.3 Anonymous authentication
------------------------------

The anonymous key exchange offers encryption without any indication of
the peer's identity.  This kind of authentication is vulnerable to a man
in the middle attack, but can be used even if there is no prior
communication or shared trusted parties with the peer.  It is useful to
establish a session over which certificate authentication will occur in
order to hide the indentities of the participants from passive
eavesdroppers.  It is only available under TLS 1.2 or earlier versions.

Unless in the above case, it is not recommended to use anonymous
authentication.  In the cases where there is no prior communication with
the peers, an alternative with better properties, such as key
continuity, is trust on first use (see Verifying a certificate using trust on first use authentication).

The available key exchange algorithms for anonymous authentication are
shown below, but note that few public servers support them, and they
have to be explicitly enabled.  These ciphersuites are negotiated only
under TLS 1.2.

'ANON_DH:'
     This algorithm exchanges Diffie-Hellman parameters.

'ANON_ECDH:'
     This algorithm exchanges elliptic curve Diffie-Hellman parameters.
     It is more efficient than ANON_DH on equivalent security levels.

4.4 Selecting an appropriate authentication method
==================================================

This section provides some guidance on how to use the available
authentication methods in GnuTLS in various scenarios.

4.4.1 Two peers with an out-of-band channel
-------------------------------------------

Let's consider two peers who need to communicate over an untrusted
channel (the Internet), but have an out-of-band channel available.  The
latter channel is considered safe from eavesdropping and message
modification and thus can be used for an initial bootstrapping of the
protocol.  The options available are:
   * Pre-shared keys (see PSK authentication).  The server and a
     client communicate a shared randomly generated key over the trusted
     channel and use it to negotiate further sessions over the untrusted
     channel.

   * Passwords (see SRP authentication).  The client
     communicates to the server its username and password of choice and
     uses it to negotiate further sessions over the untrusted channel.

   * Public keys (see Certificate authentication).  The client
     and the server exchange their public keys (or fingerprints of them)
     over the trusted channel.  On future sessions over the untrusted
     channel they verify the key being the same (similar to
     Verifying a certificate using trust on first use authentication).

Provided that the out-of-band channel is trusted all of the above
provide a similar level of protection.  An out-of-band channel may be
the initial bootstrapping of a user's PC in a corporate environment,
in-person communication, communication over an alternative network (e.g.
the phone network), etc.

4.4.2 Two peers without an out-of-band channel
----------------------------------------------

When an out-of-band channel is not available a peer cannot be reliably
authenticated.  What can be done, however, is to allow some form of
registration of users connecting for the first time and ensure that
their keys remain the same after that initial connection.  This is
termed key continuity or trust on first use (TOFU).

The available option is to use public key authentication (see
Certificate authentication).  The client and the server store each
other's public keys (or fingerprints of them) and associate them with
their identity.  On future sessions over the untrusted channel they
verify the keys being the same (see Verifying a certificate using trust on first use authentication).

To mitigate the uncertainty of the information exchanged in the first
connection other channels over the Internet may be used, e.g., DNSSEC
(see Verifying a certificate using DANE).

4.4.3 Two peers and a trusted third party
-----------------------------------------

When a trusted third party is available (or a certificate authority) the
most suitable option is to use certificate authentication (see
Certificate authentication).  The client and the server obtain
certificates that associate their identity and public keys using a
digital signature by the trusted party and use them to on the subsequent
communications with each other.  Each party verifies the peer's
certificate using the trusted third party's signature.  The parameters
of the third party's signature are present in its certificate which must
be available to all communicating parties.

While the above is the typical authentication method for servers in the
Internet by using the commercial CAs, the users that act as clients in
the protocol rarely possess such certificates.  In that case a hybrid
method can be used where the server is authenticated by the client using
the commercial CAs and the client is authenticated based on some
information the client provided over the initial server-authenticated
channel.  The available options are:
   * Passwords (see SRP authentication).  The client
     communicates to the server its username and password of choice on
     the initial server-authenticated connection and uses it to
     negotiate further sessions.  This is possible because the SRP
     protocol allows for the server to be authenticated using a
     certificate and the client using the password.

   * Public keys (see Certificate authentication).  The client
     sends its public key to the server (or a fingerprint of it) over
     the initial server-authenticated connection.  On future sessions
     the client verifies the server using the third party certificate
     and the server verifies that the client's public key remained the
     same (see Verifying a certificate using trust on first use authentication).

5 Abstract key types and Hardware security modules
**************************************************

In several cases storing the long term cryptographic keys in a hard disk
or even in memory poses a significant risk.  Once the system they are
stored is compromised the keys must be replaced as the secrecy of future
sessions is no longer guaranteed.  Moreover, past sessions that were not
protected by a perfect forward secrecy offering ciphersuite are also to
be assumed compromised.

If such threats need to be addressed, then it may be wise storing the
keys in a security module such as a smart card, an HSM or the TPM chip.
Those modules ensure the protection of the cryptographic keys by only
allowing operations on them and preventing their extraction.  The
purpose of the abstract key API is to provide an API that will allow the
handle of keys in memory and files, as well as keys stored in such
modules.

In GnuTLS the approach is to handle all keys transparently by the high
level API, e.g., the API that loads a key or certificate from a file.
The high-level API will accept URIs in addition to files that specify
keys on an HSM or in TPM, and a callback function will be used to obtain
any required keys.  The URI format is defined in [see PKCS11URI].

More information on the API is provided in the next sections.  Examples
of a URI of a certificate stored in an HSM, as well as a key stored in
the TPM chip are shown below.  To discover the URIs of the objects the
'p11tool' (see p11tool Invocation).
     pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315; \
     manufacturer=EnterSafe;object=test1;type=cert

5.1 Abstract key types
======================

Since there are many forms of a public or private keys supported by
GnuTLS such as X.509, PKCS #11 or TPM 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 to
sign an X.509 certificate with a key that resides in a token the
following steps can be used.

     #include <gnutls/abstract.h>

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

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

       /* keys stored in tokens are identified by URLs */
       gnutls_privkey_import_url(abs_key, key_url);

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

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

5.1.1 Public keys
-----------------

An abstract 'gnutls_pubkey_t' can be initialized and freed by using the
functions below.

'INT gnutls_pubkey_init (gnutls_pubkey_t * KEY)'
'VOID gnutls_pubkey_deinit (gnutls_pubkey_t KEY)'

After initialization its values can be imported from an existing
structure like 'gnutls_x509_crt_t', or through an ASN.1 encoding of the
X.509 'SubjectPublicKeyInfo' sequence.

'INT gnutls_pubkey_import_x509 (gnutls_pubkey_t KEY, gnutls_x509_crt_t CRT, unsigned int FLAGS)'
'INT gnutls_pubkey_import_pkcs11 (gnutls_pubkey_t KEY, gnutls_pkcs11_obj_t OBJ, unsigned int FLAGS)'

'INT gnutls_pubkey_import_url (gnutls_pubkey_t KEY, const char * URL, unsigned int FLAGS)'
'INT gnutls_pubkey_import_privkey (gnutls_pubkey_t KEY, gnutls_privkey_t PKEY, unsigned int USAGE, unsigned int FLAGS)'
'INT gnutls_pubkey_import (gnutls_pubkey_t KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
'INT gnutls_pubkey_export (gnutls_pubkey_t KEY, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'

 -- Function: int gnutls_pubkey_export2 (gnutls_pubkey_t KEY,
          gnutls_x509_crt_fmt_t FORMAT, gnutls_datum_t * OUT)
     KEY: Holds the certificate

     FORMAT: the format of output params.  One of PEM or DER.

     OUT: will contain a certificate PEM or DER encoded

     This function will export the public key to DER or PEM format.  The
     contents of the exported data is the SubjectPublicKeyInfo X.509
     structure.

     The output buffer will be allocated using 'gnutls_malloc()' .

     If the structure is PEM encoded, it will have a header of "BEGIN
     CERTIFICATE".

     *Returns:* In case of failure a negative error code will be
     returned, and 0 on success.

     *Since:* 3.1.3

Other helper functions that allow directly importing from raw X.509
structures are shown below.

'INT gnutls_pubkey_import_x509_raw (gnutls_pubkey_t PKEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)'

An important function is gnutls_pubkey_import_url which will
import public keys from URLs that identify objects stored in tokens (see
Smart cards and HSMs and Trusted Platform Module).  A
function to check for a supported by GnuTLS URL is
gnutls_url_is_supported.

 -- Function: unsigned gnutls_url_is_supported (const char * URL)
     URL: A URI to be tested

     Check whether the provided 'url' is supported.  Depending on the
     system libraries GnuTLS may support pkcs11, tpmkey or other URLs.

     *Returns:* return non-zero if the given URL is supported, and zero
     if it is not known.

     *Since:* 3.1.0

Additional functions are available that will return information over a
public key, such as a unique key ID, as well as a function that given a
public key fingerprint would provide a memorable sketch.

Note that gnutls_pubkey_get_key_id calculates a SHA1 digest of
the public key as a DER-formatted, subjectPublicKeyInfo object.  Other
implementations use different approaches, e.g., some use the "common
method" described in section 4.2.1.2 of [see RFC5280] which
calculates a digest on a part of the subjectPublicKeyInfo object.

'INT gnutls_pubkey_get_pk_algorithm (gnutls_pubkey_t KEY, unsigned int * BITS)'
'INT gnutls_pubkey_get_preferred_hash_algorithm (gnutls_pubkey_t KEY, gnutls_digest_algorithm_t * HASH, unsigned int * MAND)'
'INT gnutls_pubkey_get_key_id (gnutls_pubkey_t KEY, unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
'INT gnutls_random_art (gnutls_random_art_t TYPE, const char * KEY_TYPE, unsigned int KEY_SIZE, void * FPR, size_t FPR_SIZE, gnutls_datum_t * ART)'

To export the key-specific parameters, or obtain a unique key ID the
following functions are provided.

'INT gnutls_pubkey_export_rsa_raw2 (gnutls_pubkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E, unsigned FLAGS)'
'INT gnutls_pubkey_export_dsa_raw2 (gnutls_pubkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y, unsigned FLAGS)'
'INT gnutls_pubkey_export_ecc_raw2 (gnutls_pubkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y, unsigned int FLAGS)'
'INT gnutls_pubkey_export_ecc_x962 (gnutls_pubkey_t KEY, gnutls_datum_t * PARAMETERS, gnutls_datum_t * ECPOINT)'

5.1.2 Private keys
------------------

An abstract 'gnutls_privkey_t' can be initialized and freed by using the
functions below.

'INT gnutls_privkey_init (gnutls_privkey_t * KEY)'
'VOID gnutls_privkey_deinit (gnutls_privkey_t KEY)'

After initialization its values can be imported from an existing
structure like 'gnutls_x509_privkey_t', but unlike public keys it cannot
be exported.  That is to allow abstraction over keys stored in hardware
that makes available only operations.

'INT gnutls_privkey_import_x509 (gnutls_privkey_t PKEY, gnutls_x509_privkey_t KEY, unsigned int FLAGS)'
'INT gnutls_privkey_import_pkcs11 (gnutls_privkey_t PKEY, gnutls_pkcs11_privkey_t KEY, unsigned int FLAGS)'

Other helper functions that allow directly importing from raw X.509
structures are shown below.  Again, as with public keys, private keys
can be imported from a hardware module using URLs.

 -- Function: int gnutls_privkey_import_url (gnutls_privkey_t KEY, const
          char * URL, unsigned int FLAGS)
     KEY: A key of type 'gnutls_privkey_t'

     URL: A PKCS 11 url

     FLAGS: should be zero

     This function will import a PKCS11 or TPM URL as a private key.
     The supported URL types can be checked using
     'gnutls_url_is_supported()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.0

'INT gnutls_privkey_import_x509_raw (gnutls_privkey_t PKEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS)'
'INT gnutls_privkey_get_pk_algorithm (gnutls_privkey_t KEY, unsigned int * BITS)'
'GNUTLS_PRIVKEY_TYPE_T gnutls_privkey_get_type (gnutls_privkey_t KEY)'
'INT gnutls_privkey_status (gnutls_privkey_t KEY)'

In order to support cryptographic operations using an external API, the
following function is provided.  This allows for a simple extensibility
API without resorting to PKCS #11.

 -- Function: int gnutls_privkey_import_ext4 (gnutls_privkey_t PKEY,
          void * USERDATA, gnutls_privkey_sign_data_func SIGN_DATA_FN,
          gnutls_privkey_sign_hash_func SIGN_HASH_FN,
          gnutls_privkey_decrypt_func DECRYPT_FN,
          gnutls_privkey_deinit_func DEINIT_FN, gnutls_privkey_info_func
          INFO_FN, unsigned int FLAGS)
     PKEY: The private key

     USERDATA: private data to be provided to the callbacks

     SIGN_DATA_FN: callback for signature operations (may be 'NULL' )

     SIGN_HASH_FN: callback for signature operations (may be 'NULL' )

     DECRYPT_FN: callback for decryption operations (may be 'NULL' )

     DEINIT_FN: a deinitialization function

     INFO_FN: returns info about the public key algorithm (should not be
     'NULL' )

     FLAGS: Flags for the import

     This function will associate the given callbacks with the
     'gnutls_privkey_t' type.  At least one of the callbacks must be
     non-null.  If a deinitialization function is provided then flags is
     assumed to contain 'GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE' .

     Note that in contrast with the signing function of
     'gnutls_privkey_import_ext3()' , the signing functions provided to
     this function take explicitly the signature algorithm as parameter
     and different functions are provided to sign the data and hashes.

     The 'sign_hash_fn' is to be called to sign pre-hashed data.  The
     input to the callback is the output of the hash (such as SHA256)
     corresponding to the signature algorithm.  For RSA PKCS'1'
     signatures, the signature algorithm can be set to
     'GNUTLS_SIGN_RSA_RAW' , and in that case the data should be handled
     as if they were an RSA PKCS'1' DigestInfo structure.

     The 'sign_data_fn' is to be called to sign data.  The input data
     will be he data to be signed (and hashed), with the provided
     signature algorithm.  This function is to be used for signature
     algorithms like Ed25519 which cannot take pre-hashed data as input.

     When both 'sign_data_fn' and 'sign_hash_fn' functions are provided
     they must be able to operate on all the supported signature
     algorithms, unless prohibited by the type of the algorithm (e.g.,
     as with Ed25519).

     The 'info_fn' must provide information on the signature algorithms
     supported by this private key, and should support the flags
     'GNUTLS_PRIVKEY_INFO_PK_ALGO' ,
     'GNUTLS_PRIVKEY_INFO_HAVE_SIGN_ALGO' and
     'GNUTLS_PRIVKEY_INFO_PK_ALGO_BITS' .  It must return -1 on unknown
     flags.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.6.0

On the private keys where exporting of parameters is possible (i.e.,
software keys), the following functions are also available.

'INT gnutls_privkey_export_rsa_raw2 (gnutls_privkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E, gnutls_datum_t * D, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * U, gnutls_datum_t * E1, gnutls_datum_t * E2, unsigned int FLAGS)'
'INT gnutls_privkey_export_dsa_raw2 (gnutls_privkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y, gnutls_datum_t * X, unsigned int FLAGS)'
'INT gnutls_privkey_export_ecc_raw2 (gnutls_privkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y, gnutls_datum_t * K, unsigned int FLAGS)'

5.1.3 Operations
----------------

The abstract key types can be used to access signing and signature
verification operations with the underlying keys.

 -- Function: int gnutls_pubkey_verify_data2 (gnutls_pubkey_t PUBKEY,
          gnutls_sign_algorithm_t ALGO, unsigned int FLAGS, const
          gnutls_datum_t * DATA, const gnutls_datum_t * SIGNATURE)
     PUBKEY: Holds the public key

     ALGO: The signature algorithm used

     FLAGS: Zero or an OR list of 'gnutls_certificate_verify_flags'

     DATA: holds the signed data

     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 zero or positive
     code on success.  For known to be insecure signatures this function
     will return 'GNUTLS_E_INSUFFICIENT_SECURITY' unless the flag
     'GNUTLS_VERIFY_ALLOW_BROKEN' is specified.

     *Since:* 3.0

 -- Function: int gnutls_pubkey_verify_hash2 (gnutls_pubkey_t KEY,
          gnutls_sign_algorithm_t ALGO, unsigned int FLAGS, const
          gnutls_datum_t * HASH, const gnutls_datum_t * SIGNATURE)
     KEY: Holds the public key

     ALGO: The signature algorithm used

     FLAGS: Zero or an OR list of 'gnutls_certificate_verify_flags'

     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 public key.  Note that unlike
     'gnutls_privkey_sign_hash()' , this function accepts a signature
     algorithm instead of a digest algorithm.  You can use
     'gnutls_pk_to_sign()' to get the appropriate value.

     *Returns:* In case of a verification failure
     'GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and zero or positive
     code on success.  For known to be insecure signatures this function
     will return 'GNUTLS_E_INSUFFICIENT_SECURITY' unless the flag
     'GNUTLS_VERIFY_ALLOW_BROKEN' is specified.

     *Since:* 3.0

 -- Function: int gnutls_pubkey_encrypt_data (gnutls_pubkey_t KEY,
          unsigned int FLAGS, const gnutls_datum_t * PLAINTEXT,
          gnutls_datum_t * CIPHERTEXT)
     KEY: Holds the public key

     FLAGS: should be 0 for now

     PLAINTEXT: The data to be encrypted

     CIPHERTEXT: contains the encrypted data

     This function will encrypt the given data, using the public key.
     On success the 'ciphertext' will be allocated using
     'gnutls_malloc()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0

 -- 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: Zero or one of 'gnutls_privkey_flags_t'

     DATA: holds the data to be signed

     SIGNATURE: will contain the signature allocated 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 the SHA family for the DSA
     keys.

     You may use 'gnutls_pubkey_get_preferred_hash_algorithm()' to
     determine the hash algorithm.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

 -- 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 or one of 'gnutls_privkey_flags_t'

     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.

     You may use 'gnutls_pubkey_get_preferred_hash_algorithm()' to
     determine the hash algorithm.

     The flags may be 'GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA' or
     'GNUTLS_PRIVKEY_SIGN_FLAG_RSA_PSS' .  In the former case this
     function will ignore 'hash_algo' and perform a raw PKCS1 signature,
     and in the latter an RSA-PSS signature will be generated.

     Note that, not all algorithm support signing already hashed data.
     When signing with Ed25519, 'gnutls_privkey_sign_data()' should be
     used.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

 -- 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' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

Signing existing structures, such as certificates, CRLs, or certificate
requests, as well as associating public keys with structures is also
possible using the key abstractions.

 -- Function: int gnutls_x509_crq_set_pubkey (gnutls_x509_crq_t CRQ,
          gnutls_pubkey_t KEY)
     CRQ: should contain a 'gnutls_x509_crq_t' type

     KEY: holds a public key

     This function will set the public parameters from the given public
     key to the request.  The 'key' can be deallocated after that.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

 -- Function: int gnutls_x509_crt_set_pubkey (gnutls_x509_crt_t CRT,
          gnutls_pubkey_t KEY)
     CRT: should contain a 'gnutls_x509_crt_t' type

     KEY: holds a public key

     This function will set the public parameters from the given public
     key to the certificate.  The 'key' can be deallocated after that.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0
'INT gnutls_x509_crt_privkey_sign (gnutls_x509_crt_t CRT, gnutls_x509_crt_t ISSUER, gnutls_privkey_t ISSUER_KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'
'INT gnutls_x509_crl_privkey_sign (gnutls_x509_crl_t CRL, gnutls_x509_crt_t ISSUER, gnutls_privkey_t ISSUER_KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'
'INT gnutls_x509_crq_privkey_sign (gnutls_x509_crq_t CRQ, gnutls_privkey_t KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'

5.2 System and application-specific keys
========================================

5.2.1 System-specific keys
--------------------------

In several systems there are keystores which allow to read, store and
use certificates and private keys.  For these systems GnuTLS provides
the system-key API in 'gnutls/system-keys.h'.  That API provides the
ability to iterate through all stored keys, add and delete keys as well
as use these keys using a URL which starts with "system:".  The format
of the URLs is system-specific.  The 'systemkey' tool is also provided
to assist in listing keys and debugging.

The systems supported via this API are the following.
   * Windows Cryptography API (CNG)

 -- Function: int gnutls_system_key_iter_get_info
          (gnutls_system_key_iter_t * ITER, unsigned CERT_TYPE, char **
          CERT_URL, char ** KEY_URL, char ** LABEL, gnutls_datum_t *
          DER, unsigned int FLAGS)
     ITER: an iterator of the system keys (must be set to 'NULL'
     initially)

     CERT_TYPE: A value of gnutls_certificate_type_t which indicates the
     type of certificate to look for

     CERT_URL: The certificate URL of the pair (may be 'NULL' )

     KEY_URL: The key URL of the pair (may be 'NULL' )

     LABEL: The friendly name (if any) of the pair (may be 'NULL' )

     DER: if non-NULL the DER data of the certificate

     FLAGS: should be zero

     This function will return on each call a certificate and key pair
     URLs, as well as a label associated with them, and the DER-encoded
     certificate.  When the iteration is complete it will return
     'GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE' .

     Typically 'cert_type' should be 'GNUTLS_CRT_X509' .

     All values set are allocated and must be cleared using
     'gnutls_free()' ,

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.4.0

'VOID gnutls_system_key_iter_deinit (gnutls_system_key_iter_t ITER)'
'INT gnutls_system_key_add_x509 (gnutls_x509_crt_t CRT, gnutls_x509_privkey_t PRIVKEY, const char * LABEL, char ** CERT_URL, char ** KEY_URL)'
'INT gnutls_system_key_delete (const char * CERT_URL, const char * KEY_URL)'

5.2.2 Application-specific keys
-------------------------------

For systems where GnuTLS doesn't provide a system specific store, it may
often be desirable to define a custom class of keys that are identified
via URLs and available to GnuTLS calls such as
gnutls_certificate_set_x509_key_file2.  Such keys can be registered
using the API in 'gnutls/urls.h'.  The function which registers such
keys is gnutls_register_custom_url.

 -- Function: int gnutls_register_custom_url (const gnutls_custom_url_st
          * ST)
     ST: A 'gnutls_custom_url_st' structure

     Register a custom URL. This will affect the following functions:
     'gnutls_url_is_supported()' , 'gnutls_privkey_import_url()' ,
     gnutls_pubkey_import_url, 'gnutls_x509_crt_import_url()' and all
     functions that depend on them, e.g.,
     'gnutls_certificate_set_x509_key_file2()' .

     The provided structure and callback functions must be valid
     throughout the lifetime of the process.  The registration of an
     existing URL type will fail with 'GNUTLS_E_INVALID_REQUEST' .
     Since GnuTLS 3.5.0 this function can be used to override the
     builtin URLs.

     This function is not thread safe.

     *Returns:* returns zero if the given structure was imported or a
     negative value otherwise.

     *Since:* 3.4.0

The input to this function are three callback functions as well as the
prefix of the URL, (e.g., "mypkcs11:") and the length of the prefix.
The types of the callbacks are shown below, and are expected to use the
exported gnutls functions to import the keys and certificates.  E.g., a
typical 'import_key' callback should use
gnutls_privkey_import_ext4.

     typedef int (*gnutls_privkey_import_url_func)(gnutls_privkey_t pkey,
                                                   const char *url,
                                                   unsigned flags);

     typedef int (*gnutls_x509_crt_import_url_func)(gnutls_x509_crt_t pkey,
                                                    const char *url,
                                                    unsigned flags);

     /* The following callbacks are optional */

     /* This is to enable gnutls_pubkey_import_url() */
     typedef int (*gnutls_pubkey_import_url_func)(gnutls_pubkey_t pkey,
     					     const char *url, unsigned flags);

     /* This is to allow constructing a certificate chain. It will be provided
      * the initial certificate URL and the certificate to find its issuer, and must
      * return zero and the DER encoding of the issuer's certificate. If not available,
      * it should return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE. */
     typedef int (*gnutls_get_raw_issuer_func)(const char *url, gnutls_x509_crt_t crt,
     					  gnutls_datum_t *issuer_der, unsigned flags);

     typedef struct custom_url_st {
             const char *name;
             unsigned name_size;
             gnutls_privkey_import_url_func import_key;
             gnutls_x509_crt_import_url_func import_crt;
             gnutls_pubkey_import_url_func import_pubkey;
     	gnutls_get_raw_issuer_func get_issuer;
     } gnutls_custom_url_st;

5.3 Smart cards and HSMs
========================

In this section we present the smart-card and hardware security module
(HSM) support in GnuTLS using PKCS #11 [see PKCS11].  Hardware
security modules and smart cards provide a way to store private keys and
perform operations on them without exposing them.  This decouples
cryptographic keys from the applications that use them and provide an
additional security layer against cryptographic key extraction.  Since
this can also be achieved in software components such as in Gnome
keyring, we will use the term security module to describe any
cryptographic key separation subsystem.

PKCS #11 is plugin API allowing applications to access cryptographic
operations on a security module, as well as to objects residing on it.
PKCS #11 modules exist for hardware tokens such as smart cards(1),
cryptographic tokens, as well as for software modules like Gnome
Keyring.  The objects residing on a security module may be certificates,
public keys, private keys or secret keys.  Of those certificates and
public/private key pairs can be used with GnuTLS.  PKCS #11's main
advantage is that it allows operations on private key objects such as
decryption and signing without exposing the key.  In GnuTLS the PKCS #11
functionality is available in 'gnutls/pkcs11.h'.

Figure 5.1: PKCS #11 module usage.

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

   (1) For example, OpenSC-supported cards.

5.3.1 Initialization
--------------------

To allow all GnuTLS applications to transparently access smart cards and
tokens, PKCS #11 is automatically initialized during the first call of a
PKCS #11 related function, in a thread safe way.  The default
initialization process, utilizes p11-kit configuration, and loads any
appropriate PKCS #11 modules.  The p11-kit configuration files(1) are
typically stored in '/etc/pkcs11/modules/'.  For example a file that
will instruct GnuTLS to load the OpenSC module, could be named
'/etc/pkcs11/modules/opensc.module' and contain the following:

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

If you use these configuration files, then there is no need for other
initialization in GnuTLS, except for the PIN and token callbacks (see
next section).  In several cases, however, it is desirable to limit
badly behaving modules (e.g., modules that add an unacceptable delay on
initialization) to single applications.  That can be done using the
"enable-in:" option followed by the base name of applications that this
module should be used.

It is also possible to manually initialize or even disable the PKCS #11
subsystem if the default settings are not desirable or not available
(see PKCS11 Manual Initialization for more information).

Note that, PKCS #11 modules behave in a peculiar way after a fork; they
require a reinitialization of all the used PKCS #11 resources.  While
GnuTLS automates that process, there are corner cases where it is not
possible to handle it correctly in an automated way(2).  For that, it is
recommended not to mix fork() and PKCS #11 module usage.  It is
recommended to initialize and use any PKCS #11 resources in a single
process.

Older versions of GnuTLS required to call gnutls_pkcs11_reinit
after a fork() call; since 3.3.0 this is no longer required.

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

   (1) <https://p11-glue.github.io/p11-glue/p11-kit.html>

   (2) For example when an open session is to be reinitialized, but the
PIN is not available to GnuTLS (e.g., it was entered at a pinpad).

5.3.2 Manual initialization of user-specific modules
----------------------------------------------------

In systems where one cannot rely on a globally available p11-kit
configuration to be available, it is still possible to utilize PKCS #11
objects.  That can be done by loading directly the PKCS #11 shared
module in the application using gnutls_pkcs11_add_provider,
after having called gnutls_pkcs11_init specifying the
'GNUTLS_PKCS11_FLAG_MANUAL' flag.

 -- Function: int gnutls_pkcs11_add_provider (const char * NAME, const
          char * PARAMS)
     NAME: The filename of the module

     PARAMS: should be NULL or a known string (see description)

     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.

     When loading a module to be used for certificate verification, use
     the string 'trusted' as 'params' .

     Note that this function is not thread safe.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

In that case, the application will only have access to the modules
explicitly loaded.  If the 'GNUTLS_PKCS11_FLAG_MANUAL' flag is specified
and no calls to gnutls_pkcs11_add_provider are made, then the
PKCS #11 functionality is effectively disabled.

 -- Function: int gnutls_pkcs11_init (unsigned int FLAGS, const char *
          DEPRECATED_CONFIG_FILE)
     FLAGS: An ORed sequence of 'GNUTLS_PKCS11_FLAG_' *

     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.

     You don't need to call this function since GnuTLS 3.3.0 because it
     is being called during the first request PKCS 11 operation.  That
     call will assume the 'GNUTLS_PKCS11_FLAG_AUTO' flag.  If another
     flags are required then it must be called independently prior to
     any PKCS 11 operation.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

5.3.3 Accessing objects that require a PIN
------------------------------------------

Objects stored in token such as a private keys are typically protected
from access by a PIN or password.  This PIN may be required to either
read the object (if allowed) or to perform operations with it.  To allow
obtaining the PIN when accessing a protected object, as well as probe
the user to insert the token the following functions allow to set a
callback.

'VOID gnutls_pkcs11_set_token_function (gnutls_pkcs11_token_callback_t FN, void * USERDATA)'
'VOID gnutls_pkcs11_set_pin_function (gnutls_pin_callback_t FN, void * USERDATA)'
'INT gnutls_pkcs11_add_provider (const char * NAME, const char * PARAMS)'
'GNUTLS_PIN_CALLBACK_T gnutls_pkcs11_get_pin_function (void ** USERDATA)'

The callback is of type 'gnutls_pin_callback_t' and will have as input
the provided userdata, the PIN attempt number, a URL describing the
token, a label describing the object and flags.  The PIN must be at most
of 'pin_max' size and must be copied to pin variable.  The function must
return 0 on success or a negative error code otherwise.

typedef int (*gnutls_pin_callback_t) (void *userdata, int attempt,
                                      const char *token_url,
                                      const char *token_label,
                                      unsigned int flags,
                                      char *pin, size_t pin_max);

The flags are of 'gnutls_pin_flag_t' type and are explained below.

'GNUTLS_PIN_USER'
     The PIN for the user.
'GNUTLS_PIN_SO'
     The PIN for the security officer (admin).
'GNUTLS_PIN_FINAL_TRY'
     This is the final try before blocking.
'GNUTLS_PIN_COUNT_LOW'
     Few tries remain before token blocks.
'GNUTLS_PIN_CONTEXT_SPECIFIC'
     The PIN is for a specific action and key like signing.
'GNUTLS_PIN_WRONG'
     Last given PIN was not correct.

Figure 5.2: The 'gnutls_pin_flag_t' enumeration.

Note that due to limitations of PKCS #11 there are issues when multiple
libraries are sharing a module.  To avoid this problem GnuTLS uses
p11-kit that provides a middleware to control access to resources over
the multiple users.

To avoid conflicts with multiple registered callbacks for PIN functions,
see gnutls_pkcs11_get_pin_function may be used to check for any
previously set functions.  In addition context specific PIN functions
are allowed, e.g., by using functions below.

'VOID gnutls_certificate_set_pin_function (gnutls_certificate_credentials_t CRED, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID gnutls_pubkey_set_pin_function (gnutls_pubkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID gnutls_privkey_set_pin_function (gnutls_privkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID gnutls_pkcs11_obj_set_pin_function (gnutls_pkcs11_obj_t OBJ, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID gnutls_x509_crt_set_pin_function (gnutls_x509_crt_t CRT, gnutls_pin_callback_t FN, void * USERDATA)'

5.3.4 Reading objects
---------------------

All PKCS #11 objects are referenced by GnuTLS functions by URLs as
described in [see PKCS11URI].  This allows for a consistent naming
of objects across systems and applications in the same system.  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;type=public;\
     id=32f153f3e37990b08624141077ca5dec2d15faed

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

Objects stored in a PKCS #11 token can typically be extracted if they
are not marked as sensitive.  Usually only private keys are marked as
sensitive and cannot be extracted, while certificates and other data can
be retrieved.  The functions that can be used to enumerate and access
objects are shown below.

'INT gnutls_pkcs11_obj_list_import_url4 (gnutls_pkcs11_obj_t ** P_LIST, unsigned int * N_LIST, const char * URL, unsigned int FLAGS)'
'INT gnutls_pkcs11_obj_import_url (gnutls_pkcs11_obj_t OBJ, const char * URL, unsigned int FLAGS)'
'INT gnutls_pkcs11_obj_export_url (gnutls_pkcs11_obj_t OBJ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)'

 -- Function: int gnutls_pkcs11_obj_get_info (gnutls_pkcs11_obj_t OBJ,
          gnutls_pkcs11_obj_info_t ITYPE, void * OUTPUT, size_t *
          OUTPUT_SIZE)
     OBJ: should contain a 'gnutls_pkcs11_obj_t' type

     ITYPE: Denotes the type of information requested

     OUTPUT: where output will be stored

     OUTPUT_SIZE: contains the maximum size of the output buffer and
     will be overwritten with the actual size.

     This function will return information about the PKCS11 certificate
     such as the label, id as well as token information where the key is
     stored.

     When output is text, a null terminated string is written to
     'output' and its string length is written to 'output_size' (without
     null terminator).  If the buffer is too small, 'output_size' will
     contain the expected buffer size (with null terminator for text)
     and return 'GNUTLS_E_SHORT_MEMORY_BUFFER' .

     In versions previously to 3.6.0 this function included the null
     terminator to 'output_size' .  After 3.6.0 the output size doesn't
     include the terminator character.

     *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error
     code on error.

     *Since:* 2.12.0

'INT gnutls_x509_crt_import_pkcs11 (gnutls_x509_crt_t CRT, gnutls_pkcs11_obj_t PKCS11_CRT)'
'INT gnutls_x509_crt_import_url (gnutls_x509_crt_t CRT, const char * URL, unsigned int FLAGS)'
'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)'

Properties of the physical token can also be accessed and altered with
GnuTLS.  For example data in a token can be erased (initialized), PIN
can be altered, etc.

'INT gnutls_pkcs11_token_init (const char * TOKEN_URL, const char * SO_PIN, const char * LABEL)'
'INT gnutls_pkcs11_token_get_url (unsigned int SEQ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)'
'INT gnutls_pkcs11_token_get_info (const char * URL, gnutls_pkcs11_token_info_t TTYPE, void * OUTPUT, size_t * OUTPUT_SIZE)'
'INT gnutls_pkcs11_token_get_flags (const char * URL, unsigned int * FLAGS)'
'INT gnutls_pkcs11_token_set_pin (const char * TOKEN_URL, const char * OLDPIN, const char * NEWPIN, unsigned int FLAGS)'

The following examples demonstrate the usage of the API. The first
example will list all available PKCS #11 tokens in a system and the
latter will list all certificates in a token that have a corresponding
private key.

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

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

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

#define URL "pkcs11:URL"

int main(int argc, char **argv)
{
        gnutls_pkcs11_obj_t *obj_list;
        gnutls_x509_crt_t xcrt;
        unsigned int obj_list_size = 0;
        gnutls_datum_t cinfo;
        int ret;
        unsigned int i;

        ret = gnutls_pkcs11_obj_list_import_url4(&obj_list, &obj_list_size, URL,
                                                GNUTLS_PKCS11_OBJ_FLAG_CRT|
                                                GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY);
        if (ret < 0)
                return -1;

        /* 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", i, cinfo.data);

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

        for (i = 0; i < obj_list_size; i++)
                gnutls_pkcs11_obj_deinit(obj_list[i]);
	gnutls_free(obj_list);

        return 0;
}

5.3.5 Writing objects
---------------------

With GnuTLS you can copy existing private keys and certificates to a
token.  Note that when copying private keys it is recommended to mark
them as sensitive using the 'GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE' to
prevent its extraction.  An object can be marked as private using the
flag 'GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE', to require PIN to be entered
before accessing the object (for operations or otherwise).

 -- Function: int gnutls_pkcs11_copy_x509_privkey2 (const char *
          TOKEN_URL, gnutls_x509_privkey_t KEY, const char * LABEL,
          const gnutls_datum_t * CID, 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

     CID: The CKA_ID to set for the object -if NULL, the ID will be
     derived from the public key

     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.

     Since 3.6.3 the objects are marked as sensitive by default unless
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE' is specified.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.4.0

 -- Function: int gnutls_pkcs11_copy_x509_crt2 (const char * TOKEN_URL,
          gnutls_x509_crt_t CRT, const char * LABEL, const
          gnutls_datum_t * CID, unsigned int FLAGS)
     TOKEN_URL: A PKCS '11' URL specifying a token

     CRT: The certificate to copy

     LABEL: The name to be used for the stored data

     CID: The CKA_ID to set for the object -if NULL, the ID will be
     derived from the public key

     FLAGS: One of GNUTLS_PKCS11_OBJ_FLAG_*

     This function will copy a certificate into a PKCS '11' token
     specified by a URL. Valid flags to mark the certificate:
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED' ,
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE' ,
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_CA' ,
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.4.0

 -- 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. Note that
     not all tokens support the delete operation.

     *Returns:* On success, the number of objects deleted is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

5.3.6 Low Level Access
----------------------

When it is needed to use PKCS#11 functionality which is not wrapped by
GnuTLS, it is possible to extract the PKCS#11 session, object or token
pointers.  That allows an application to still access the low-level
functionality, while at the same time take advantage of the URI
addressing scheme supported by GnuTLS.

 -- Function: int gnutls_pkcs11_token_get_ptr (const char * URL, void **
          PTR, unsigned long * SLOT_ID, unsigned int FLAGS)
     URL: should contain a PKCS'11' URL identifying a token

     PTR: will contain the CK_FUNCTION_LIST_PTR pointer

     SLOT_ID: will contain the slot_id (may be 'NULL' )

     FLAGS: should be zero

     This function will return the function pointer of the specified
     token by the URL. The returned pointers are valid until gnutls is
     deinitialized, c.f.  '_global_deinit()' .

     *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error
     code on error.

     *Since:* 3.6.3

 -- Function: int gnutls_pkcs11_obj_get_ptr (gnutls_pkcs11_obj_t OBJ,
          void ** PTR, void ** SESSION, void ** OHANDLE, unsigned long *
          SLOT_ID, unsigned int FLAGS)
     OBJ: should contain a 'gnutls_pkcs11_obj_t' type

     PTR: will contain the CK_FUNCTION_LIST_PTR pointer (may be 'NULL' )

     SESSION: will contain the CK_SESSION_HANDLE of the object

     OHANDLE: will contain the CK_OBJECT_HANDLE of the object

     SLOT_ID: the identifier of the slot (may be 'NULL' )

     FLAGS: Or sequence of GNUTLS_PKCS11_OBJ_* flags

     Obtains the PKCS'11' session handles of an object.  'session' and
     'ohandle' must be deinitialized by the caller.  The returned
     pointers are independent of the 'obj' lifetime.

     *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error
     code on error.

     *Since:* 3.6.3

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

It is possible to use a PKCS #11 token to a TLS session, as shown in
ex-pkcs11-client.  In addition the following functions can be
used to load PKCS #11 key and certificates by specifying a PKCS #11 URL
instead of a filename.

'INT gnutls_certificate_set_x509_trust_file (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)'
'INT gnutls_certificate_set_x509_key_file2 (gnutls_certificate_credentials_t RES, const char * CERTFILE, const char * KEYFILE, gnutls_x509_crt_fmt_t TYPE, const char * PASS, unsigned int FLAGS)'

5.3.8 Verifying certificates over PKCS #11
------------------------------------------

The PKCS #11 API 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 Figure 5.1.  That way
applications could load their trusted certificate list, as well as user
certificates from a common PKCS #11 module.  Such a provider is the
p11-kit trust storage module(1) and it provides access to the trusted
Root CA certificates in a system.  That provides a more dynamic list of
Root CA certificates, as opposed to a static list in a file or
directory.

That store, allows for blacklisting of CAs or certificates, as well as
categorization of the Root CAs (Web verification, Code signing, etc.),
in addition to restricting their purpose via stapled extensions(2).
GnuTLS will utilize the p11-kit trust module as the default trust store
if configured to; i.e., if '-with-default-trust-store-pkcs11=pkcs11:' is
given to the configure script.

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

   (1) <https://p11-glue.github.io/p11-glue/trust-module.html>

   (2) See the 'Restricting the scope of CA certificates' post at
<https://nmav.gnutls.org/2016/06/restricting-scope-of-ca-certificates.html>

5.3.9 Invoking p11tool
----------------------

Program that allows operations on PKCS #11 smart cards and security
modules.

To use PKCS #11 tokens with GnuTLS the p11-kit configuration files need
to be setup.  That is create a .module file in /etc/pkcs11/modules with
the contents 'module: /path/to/pkcs11.so'.  Alternatively the
configuration file /etc/gnutls/pkcs11.conf has to exist and contain a
number of lines of the form 'load=/usr/lib/opensc-pkcs11.so'.

You can provide the PIN to be used for the PKCS #11 operations with the
environment variables GNUTLS_PIN and GNUTLS_SO_PIN.

This section was generated by *AutoGen*, using the 'agtexi-cmd' template
and the option descriptions for the 'p11tool' program.  This software is
released under the GNU General Public License, version 3 or later.

p11tool help/usage ('--help')
-----------------------------

This is the automatically generated usage text for p11tool.

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     p11tool - GnuTLS PKCS #11 tool
     Usage:  p11tool [ -<flag> [<val>] | --<name>[{=| }<val>] ]... [url]

     Tokens:

            --list-tokens          List all available tokens
            --list-token-urls      List the URLs available tokens
            --list-mechanisms      List all available mechanisms in a token
            --initialize           Initializes a PKCS #11 token
            --initialize-pin       Initializes/Resets a PKCS #11 token user PIN
            --initialize-so-pin    Initializes/Resets a PKCS #11 token security officer PIN.
            --set-pin=str          Specify the PIN to use on token operations
            --set-so-pin=str       Specify the Security Officer's PIN to use on token initialization

     Object listing:

            --list-all             List all available objects in a token
            --list-all-certs       List all available certificates in a token
            --list-certs           List all certificates that have an associated private key
            --list-all-privkeys    List all available private keys in a token
            --list-privkeys        an alias for the 'list-all-privkeys' option
            --list-keys            an alias for the 'list-all-privkeys' option
            --list-all-trusted     List all available certificates marked as trusted
            --export               Export the object specified by the URL
                                     - prohibits these options:
                                     export-stapled
                                     export-chain
                                     export-pubkey
            --export-stapled       Export the certificate object specified by the URL
                                     - prohibits these options:
                                     export
                                     export-chain
                                     export-pubkey
            --export-chain         Export the certificate specified by the URL and its chain of trust
                                     - prohibits these options:
                                     export-stapled
                                     export
                                     export-pubkey
            --export-pubkey        Export the public key for a private key
                                     - prohibits these options:
                                     export-stapled
                                     export
                                     export-chain
            --info                 List information on an available object in a token
            --trusted              an alias for the 'mark-trusted' option
            --distrusted           an alias for the 'mark-distrusted' option

     Key generation:

            --generate-privkey=str Generate private-public key pair of given type
            --bits=num             Specify the number of bits for the key generate
            --curve=str            Specify the curve used for EC key generation
            --sec-param=str        Specify the security level

     Writing objects:

            --set-id=str           Set the CKA_ID (in hex) for the specified by the URL object
                                     - prohibits the option 'write'
            --set-label=str        Set the CKA_LABEL for the specified by the URL object
                                     - prohibits these options:
                                     write
                                     set-id
            --write                Writes the loaded objects to a PKCS #11 token
            --delete               Deletes the objects matching the given PKCS #11 URL
            --label=str            Sets a label for the write operation
            --id=str               Sets an ID for the write operation
            --mark-wrap            Marks the generated key to be a wrapping key
                                     - disabled as '--no-mark-wrap'
            --mark-trusted         Marks the object to be written as trusted
                                     - prohibits the option 'mark-distrusted'
                                     - disabled as '--no-mark-trusted'
            --mark-distrusted      When retrieving objects, it requires the objects to be distrusted
     (blacklisted)
                                     - prohibits the option 'mark-trusted'
            --mark-decrypt         Marks the object to be written for decryption
                                     - disabled as '--no-mark-decrypt'
            --mark-sign            Marks the object to be written for signature generation
                                     - disabled as '--no-mark-sign'
            --mark-ca              Marks the object to be written as a CA
                                     - disabled as '--no-mark-ca'
            --mark-private         Marks the object to be written as private
                                     - disabled as '--no-mark-private'
            --ca                   an alias for the 'mark-ca' option
            --private              an alias for the 'mark-private' option
            --secret-key=str       Provide a hex encoded secret key
            --load-privkey=file    Private key file to use
                                     - file must pre-exist
            --load-pubkey=file     Public key file to use
                                     - file must pre-exist
            --load-certificate=file Certificate file to use
                                     - file must pre-exist

     Other options:

        -d, --debug=num            Enable debugging
                                     - it must be in the range:
                                       0 to 9999
            --outfile=str          Output file
            --login                Force (user) login to token
                                     - disabled as '--no-login'
            --so-login             Force security officer login to token
                                     - disabled as '--no-so-login'
            --admin-login          an alias for the 'so-login' option
            --test-sign            Tests the signature operation of the provided object
            --sign-params=str      Sign with a specific signature algorithm
            --hash=str             Hash algorithm to use for signing
            --generate-random=num  Generate random data
        -8, --pkcs8                Use PKCS #8 format for private keys
            --inder                Use DER/RAW format for input
                                     - disabled as '--no-inder'
            --inraw                an alias for the 'inder' option
            --outder               Use DER format for output certificates, private keys, and DH parameters
                                     - disabled as '--no-outder'
            --outraw               an alias for the 'outder' option
            --provider=file        Specify the PKCS #11 provider library
            --detailed-url         Print detailed URLs
                                     - disabled as '--no-detailed-url'
            --only-urls            Print a compact listing using only the URLs
            --batch                Disable all interaction with the tool

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.
     Operands and options may be intermixed.  They will be reordered.

     Program that allows operations on PKCS #11 smart cards and security
     modules.

     To use PKCS #11 tokens with GnuTLS the p11-kit configuration files need to
     be setup.  That is create a .module file in /etc/pkcs11/modules with the
     contents 'module: /path/to/pkcs11.so'.  Alternatively the configuration
     file /etc/gnutls/pkcs11.conf has to exist and contain a number of lines of
     the form 'load=/usr/lib/opensc-pkcs11.so'.

     You can provide the PIN to be used for the PKCS #11 operations with the
     environment variables GNUTLS_PIN and GNUTLS_SO_PIN.

token-related-options options
-----------------------------

Tokens.

list-token-urls option.
.......................

This is the "list the urls available tokens" option.  This is a more
compact version of -list-tokens.

initialize-so-pin option.
.........................

This is the "initializes/resets a pkcs #11 token security officer pin."
option.  This initializes the security officer's PIN. When used
non-interactively use the GNUTLS_NEW_SO_PIN environment variables to
initialize SO's PIN.

set-pin option.
...............

This is the "specify the pin to use on token operations" option.  This
option takes a string argument.  Alternatively the GNUTLS_PIN
environment variable may be used.

set-so-pin option.
..................

This is the "specify the security officer's pin to use on token
initialization" option.  This option takes a string argument.
Alternatively the GNUTLS_SO_PIN environment variable may be used.

object-list-related-options options
-----------------------------------

Object listing.

list-all option.
................

This is the "list all available objects in a token" option.  All objects
available in the token will be listed.  That includes objects which are
potentially unaccessible using this tool.

list-all-certs option.
......................

This is the "list all available certificates in a token" option.  That
option will also provide more information on the certificates, for
example, expand the attached extensions in a trust token (like
p11-kit-trust).

list-certs option.
..................

This is the "list all certificates that have an associated private key"
option.  That option will only display certificates which have a private
key associated with them (share the same ID).

list-all-privkeys option.
.........................

This is the "list all available private keys in a token" option.  Lists
all the private keys in a token that match the specified URL.

list-privkeys option.
.....................

This is an alias for the 'list-all-privkeys' option, see the list-all-privkeys option documentation.

list-keys option.
.................

This is an alias for the 'list-all-privkeys' option, see the list-all-privkeys option documentation.

export-stapled option.
......................

This is the "export the certificate object specified by the url" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     export, export-chain, export-pubkey.

Exports the certificate specified by the URL while including any
attached extensions to it.  Since attached extensions are a p11-kit
extension, this option is only available on p11-kit registered trust
modules.

export-chain option.
....................

This is the "export the certificate specified by the url and its chain
of trust" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     export-stapled, export, export-pubkey.

Exports the certificate specified by the URL and generates its chain of
trust based on the stored certificates in the module.

export-pubkey option.
.....................

This is the "export the public key for a private key" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     export-stapled, export, export-chain.

Exports the public key for the specified private key

trusted option.
...............

This is an alias for the 'mark-trusted' option, see the mark-trusted option documentation.

distrusted option.
..................

This is an alias for the 'mark-distrusted' option, see the mark-distrusted option documentation.

keygen-related-options options
------------------------------

Key generation.

generate-privkey option.
........................

This is the "generate private-public key pair of given type" option.
This option takes a string argument.  Generates a private-public key
pair in the specified token.  Acceptable types are RSA, ECDSA, Ed25519,
and DSA. Should be combined with -sec-param or -bits.

generate-rsa option.
....................

This is the "generate an rsa private-public key pair" option.  Generates
an RSA private-public key pair on the specified token.  Should be
combined with -sec-param or -bits.

*NOTE**: THIS OPTION IS DEPRECATED*

generate-dsa option.
....................

This is the "generate a dsa private-public key pair" option.  Generates
a DSA private-public key pair on the specified token.  Should be
combined with -sec-param or -bits.

*NOTE**: THIS OPTION IS DEPRECATED*

generate-ecc option.
....................

This is the "generate an ecdsa private-public key pair" option.
Generates an ECDSA private-public key pair on the specified token.
Should be combined with -curve, -sec-param or -bits.

*NOTE**: THIS OPTION IS DEPRECATED*

bits option.
............

This is the "specify the number of bits for the key generate" option.
This option takes a number argument.  For applications which have no
key-size restrictions the -sec-param option is recommended, as the
sec-param levels will adapt to the acceptable security levels with the
new versions of gnutls.

curve option.
.............

This is the "specify the curve used for ec key generation" option.  This
option takes a string argument.  Supported values are secp192r1,
secp224r1, secp256r1, secp384r1 and secp521r1.

sec-param option.
.................

This is the "specify the security level" option.  This option takes a
string argument 'Security parameter'.  This is alternative to the bits
option.  Available options are [low, legacy, medium, high, ultra].

write-object-related-options options
------------------------------------

Writing objects.

set-id option.
..............

This is the "set the cka_id (in hex) for the specified by the url
object" option.  This option takes a string argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     write.

Modifies or sets the CKA_ID in the specified by the URL object.  The ID
should be specified in hexadecimal format without a '0x' prefix.

set-label option.
.................

This is the "set the cka_label for the specified by the url object"
option.  This option takes a string argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     write, set-id.

Modifies or sets the CKA_LABEL in the specified by the URL object

write option.
.............

This is the "writes the loaded objects to a pkcs #11 token" option.  It
can be used to write private, public keys, certificates or secret keys
to a token.  Must be combined with one of -load-privkey, -load-pubkey,
-load-certificate option.

id option.
..........

This is the "sets an id for the write operation" option.  This option
takes a string argument.  Sets the CKA_ID to be set by the write
operation.  The ID should be specified in hexadecimal format without a
'0x' prefix.

mark-wrap option.
.................

This is the "marks the generated key to be a wrapping key" option.

This option has some usage constraints.  It:
   * can be disabled with -no-mark-wrap.

Marks the generated key with the CKA_WRAP flag.

mark-trusted option.
....................

This is the "marks the object to be written as trusted" option.

This option has some usage constraints.  It:
   * can be disabled with -no-mark-trusted.
   * must not appear in combination with any of the following options:
     mark-distrusted.

Marks the object to be generated/written with the CKA_TRUST flag.

mark-distrusted option.
.......................

This is the "when retrieving objects, it requires the objects to be
distrusted (blacklisted)" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     mark-trusted.

Ensures that the objects retrieved have the CKA_X_TRUST flag.  This is
p11-kit trust module extension, thus this flag is only valid with
p11-kit registered trust modules.

mark-decrypt option.
....................

This is the "marks the object to be written for decryption" option.

This option has some usage constraints.  It:
   * can be disabled with -no-mark-decrypt.

Marks the object to be generated/written with the CKA_DECRYPT flag set
to true.

mark-sign option.
.................

This is the "marks the object to be written for signature generation"
option.

This option has some usage constraints.  It:
   * can be disabled with -no-mark-sign.

Marks the object to be generated/written with the CKA_SIGN flag set to
true.

mark-ca option.
...............

This is the "marks the object to be written as a ca" option.

This option has some usage constraints.  It:
   * can be disabled with -no-mark-ca.

Marks the object to be generated/written with the
CKA_CERTIFICATE_CATEGORY as CA.

mark-private option.
....................

This is the "marks the object to be written as private" option.

This option has some usage constraints.  It:
   * can be disabled with -no-mark-private.

Marks the object to be generated/written with the CKA_PRIVATE flag.  The
written object will require a PIN to be used.

ca option.
..........

This is an alias for the 'mark-ca' option, see the mark-ca option documentation.

private option.
...............

This is an alias for the 'mark-private' option, see the mark-private option documentation.

secret-key option.
..................

This is the "provide a hex encoded secret key" option.  This option
takes a string argument.  This secret key will be written to the module
if -write is specified.

other-options options
---------------------

Other options.

debug option (-d).
..................

This is the "enable debugging" option.  This option takes a number
argument.  Specifies the debug level.

so-login option.
................

This is the "force security officer login to token" option.

This option has some usage constraints.  It:
   * can be disabled with -no-so-login.

Forces login to the token as security officer (admin).

admin-login option.
...................

This is an alias for the 'so-login' option, see the so-login option documentation.

test-sign option.
.................

This is the "tests the signature operation of the provided object"
option.  It can be used to test the correct operation of the signature
operation.  If both a private and a public key are available this
operation will sign and verify the signed data.

sign-params option.
...................

This is the "sign with a specific signature algorithm" option.  This
option takes a string argument.  This option can be combined with
-test-sign, to sign with a specific signature algorithm variant.  The
only option supported is 'RSA-PSS', and should be specified in order to
use RSA-PSS signature on RSA keys.

hash option.
............

This is the "hash algorithm to use for signing" option.  This option
takes a string argument.  This option can be combined with test-sign.
Available hash functions are SHA1, RMD160, SHA256, SHA384, SHA512,
SHA3-224, SHA3-256, SHA3-384, SHA3-512.

generate-random option.
.......................

This is the "generate random data" option.  This option takes a number
argument.  Asks the token to generate a number of bytes of random bytes.

inder option.
.............

This is the "use der/raw format for input" option.

This option has some usage constraints.  It:
   * can be disabled with -no-inder.

Use DER/RAW format for input certificates and private keys.

inraw option.
.............

This is an alias for the 'inder' option, see the inder option documentation.

outder option.
..............

This is the "use der format for output certificates, private keys, and
dh parameters" option.

This option has some usage constraints.  It:
   * can be disabled with -no-outder.

The output will be in DER or RAW format.

outraw option.
..............

This is an alias for the 'outder' option, see the outder option documentation.

provider option.
................

This is the "specify the pkcs #11 provider library" option.  This option
takes a file argument.  This will override the default options in
/etc/gnutls/pkcs11.conf

provider-opts option.
.....................

This is the "specify parameters for the pkcs #11 provider library"
option.  This option takes a string argument.  This is a PKCS#11
internal option used by few modules.  Mainly for testing PKCS#11
modules.

*NOTE**: THIS OPTION IS DEPRECATED*

batch option.
.............

This is the "disable all interaction with the tool" option.  In batch
mode there will be no prompts, all parameters need to be specified on
command line.

p11tool exit status
-------------------

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

p11tool See Also
----------------

certtool (1)

p11tool Examples
----------------

To view all tokens in your system use:
     $ p11tool --list-tokens

To view all objects in a token use:
     $ p11tool --login --list-all "pkcs11:TOKEN-URL"

To store a private key and a certificate in a token run:
     $ p11tool --login --write "pkcs11:URL" --load-privkey key.pem \
               --label "Mykey"
     $ p11tool --login --write "pkcs11:URL" --load-certificate cert.pem \
               --label "Mykey"
Note that some tokens require the same label to be used for the
certificate and its corresponding private key.

To generate an RSA private key inside the token use:
     $ p11tool --login --generate-privkey rsa --bits 1024 --label "MyNewKey" \
               --outfile MyNewKey.pub "pkcs11:TOKEN-URL"
The bits parameter in the above example is explicitly set because some
tokens only support limited choices in the bit length.  The output file
is the corresponding public key.  This key can be used to general a
certificate request with certtool.
     certtool --generate-request --load-privkey "pkcs11:KEY-URL" \
        --load-pubkey MyNewKey.pub --outfile request.pem