This is gnutls.info, produced by makeinfo version 5.2 from gnutls.texi. This manual is last updated 1 January 2014 for version 3.2.21 of GnuTLS. Copyright (C) 2001-2013 Free Software Foundation, Inc.\\ Copyright (C) 2001-2013 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". INFO-DIR-SECTION Software libraries START-INFO-DIR-ENTRY * GnuTLS: (gnutls). GNU Transport Layer Security Library. END-INFO-DIR-ENTRY INFO-DIR-SECTION System Administration START-INFO-DIR-ENTRY * certtool: (gnutls)Invoking certtool. Manipulate certificates and keys. * gnutls-serv: (gnutls)Invoking gnutls-serv. GnuTLS test server. * gnutls-cli: (gnutls)Invoking gnutls-cli. GnuTLS test client. * gnutls-cli-debug: (gnutls)Invoking gnutls-cli-debug. GnuTLS debug client. * psktool: (gnutls)Invoking psktool. Simple TLS-Pre-Shared-Keys manager. * srptool: (gnutls)Invoking srptool. Simple SRP password tool. END-INFO-DIR-ENTRY  File: gnutls.info, Node: Top, Next: Preface, Up: (dir) GnuTLS ****** This manual is last updated 1 January 2014 for version 3.2.21 of GnuTLS. Copyright (C) 2001-2013 Free Software Foundation, Inc.\\ Copyright (C) 2001-2013 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". * Menu: * Preface:: * Introduction to GnuTLS:: * Introduction to TLS:: * Authentication methods:: * Hardware security modules and abstract key types:: * How to use GnuTLS in applications:: * GnuTLS application examples:: * Using GnuTLS as a cryptographic library:: * Other included programs:: * Internal architecture of GnuTLS:: * Upgrading from previous versions:: * Support:: * Error codes:: * Supported ciphersuites:: * API reference:: * Copying Information:: * Bibliography:: * Function and Data Index:: * Concept Index::  File: gnutls.info, Node: Preface, Next: Introduction to GnuTLS, Prev: Top, Up: Top 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 [_STEVENS_], to public key infrastructure in [_GUTPKI_] and to security engineering in [_ANDERSON_]. Updated versions of the GnuTLS software and this document will be available from .  File: gnutls.info, Node: Introduction to GnuTLS, Next: Introduction to TLS, Prev: Preface, Up: Top 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.2 (see *note 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.2, TLS 1.1, TLS 1.0 and SSL 3.0 protocols. * Support for Datagram TLS 1.0 and 1.2. * Support for handling and verification of X.509 and OpenPGP 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. * Menu: * Downloading and installing:: * Document overview::  File: gnutls.info, Node: Downloading and installing, Next: Document overview, Up: Introduction to GnuTLS 2.1 Downloading and installing ============================== GnuTLS is available for download at: 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 , while 'gmplib' is available from . 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 . The compression library, 'libz', the PKCS #11 helper library 'p11-kit', as well as the TPM library 'trousers', are optional dependencies. You may get libz from , p11-kit from and trousers from . 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-openpgp-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'.  File: gnutls.info, Node: Document overview, Prev: Downloading and installing, Up: Introduction to GnuTLS 2.2 Overview ============ In this document we present an overview of the supported security protocols in *note Introduction to TLS::, and continue by providing more information on the certificate authentication in *note Certificate authentication::, and shared-key as well anonymous authentication in *note Shared-key and anonymous authentication::. We elaborate on certificate authentication by demonstrating advanced usage of the API in *note More on certificate authentication::. The core of the TLS library is presented in *note How to use GnuTLS in applications:: and example applications are listed in *note GnuTLS application examples::. In *note Other included programs:: the usage of few included programs that may assist debugging is presented. The last chapter is *note Internal architecture of GnuTLS:: that provides a short introduction to GnuTLS' internal architecture.  File: gnutls.info, Node: Introduction to TLS, Next: Authentication methods, Prev: Introduction to GnuTLS, Up: Top 3 Introduction to TLS and DTLS ****************************** TLS stands for "Transport Layer Security" and is the successor of SSL, the Secure Sockets Layer protocol [_SSL3_] designed by Netscape. TLS is an Internet protocol, defined by IETF(1), described in [_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" [_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. * Menu: * TLS layers:: * The transport layer:: * The TLS record protocol:: * The TLS Alert Protocol:: * The TLS Handshake Protocol:: * TLS Extensions:: * How to use TLS in application protocols:: * On SSL 2 and older protocols:: ---------- Footnotes ---------- (1) IETF, or Internet Engineering Task Force, is a large open international community of network designers, operators, vendors, and researchers concerned with the evolution of the Internet architecture and the smooth operation of the Internet. It is open to any interested individual.  File: gnutls.info, Node: TLS layers, Next: The transport layer, Up: Introduction to TLS 3.1 TLS layers ============== TLS is a layered protocol, and consists of the record protocol, the handshake protocol and the alert protocol. The record protocol is to serve all other protocols and is above the transport layer. The record protocol offers symmetric encryption, data authenticity, and optionally compression. The alert protocol offers some signaling to the other protocols. It can help informing the peer for the cause of failures and other error conditions. *Note The Alert Protocol::, for more information. The alert protocol is above the record protocol. The handshake protocol is responsible for the security parameters' negotiation, the initial key exchange and authentication. *Note The Handshake Protocol::, for more information about the handshake protocol. The protocol layering in TLS is shown in *note Figure 3.1: fig-tls-layers. [image src="gnutls-layers.png"] Figure 3.1: The TLS protocol layers.  File: gnutls.info, Node: The transport layer, Next: The TLS record protocol, Prev: TLS layers, Up: Introduction to TLS 3.2 The transport layer ======================= TLS is not limited to 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 *note Setting up the transport layer::).  File: gnutls.info, Node: The TLS record protocol, Next: The TLS Alert Protocol, Prev: The transport layer, Up: Introduction to TLS 3.3 The TLS record protocol =========================== The record protocol is the secure communications provider. Its purpose is to encrypt, authenticate and --optionally-- compress packets. The 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. * Menu: * Encryption algorithms used in the record layer:: * Compression algorithms used in the record layer:: * Weaknesses and countermeasures:: * On Record Padding::  File: gnutls.info, Node: Encryption algorithms used in the record layer, Next: Compression algorithms used in the record layer, Up: The TLS record protocol 3.3.1 Encryption algorithms used in the record layer ---------------------------------------------------- Confidentiality in the record layer is achieved by using symmetric block encryption algorithms like '3DES', 'AES' or stream algorithms like 'ARCFOUR_128'. Ciphers are encryption algorithms that use a single, secret, key to encrypt and decrypt data. Block algorithms in CBC mode also provide protection against statistical analysis of the data. Thus, if you're using the TLS protocol, a random number of blocks will be appended to data, to prevent eavesdroppers from guessing the actual data size. The supported in GnuTLS ciphers and MAC algorithms are shown in *note Table 3.1: tab:ciphers. and *note Table 3.2: tab:macs. Algorithm Description ------------------------------------------------------------------ 3DES_CBC This is the DES block cipher algorithm used with triple encryption (EDE). Has 64 bits block size and is used in CBC mode. ARCFOUR_128 ARCFOUR_128 is a compatible algorithm with RSA's RC4 algorithm, which is considered to be a trade secret. It is a fast cipher but considered weak today. AES_CBC AES or RIJNDAEL is the block cipher algorithm that replaces the old DES algorithm. Has 128 bits block size and is used in CBC mode. AES_GCM This is the AES algorithm in the authenticated encryption GCM mode. This mode combines message authentication and encryption and can be extremely fast on CPUs that support hardware acceleration. CAMELLIA_CBC This is an 128-bit block cipher developed by Mitsubishi and NTT. It is one of the approved ciphers of the European NESSIE and Japanese CRYPTREC projects. SALSA20_256 SALSA20_256 is a fast stream cipher. This is currently a GnuTLS extension. ESTREAM_SALSA20_256ESTREAM_SALSA20_256 is a faster variant of SALSA20, and is one of the selected ciphers of the ESTREAM competition. This is currently a GnuTLS extension. Table 3.1: Supported ciphers. 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 SHA256. Outputs 256 bits of data. MAC_UMAC This is a very fast MAC algorithm based on universal hashing, described in [_RFC4418_]. This is currently a GnuTLS extension. MAC_AEAD This indicates that an authenticated encryption algorithm, such as GCM, is in use. Table 3.2: Supported MAC algorithms.  File: gnutls.info, Node: Compression algorithms used in the record layer, Next: Weaknesses and countermeasures, Prev: Encryption algorithms used in the record layer, Up: The TLS record protocol 3.3.2 Compression algorithms used in the record layer ----------------------------------------------------- The TLS record layer also supports compression. The algorithms implemented in GnuTLS can be found in the table below. The included algorithms perform really good when text, or other compressible data are to be transferred, but offer nothing on already compressed data, such as compressed images, zipped archives etc. These compression algorithms, may be useful in high bandwidth TLS tunnels, and in cases where network usage has to be minimized. It should be noted however that compression increases latency. The record layer compression in GnuTLS is implemented based on [_RFC3749_]. The supported algorithms are shown below. 'GNUTLS_COMP_UNKNOWN' Unknown compression method. 'GNUTLS_COMP_NULL' The NULL compression method (no compression). 'GNUTLS_COMP_DEFLATE' The DEFLATE compression method from zlib. 'GNUTLS_COMP_ZLIB' Same as 'GNUTLS_COMP_DEFLATE' . Figure 3.2: Supported compression algorithms Note that compression enables attacks such as traffic analysis, or even plaintext recovery under certain circumstances. To avoid some of these attacks GnuTLS allows each record to be compressed independently (i.e., stateless compression), by using the "%STATELESS_COMPRESSION" priority string, in order to be used in cases where the attacker controlled data are pt in separate records.  File: gnutls.info, Node: Weaknesses and countermeasures, Next: On Record Padding, Prev: Compression algorithms used in the record layer, Up: The TLS record protocol 3.3.3 Weaknesses and countermeasures ------------------------------------ Some weaknesses that may affect the security of the record layer have been found in TLS 1.0 protocol. These weaknesses can be exploited by active attackers, and exploit the facts that 1. TLS has separate alerts for "decryption_failed" and "bad_record_mac" 2. The decryption failure reason can be detected by timing the response time. 3. The IV for CBC encrypted packets is the last block of the previous encrypted packet. Those weaknesses were solved in TLS 1.1 [_RFC4346_] which is implemented in GnuTLS. For this reason we suggest to always negotiate the highest supported TLS version with the peer(1). For a detailed discussion of the issues see the archives of the TLS Working Group mailing list and [_CBCATT_]. ---------- Footnotes ---------- (1) If this is not possible then please consult *note Interoperability::.  File: gnutls.info, Node: On Record Padding, Prev: Weaknesses and countermeasures, Up: The TLS record protocol 3.3.4 On record padding ----------------------- The TLS protocol allows for extra padding of records in CBC ciphers, to prevent statistical analysis based on the length of exchanged messages (see [_RFC5246_] section 6.2.3.2). GnuTLS appears to be one of few implementations that take advantage of this feature: the user can provide some plaintext data with a range of lengths she wishes to hide, and GnuTLS adds extra padding to make sure the attacker cannot tell the real plaintext length is in a range smaller than the user-provided one. Use *note gnutls_record_send_range:: to send length-hidden messages and *note gnutls_record_can_use_length_hiding:: to check whether the current session supports length hiding. Using the standard *note gnutls_record_send:: will only add minimal padding. The TLS implementation in the Symbian operating system, frequently used by Nokia and Sony-Ericsson mobile phones, cannot handle non-minimal record padding. What happens when one of these clients handshake with a GnuTLS server is that the client will fail to compute the correct MAC for the record. The client sends a TLS alert ('bad_record_mac') and disconnects. Typically this will result in error messages such as 'A TLS fatal alert has been received', 'Bad record MAC', or both, on the GnuTLS server side. If compatibility with such devices is a concern, not sending length-hidden messages solves the problem by using minimal padding. If you implement an application that has a configuration file, we recommend that you make it possible for users or administrators to specify a GnuTLS protocol priority string, which is used by your application via *note gnutls_priority_set::. To allow the best flexibility, make it possible to have a different priority string for different incoming IP addresses.  File: gnutls.info, Node: The TLS Alert Protocol, Next: The TLS Handshake Protocol, Prev: The TLS record protocol, Up: Introduction to TLS 3.4 The TLS alert protocol ========================== The alert protocol is there to allow signals to be sent between peers. These signals are mostly used to inform the peer about the cause of a protocol failure. Some of these signals are used internally by the protocol and the application protocol does not have to cope with them (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. Fatal alerts always terminate the current connection, and prevent future re-negotiations using the current session ID. All 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_USER_CANCELED 90 User canceled GNUTLS_A_NO_RENEGOTIATION 100 No renegotiation is allowed 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_NO_APPLICATION_PROTOCOL 120 No supported application protocol could be negotiated  File: gnutls.info, Node: The TLS Handshake Protocol, Next: TLS Extensions, Prev: The TLS Alert Protocol, Up: Introduction to TLS 3.5 The TLS handshake protocol ============================== The handshake protocol is responsible for the ciphersuite negotiation, the initial key exchange, and the authentication of the two peers. This is fully controlled by the application layer, thus your program has to set up the required parameters. The main handshake function is *note gnutls_handshake::. In the next paragraphs we elaborate on the handshake protocol, i.e., the ciphersuite negotiation. * Menu: * TLS Cipher Suites:: TLS session parameters. * Authentication:: TLS authentication. * Client Authentication:: Requesting a certificate from the client. * Resuming Sessions:: Reusing previously established keys.  File: gnutls.info, Node: TLS Cipher Suites, Next: Authentication, Up: The TLS Handshake Protocol 3.5.1 TLS ciphersuites ---------------------- The handshake protocol of TLS 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 *note ciphersuites::. ---------- Footnotes ---------- (1) MAC stands for Message Authentication Code. It can be described as a keyed hash algorithm. See RFC2104.  File: gnutls.info, Node: Authentication, Next: Client Authentication, Prev: TLS Cipher Suites, Up: The TLS Handshake Protocol 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 follow. * Certificate authentication: Authenticated key exchange using public key infrastructure and certificates (X.509 or OpenPGP). * SRP authentication: Authenticated key exchange using a password. * PSK authentication: Authenticated key exchange using a pre-shared key. * Anonymous authentication: Key exchange without peer authentication.  File: gnutls.info, Node: Client Authentication, Next: Resuming Sessions, Prev: Authentication, Up: The TLS Handshake Protocol 3.5.3 Client authentication --------------------------- In the case of ciphersuites that use certificate authentication, the authentication of the client is optional in TLS. A server may request a certificate from the client using the *note gnutls_certificate_server_set_request:: function. We elaborate in *note Certificate credentials::.  File: gnutls.info, Node: Resuming Sessions, Prev: Client Authentication, Up: The TLS Handshake Protocol 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 - *note Session tickets::). Session resumption is an integral part of GnuTLS, and *note Session resumption::, *note ex-resume-client:: illustrate typical uses of it.  File: gnutls.info, Node: TLS Extensions, Next: How to use TLS in application protocols, Prev: The TLS Handshake Protocol, Up: Introduction to TLS 3.6 TLS extensions ================== A number of extensions to the TLS protocol have been proposed mainly in [_TLSEXT_]. The extensions supported in GnuTLS are: * Maximum fragment length negotiation * Server name indication * Session tickets * HeartBeat * Safe Renegotiation and they will be discussed in the subsections that follow. * Menu: * Maximum fragment length negotiation:: * Server name indication:: * Session tickets:: * HeartBeat:: * Safe renegotiation:: * OCSP status request:: * SRTP:: * Application Layer Protocol Negotiation (ALPN)::  File: gnutls.info, Node: Maximum fragment length negotiation, Next: Server name indication, Up: TLS Extensions 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 *note gnutls_record_get_max_size:: (gnutls_session_t SESSION)' 'SSIZE_T *note gnutls_record_set_max_size:: (gnutls_session_t SESSION, size_t SIZE)'  File: gnutls.info, Node: Server name indication, Next: Session tickets, Prev: Maximum fragment length negotiation, Up: TLS Extensions 3.6.2 Server name indication ---------------------------- A common problem in HTTPS servers is the fact that the TLS protocol is not aware of the hostname that a client connects to, when the handshake procedure begins. For that reason the TLS server has no way to know which certificate to send. This extension solves that problem within the TLS protocol, and allows a client to send the HTTP hostname before the handshake begins within the first handshake packet. The functions *note gnutls_server_name_set:: and *note gnutls_server_name_get:: can be used to enable this extension, or to retrieve the name sent by a client. 'INT *note gnutls_server_name_set:: (gnutls_session_t SESSION, gnutls_server_name_type_t TYPE, const void * NAME, size_t NAME_LENGTH)' 'INT *note gnutls_server_name_get:: (gnutls_session_t SESSION, void * DATA, size_t * DATA_LENGTH, unsigned int * TYPE, unsigned int INDX)'  File: gnutls.info, Node: Session tickets, Next: HeartBeat, Prev: Server name indication, Up: TLS Extensions 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 [_TLSTKT_]. Since version 3.1.3 GnuTLS clients transparently support session tickets.  File: gnutls.info, Node: HeartBeat, Next: Safe renegotiation, Prev: Session tickets, Up: TLS Extensions 3.6.4 HeartBeat --------------- This is a TLS extension that allows to ping and receive confirmation from the peer, and is described in [_RFC6520_]. The extension is disabled by default and *note 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 *note gnutls_heartbeat_allowed::. The requests coming from the peer result to 'GNUTLS_E_HERTBEAT_PING_RECEIVED' being returned from the receive function. Ping requests to peer can be send via *note gnutls_heartbeat_ping::. 'INT *note gnutls_heartbeat_allowed:: (gnutls_session_t SESSION, unsigned int TYPE)' 'VOID *note gnutls_heartbeat_enable:: (gnutls_session_t SESSION, unsigned int TYPE)' 'INT *note gnutls_heartbeat_ping:: (gnutls_session_t SESSION, size_t DATA_SIZE, unsigned int MAX_TRIES, unsigned int FLAGS)' 'INT *note gnutls_heartbeat_pong:: (gnutls_session_t SESSION, unsigned int FLAGS)' 'VOID *note gnutls_heartbeat_set_timeouts:: (gnutls_session_t SESSION, unsigned int RETRANS_TIMEOUT, unsigned int TOTAL_TIMEOUT)' 'UNSIGNED INT *note gnutls_heartbeat_get_timeout:: (gnutls_session_t SESSION)'  File: gnutls.info, Node: Safe renegotiation, Next: OCSP status request, Prev: HeartBeat, Up: TLS Extensions 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 [_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 *note 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 *note gnutls_safe_renegotiation_status:: function is used to check if the extension has been negotiated on a session, and can be used both by clients and servers.  File: gnutls.info, Node: OCSP status request, Next: SRTP, Prev: Safe renegotiation, Up: TLS Extensions 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 *note 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. 'VOID *note gnutls_certificate_set_ocsp_status_request_function:: (gnutls_certificate_credentials_t SC, gnutls_status_request_ocsp_func OCSP_FUNC, void * PTR)' 'INT *note gnutls_certificate_set_ocsp_status_request_file:: (gnutls_certificate_credentials_t SC, const char * RESPONSE_FILE, unsigned int FLAGS)' 'INT *note gnutls_ocsp_status_request_enable_client:: (gnutls_session_t SESSION, gnutls_datum_t * RESPONDER_ID, size_t RESPONDER_ID_SIZE, gnutls_datum_t * EXTENSIONS)' 'INT *note gnutls_ocsp_status_request_is_checked:: (gnutls_session_t SESSION, unsigned int FLAGS)' A server is required to provide the OCSP server's response using the *note gnutls_certificate_set_ocsp_status_request_file::. The response may be obtained periodically using the following command. ocsptool --ask --load-cert server_cert.pem --load-issuer the_issuer.pem --load-signer the_issuer.pem --outfile ocsp.response Since version 3.1.3 GnuTLS clients transparently support the certificate status request.  File: gnutls.info, Node: SRTP, Next: Application Layer Protocol Negotiation (ALPN), Prev: OCSP status request, Up: TLS Extensions 3.6.7 SRTP ---------- The TLS protocol was extended in [_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.3: Supported SRTP profiles To enable use the following functions. 'INT *note gnutls_srtp_set_profile:: (gnutls_session_t SESSION, gnutls_srtp_profile_t PROFILE)' 'INT *note 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' structure. 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 *note gnutls_srtp_get_selected_profile:: (gnutls_session_t SESSION, gnutls_srtp_profile_t * PROFILE)' 'CONST CHAR * *note gnutls_srtp_get_profile_name:: (gnutls_srtp_profile_t PROFILE)' 'INT *note gnutls_srtp_get_profile_id:: (const char * NAME, gnutls_srtp_profile_t * PROFILE)'  File: gnutls.info, Node: Application Layer Protocol Negotiation (ALPN), Prev: SRTP, Up: TLS Extensions 3.6.8 Application Layer Protocol Negotiation (ALPN) --------------------------------------------------- The TLS protocol was extended in 'draft-ietf-tls-applayerprotoneg-00' 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 *note gnutls_alpn_set_protocols:: (gnutls_session_t SESSION, const gnutls_datum_t * PROTOCOLS, unsigned PROTOCOLS_SIZE, unsigned int FLAGS)' 'INT *note gnutls_alpn_get_selected_protocol:: (gnutls_session_t SESSION, gnutls_datum_t * PROTOCOL)' Note that you can use these functions with protocols that are registered in the Application Layer Protocol Negotiation IANA registry. If you wish to use them for other custom protocols then prefix them with the 3 characters 'exp' (lower-case).  File: gnutls.info, Node: How to use TLS in application protocols, Next: On SSL 2 and older protocols, Prev: TLS Extensions, Up: Introduction to TLS 3.7 How to use TLS in application protocols =========================================== This chapter is intended to provide some hints on how to use the TLS over simple custom made application protocols. The discussion below mainly refers to the TCP/IP transport layer but may be extended to other ones too. * Menu: * Separate ports:: * Upward negotiation::  File: gnutls.info, Node: Separate ports, Next: Upward negotiation, Up: How to use TLS in application protocols 3.7.1 Separate ports -------------------- Traditionally SSL was used in application protocols by assigning a new port number for the secure services. That way two separate ports were assigned, one for the non secure sessions, and one for the secured ones. This has the benefit that if a user requests a secure session then the client will try to connect to the secure port and fail otherwise. The only possible attack with this method is a denial of service one. The most famous example of this method is the famous "HTTP over TLS" or HTTPS protocol [_RFC2818_]. Despite its wide use, this method is not as good as it seems. This approach starts the TLS Handshake procedure just after the client connects on the --so called-- secure port. That way the TLS protocol does not know anything about the client, and popular methods like the host advertising in HTTP do not work(1). There is no way for the client to say "I connected to YYY server" before the Handshake starts, so the server cannot possibly know which certificate to use. Other than that it requires two separate ports to run a single service, which is unnecessary complication. Due to the fact that there is a limitation on the available privileged ports, this approach was soon obsoleted. ---------- Footnotes ---------- (1) See also the Server Name Indication extension on *note serverind::.  File: gnutls.info, Node: Upward negotiation, Prev: Separate ports, Up: How to use TLS in application protocols 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 that method [_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 see an example of a conversation where someone is acting in between: (client connects to the server) CLIENT: HELLO I'M MR. XXX SERVER: NICE TO MEET YOU XXX CLIENT: PLEASE START TLS (here someone inserts this message) SERVER: SORRY I DON'T HAVE THIS CAPABILITY CLIENT: HERE ARE SOME CONFIDENTIAL DATA As you can see above the client was fooled, and was dummy enough to send the confidential data in the clear. How to avoid the above attack? As you may have already noticed this one is easy to avoid. The client has to ask the user before it connects whether the user requests TLS or not. If the user answered that he certainly wants the secure layer the last conversation should be: (client connects to the server) CLIENT: HELLO I'M MR. XXX SERVER: NICE TO MEET YOU XXX CLIENT: PLEASE START TLS (here someone inserts this message) SERVER: SORRY I DON'T HAVE THIS CAPABILITY CLIENT: BYE (the client notifies the user that the secure connection was not possible) This method, if implemented properly, is far better than the traditional method, and the security properties remain the same, since only denial of service is possible. The benefit is that the server may request additional data before the TLS Handshake protocol starts, in order to send the correct certificate, use the correct password file, or anything else! ---------- Footnotes ---------- (1) See LDAP, IMAP etc.  File: gnutls.info, Node: On SSL 2 and older protocols, Prev: How to use TLS in application protocols, Up: Introduction to TLS 3.8 On SSL 2 and older protocols ================================ One of the initial decisions in the GnuTLS development was to implement the known security protocols for the transport layer. Initially TLS 1.0 was implemented since it was the latest at that time, and was considered to be the most advanced in security properties. Later the SSL 3.0 protocol was implemented since it is still the only protocol supported by several servers and there are no serious security vulnerabilities known. One question that may arise is why we didn't implement SSL 2.0 in the library. There are several reasons, most important being that it has serious security flaws, unacceptable for a modern security library. Other than that, this protocol is barely used by anyone these days since it has been deprecated since 1996. The security problems in SSL 2.0 include: * Message integrity compromised. The SSLv2 message authentication uses the MD5 function, and is insecure. * Man-in-the-middle attack. There is no protection of the handshake in SSLv2, which permits a man-in-the-middle attack. * Truncation attack. SSLv2 relies on TCP FIN to close the session, so the attacker can forge a TCP FIN, and the peer cannot tell if it was a legitimate end of data or not. * Weak message integrity for export ciphers. The cryptographic keys in SSLv2 are used for both message authentication and encryption, so if weak encryption schemes are negotiated (say 40-bit keys) the message authentication code 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.  File: gnutls.info, Node: Authentication methods, Next: Hardware security modules and abstract key types, Prev: Introduction to TLS, Up: Top 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. * Menu: * Certificate authentication:: * More on certificate authentication:: * Shared-key and anonymous authentication:: * Selecting an appropriate authentication method::  File: gnutls.info, Node: Certificate authentication, Next: More on certificate authentication, Up: Authentication methods 4.1 Certificate authentication ============================== The most known authentication method of TLS are certificates. The PKIX [_PKIX_] public key infrastructure is daily used by anyone using a browser today. GnuTLS supports both X.509 certificates [_PKIX_] and OpenPGP certificates using a common API. The key exchange algorithms supported by certificate authentication are shown in *note Table 4.1: tab:key-exchange. 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. * Menu: * X.509 certificates:: * OpenPGP certificates:: * Advanced certificate verification:: * Digital signatures::  File: gnutls.info, Node: X.509 certificates, Next: OpenPGP certificates, Up: Certificate authentication 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. [image src="gnutls-x509.png"] 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 *note Figure 4.1: fig-x509. * Menu: * X.509 certificate structure:: * Importing an X.509 certificate:: * X.509 distinguished names:: * X.509 public and private keys:: * Verifying X.509 certificate paths:: * Verifying a certificate in the context of TLS session::  File: gnutls.info, Node: X.509 certificate structure, Next: Importing an X.509 certificate, Up: X.509 certificates 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 [_PKIX_] as shown in *note Table 4.2: tab:x509. 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. Certificate _extensions_ are there to include information about the certificate's subject that did not fit in the typical certificate fields. Those may be e-mail addresses, flags that indicate whether the belongs to a CA etc. All the supported X.509 version 3 extensions are shown in *note Table 4.3: tab:x509-ext. Extension OID Description -------------------------------------------------------------------- Subject key id 2.5.29.14 An identifier of the key of the subject. Authority key id 2.5.29.35 An identifier of the authority's key used to sign the certificate. Subject alternative 2.5.29.17 Alternative names to name subject's distinguished name. Key usage 2.5.29.15 Constraints the key's usage of the certificate. Extended key usage 2.5.29.37 Constraints the purpose of the certificate. Basic constraints 2.5.29.19 Indicates whether this is a CA certificate or not, and specify the maximum path lengths of certificate chains. CRL distribution 2.5.29.31 This extension is set by points the CA, in order to inform about the issued CRLs. 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. 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 [_RFC3820_]. Table 4.3: X.509 certificate extensions. 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 *note ex-x509-info::.  File: gnutls.info, Node: Importing an X.509 certificate, Next: X.509 distinguished names, Prev: X.509 certificate structure, Up: X.509 certificates 4.1.1.2 Importing an X.509 certificate ...................................... The certificate structure should be initialized using *note gnutls_x509_crt_init::, and a certificate structure can be imported using *note gnutls_x509_crt_import::. 'INT *note gnutls_x509_crt_init:: (gnutls_x509_crt_t * CERT)' 'INT *note gnutls_x509_crt_import:: (gnutls_x509_crt_t CERT, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)' 'VOID *note 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 *note 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 *note 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 *note 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'.  File: gnutls.info, Node: X.509 distinguished names, Next: X.509 public and private keys, Prev: Importing an X.509 certificate, Up: X.509 certificates 4.1.1.3 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 *note gnutls_x509_crt_get_dn2:: which follows the rules in [_RFC4514_] and returns a single string. Access to each string by individual object identifiers can be accessed using *note 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' structure DN: a pointer to a structure to hold the name 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. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. and a negative error code on error. *Since:* 3.1.10 'INT *note gnutls_x509_crt_get_dn:: (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)' 'INT *note gnutls_x509_crt_get_dn_by_oid:: (gnutls_x509_crt_t CERT, const char * OID, int INDX, unsigned int RAW_FLAG, void * BUF, size_t * BUF_SIZE)' 'INT *note gnutls_x509_crt_get_dn_oid:: (gnutls_x509_crt_t CERT, int INDX, void * OID, size_t * OID_SIZE)' Similar functions exist to access the distinguished name of the issuer of the certificate. 'INT *note gnutls_x509_crt_get_issuer_dn:: (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)' 'INT *note gnutls_x509_crt_get_issuer_dn2:: (gnutls_x509_crt_t CERT, gnutls_datum_t * DN)' 'INT *note gnutls_x509_crt_get_issuer_dn_by_oid:: (gnutls_x509_crt_t CERT, const char * OID, int INDX, unsigned int RAW_FLAG, void * BUF, size_t * BUF_SIZE)' 'INT *note gnutls_x509_crt_get_issuer_dn_oid:: (gnutls_x509_crt_t CERT, int INDX, void * OID, size_t * OID_SIZE)' 'INT *note gnutls_x509_crt_get_issuer:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)' The more powerful *note gnutls_x509_crt_get_subject:: and *note gnutls_x509_dn_get_rdn_ava:: provide efficient but low-level access to the contents of the distinguished name structure. 'INT *note gnutls_x509_crt_get_subject:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)' 'INT *note 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.  File: gnutls.info, Node: X.509 public and private keys, Next: Verifying X.509 certificate paths, Prev: X.509 distinguished names, Up: X.509 certificates 4.1.1.4 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 *note 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 *note 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 0 for now OUTPUT_DATA: will contain the key ID OUTPUT_DATA_SIZE: holds the size of output_data (and will be replaced by the actual size of parameters) This function will return a unique ID 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 *note gnutls_x509_privkey_get_pk_algorithm2:: (gnutls_x509_privkey_t KEY, unsigned int * BITS)' 'INT *note 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 *note 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 *note 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 *note gnutls_x509_privkey_get_key_id:: (gnutls_x509_privkey_t KEY, unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'  File: gnutls.info, Node: Verifying X.509 certificate paths, Next: Verifying a certificate in the context of TLS session, Prev: X.509 public and private keys, Up: X.509 certificates 4.1.1.5 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, int CLIST_SIZE, unsigned int FLAGS) LIST: The structure of the list CLIST: A list of CAs CLIST_SIZE: The length of the CA list FLAGS: should be 0. This function will add the given certificate authorities to the trusted list. The list of CAs must not be deinitialized during this structure's lifetime. *Returns:* The number of added elements is returned. *Since:* 3.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 structure of 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 only with 'gnutls_x509_trust_list_verify_named_crt()' . 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 must not be deinitialized during the lifetime of the trusted list. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.0 -- Function: int gnutls_x509_trust_list_add_crls (gnutls_x509_trust_list_t LIST, const gnutls_x509_crl_t * CRL_LIST, int CRL_SIZE, unsigned int FLAGS, unsigned int VERIFICATION_FLAGS) LIST: The structure of the list CRL_LIST: A list of CRLs CRL_SIZE: The length of the CRL list FLAGS: if GNUTLS_TL_VERIFY_CRL is given the CRLs will be verified before being added. 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 list of CRLs must not be deinitialized during this structure's lifetime. This function must be called after 'gnutls_x509_trust_list_add_cas()' to allow verifying the CRLs for validity. *Returns:* The number of added elements is returned. *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 * VERIFY, gnutls_verify_output_function FUNC) LIST: The structure of 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. VERIFY: 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 'verify' parameter will hold an OR'ed sequence of 'gnutls_certificate_status_t' flags. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.0 -- 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 * VERIFY, gnutls_verify_output_function FUNC) LIST: The structure of 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. VERIFY: 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 'verify' parameter will hold an OR'ed sequence of 'gnutls_certificate_status_t' flags. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.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 structure of 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: GNUTLS_TL_* 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. pkcs11 URLs are also accepted, instead of files, by this function. *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 structure of 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: GNUTLS_TL_* 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. *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 system this function returns 'GNUTLS_E_UNIMPLEMENTED_FEATURE' . *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 *note Figure 4.2: gnutls_certificate_status_t. 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) Figure 4.2: The 'gnutls_certificate_status_t' enumeration. An example of certificate verification is shown in *note 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 *note gnutls_x509_trust_list_add_named_crt:: and *note gnutls_x509_trust_list_verify_named_crt::.  File: gnutls.info, Node: Verifying a certificate in the context of TLS session, Prev: Verifying X.509 certificate paths, Up: X.509 certificates 4.1.1.6 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 *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)' 'INT *note gnutls_certificate_set_x509_crl_file:: (gnutls_certificate_credentials_t RES, const char * CRLFILE, gnutls_x509_crt_fmt_t TYPE)' 'INT *note gnutls_certificate_set_x509_system_trust:: (gnutls_certificate_credentials_t CRED)' Then it is not required to setup a trusted list as above. The function *note gnutls_certificate_verify_peers3:: may then be used to verify the peer's certificate chain and identity. The flags are set similarly to the verification functions in the previous section. There is also the possibility to pass some input to the verification functions in the form of flags. For *note gnutls_x509_trust_list_verify_crt:: the flags are passed straightforward, but *note gnutls_certificate_verify_peers3:: depends on the flags set by calling *note gnutls_certificate_set_verify_flags::. All the available flags are part of the enumeration 'gnutls_certificate_verify_flags' shown in *note Figure 4.3: gnutls_certificate_verify_flags. '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_ALLOW_X509_V1_CA_CRT' Allow trusted CA certificates with version 1. This is safer than 'GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT' , and should be used instead. That way only signers in your trusted list will be allowed to have certificates of version 1. This is the default. '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. Must be used in combination with 'GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT' . '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. Figure 4.3: The 'gnutls_certificate_verify_flags' enumeration.  File: gnutls.info, Node: OpenPGP certificates, Next: Advanced certificate verification, Prev: X.509 certificates, Up: Certificate authentication 4.1.2 OpenPGP certificates -------------------------- The OpenPGP key authentication relies on a distributed trust model, called the "web of trust". The "web of trust" uses a decentralized system of trusted introducers, which are the same as a CA. OpenPGP allows anyone to sign anyone else's public key. When Alice signs Bob's key, she is introducing Bob's key to anyone who trusts Alice. If someone trusts Alice to introduce keys, then Alice is a trusted introducer in the mind of that observer. For example in *note Figure 4.4: fig-openpgp, David trusts Alice to be an introducer and Alice signed Bob's key thus Dave trusts Bob's key to be the real one. [image src="gnutls-pgp.png"] Figure 4.4: An example of the OpenPGP trust model. There are some key points that are important in that model. In the example Alice has to sign Bob's key, only if she is sure that the key belongs to Bob. Otherwise she may also make Dave falsely believe that this is Bob's key. Dave has also the responsibility to know who to trust. This model is similar to real life relations. Just see how Charlie behaves in the previous example. Although he has signed Bob's key - because he knows, somehow, that it belongs to Bob - he does not trust Bob to be an introducer. Charlie decided to trust only Kevin, for some reason. A reason could be that Bob is lazy enough, and signs other people's keys without being sure that they belong to the actual owner. Field Description ------------------------------------------------------------------ version The field that indicates the version of the OpenPGP structure. user ID An RFC 2822 string that identifies the owner of the key. There may be multiple user identifiers in a key. public key The main public key of the certificate. expiration The expiration time of the main public key. public An additional public key of the certificate. subkey There may be multiple subkeys in a certificate. public The expiration time of the subkey. subkey expiration Table 4.4: OpenPGP certificate fields. 4.1.2.1 OpenPGP certificate structure ..................................... In GnuTLS the OpenPGP certificate structures [_RFC2440_] are handled using the 'gnutls_openpgp_crt_t' type. A typical certificate contains the user ID, which is an RFC 2822 mail and name address, a public key, possibly a number of additional public keys (called subkeys), and a number of signatures. The various fields are shown in *note Table 4.4: tab:openpgp-certificate. The additional subkeys may provide key for various different purposes, e.g. one key to encrypt mail, and another to sign a TLS key exchange. Each subkey is identified by a unique key ID. The keys that are to be used in a TLS key exchange that requires signatures are called authentication keys in the OpenPGP jargon. The mapping of TLS key exchange methods to public keys is shown in *note Table 4.5: tab:openpgp-key-exchange. Key exchange Public key requirements ------------------------------------------------------------------ RSA An RSA public key that allows encryption. DHE_RSA An RSA public key that is marked for authentication. ECDHE_RSA An RSA public key that is marked for authentication. DHE_DSS A DSA public key that is marked for authentication. Table 4.5: The types of (sub)keys required for the various TLS key exchange methods. The corresponding private keys are stored in the 'gnutls_openpgp_privkey_t' type. All the prototypes for the key handling functions can be found in 'gnutls/openpgp.h'. 4.1.2.2 Verifying an OpenPGP certificate ........................................ The verification functions of OpenPGP keys, included in GnuTLS, are simple ones, and do not use the features of the "web of trust". For that reason, if the verification needs are complex, the assistance of external tools like GnuPG and GPGME(1) is recommended. In GnuTLS there is a verification function for OpenPGP certificates, the *note gnutls_openpgp_crt_verify_ring::. This checks an OpenPGP key against a given set of public keys (keyring) and returns the key status. The key verification status is the same as in X.509 certificates, although the meaning and interpretation are different. For example an OpenPGP key may be valid, if the self signature is ok, even if no signers were found. The meaning of verification status flags is the same as in the X.509 certificates (see *note Figure 4.3: gnutls_certificate_verify_flags.). -- Function: int gnutls_openpgp_crt_verify_ring (gnutls_openpgp_crt_t KEY, gnutls_openpgp_keyring_t KEYRING, unsigned int FLAGS, unsigned int * VERIFY) KEY: the structure that holds the key. KEYRING: holds the keyring to check against FLAGS: unused (should be 0) VERIFY: will hold the certificate verification output. Verify all signatures in the key, using the given set of keys (keyring). The key verification output will be put in 'verify' and will be one or more of the 'gnutls_certificate_status_t' enumerated elements bitwise or'd. Note that this function does not verify using any "web of trust". You may use GnuPG for that purpose, or any other external PGP application. *Returns:* 'GNUTLS_E_SUCCESS' on success, or an error code. -- Function: int gnutls_openpgp_crt_verify_self (gnutls_openpgp_crt_t KEY, unsigned int FLAGS, unsigned int * VERIFY) KEY: the structure that holds the key. FLAGS: unused (should be 0) VERIFY: will hold the key verification output. Verifies the self signature in the key. The key verification output will be put in 'verify' and will be one or more of the gnutls_certificate_status_t enumerated elements bitwise or'd. *Returns:* 'GNUTLS_E_SUCCESS' on success, or an error code. 4.1.2.3 Verifying a certificate in the context of a TLS session ............................................................... Similarly with X.509 certificates, one needs to specify the OpenPGP keyring file in the credentials structure. The certificates in this file will be used by *note gnutls_certificate_verify_peers3:: to verify the signatures in the certificate sent by the peer. -- Function: int gnutls_certificate_set_openpgp_keyring_file (gnutls_certificate_credentials_t C, const char * FILE, gnutls_openpgp_crt_fmt_t FORMAT) C: A certificate credentials structure FILE: filename of the keyring. FORMAT: format of keyring. The function is used to set keyrings that will be used internally by various OpenPGP functions. For example to find a key when it is needed for an operations. The keyring will also be used at the verification functions. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. ---------- Footnotes ---------- (1)  File: gnutls.info, Node: Advanced certificate verification, Next: Digital signatures, Prev: OpenPGP certificates, Up: Certificate authentication 4.1.3 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 *note 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. * Menu: * Verifying a certificate using trust on first use authentication:: * Verifying a certificate using DANE::  File: gnutls.info, Node: Verifying a certificate using trust on first use authentication, Next: Verifying a certificate using DANE, Up: Advanced certificate verification 4.1.3.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 *note Simple client example with SSH-style certificate verification::. See *note Certificate verification:: on how to use the available functionality.  File: gnutls.info, Node: Verifying a certificate using DANE, Prev: Verifying a certificate using trust on first use authentication, Up: Advanced certificate verification 4.1.3.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 *note 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.  File: gnutls.info, Node: Digital signatures, Prev: Advanced certificate verification, Up: Certificate authentication 4.1.4 Digital signatures ------------------------ In this section we will provide some information about digital signatures, how they work, and give the rationale for disabling some of the algorithms used. Digital signatures work by using somebody's secret key to sign some arbitrary data. Then anybody else could use the public key of that person to verify the signature. Since the data may be arbitrary it is not suitable input to a cryptographic digital signature algorithm. For this reason and also for performance cryptographic hash algorithms are used to preprocess the input to the signature algorithm. This works as long as it is difficult enough to generate two different messages with the same hash algorithm output. In that case the same signature could be used as a proof for both messages. Nobody wants to sign an innocent message of donating 1 euro to Greenpeace and find out that he donated 1.000.000 euros to Bad Inc. For a hash algorithm to be called cryptographic the following three requirements must hold: 1. Preimage resistance. That means the algorithm must be one way and given the output of the hash function H(x), it is impossible to calculate x. 2. 2nd preimage resistance. That means that given a pair x,y with y=H(x) it is impossible to calculate an x' such that y=H(x'). 3. Collision resistance. That means that it is impossible to calculate random x and x' such H(x')=H(x). The last two requirements in the list are the most important in digital signatures. These protect against somebody who would like to generate two messages with the same hash output. When an algorithm is considered broken usually it means that the Collision resistance of the algorithm is less than brute force. Using the birthday paradox the brute force attack takes 2^{((hash size) / 2)} operations. Today colliding certificates using the MD5 hash algorithm have been generated as shown in [_WEGER_]. 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.4.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 *note Verifying X.509 certificate paths::), it means that somewhere in the certificate chain there is a certificate signed using 'RSA-MD2' or 'RSA-MD5'. These two digital signature algorithms are considered broken, so GnuTLS 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 *note gnutls_certificate_verify_peers3:: to verify the certificate chain, you can call *note gnutls_certificate_set_verify_flags:: with the flags: * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2' * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5' 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 *note gnutls_x509_crt_verify:: or *note gnutls_x509_crt_list_verify::, you can pass the 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5' parameter directly in the 'flags' parameter. If you are using these flags, it may also be a good idea to warn the user when verification failure occur for this reason. The simplest is to not use the flags by default, and only fall back to using them after warning the user. If you wish to inspect the certificate chain yourself, you can use *note gnutls_certificate_get_peers:: to extract the raw server's certificate chain, *note gnutls_x509_crt_list_import:: to parse each of the certificates, and then *note gnutls_x509_crt_get_signature_algorithm:: to find out the signing algorithm used for each certificate. If any of the intermediary certificates are using 'GNUTLS_SIGN_RSA_MD2' or 'GNUTLS_SIGN_RSA_MD5', you could present a warning.  File: gnutls.info, Node: More on certificate authentication, Next: Shared-key and anonymous authentication, Prev: Certificate authentication, Up: Authentication methods 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. * Menu: * PKCS 10 certificate requests:: * PKIX certificate revocation lists:: * OCSP certificate status checking:: * Managing encrypted keys:: * certtool Invocation:: Invoking certtool * ocsptool Invocation:: Invoking ocsptool * danetool Invocation:: Invoking danetool  File: gnutls.info, Node: PKCS 10 certificate requests, Next: PKIX certificate revocation lists, Up: More on certificate authentication 4.2.1 PKCS #10 certificate requests ----------------------------------- A certificate request is a structure, which contain information about an applicant of a certificate service. It usually contains a private key, a distinguished name and secondary data such as a challenge password. GnuTLS supports the requests defined in PKCS #10 [_RFC2986_]. Other formats of certificate requests are not currently supported. 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 *note gnutls_x509_crq_set_version:: (gnutls_x509_crq_t CRQ, unsigned int VERSION)' 'INT *note gnutls_x509_crq_set_dn:: (gnutls_x509_crq_t CRQ, const char * DN, const char ** ERR)' 'INT *note 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 *note gnutls_x509_crq_set_key_usage:: (gnutls_x509_crq_t CRQ, unsigned int USAGE)' 'INT *note gnutls_x509_crq_set_key_purpose_oid:: (gnutls_x509_crq_t CRQ, const void * OID, unsigned int CRITICAL)' 'INT *note gnutls_x509_crq_set_basic_constraints:: (gnutls_x509_crq_t CRQ, unsigned int CA, int PATHLENCONSTRAINT)' The *note gnutls_x509_crq_set_key:: and *note 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 *note 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' structure 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' structure KEY: holds a private key DIG: The message digest to use, i.e., 'GNUTLS_DIG_SHA1' 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. *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 #endif #include #include #include #include #include #include #include /* 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_NORMAL); gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, bits, 0); /* Add stuff to the distinguished name */ gnutls_x509_crq_set_dn_by_oid(crq, GNUTLS_OID_X520_COUNTRY_NAME, 0, "GR", 2); gnutls_x509_crq_set_dn_by_oid(crq, GNUTLS_OID_X520_COMMON_NAME, 0, "Nikos", strlen("Nikos")); /* Set the request version. */ gnutls_x509_crq_set_version(crq, 1); /* Set a challenge password. */ gnutls_x509_crq_set_challenge_password(crq, "something to remember here"); /* Associate the request with the private key */ gnutls_x509_crq_set_key(crq, key); /* Self sign the certificate request. */ gnutls_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; }  File: gnutls.info, Node: PKIX certificate revocation lists, Next: OCSP certificate status checking, Prev: PKCS 10 certificate requests, Up: More on certificate authentication 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 *note Table 4.6: tab:crl. 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.6: Certificate revocation list fields. The basic CRL structure functions follow. 'INT *note gnutls_x509_crl_init:: (gnutls_x509_crl_t * CRL)' 'INT *note gnutls_x509_crl_import:: (gnutls_x509_crl_t CRL, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)' 'INT *note gnutls_x509_crl_export:: (gnutls_x509_crl_t CRL, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)' 'INT *note 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 *note 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, int INDX, unsigned char * SERIAL, size_t * SERIAL_SIZE, time_t * T) CRL: should contain a 'gnutls_x509_crl_t' structure 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. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. and a negative error code on error. 'INT *note gnutls_x509_crl_get_version:: (gnutls_x509_crl_t CRL)' 'INT *note gnutls_x509_crl_get_issuer_dn:: (const gnutls_x509_crl_t CRL, char * BUF, size_t * SIZEOF_BUF)' 'INT *note gnutls_x509_crl_get_issuer_dn2:: (gnutls_x509_crl_t CRL, gnutls_datum_t * DN)' 'TIME_T *note gnutls_x509_crl_get_this_update:: (gnutls_x509_crl_t CRL)' 'TIME_T *note gnutls_x509_crl_get_next_update:: (gnutls_x509_crl_t CRL)' 'INT *note 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 *note gnutls_x509_crl_set_version:: (gnutls_x509_crl_t CRL, unsigned int VERSION)' 'INT *note gnutls_x509_crl_set_crt_serial:: (gnutls_x509_crl_t CRL, const void * SERIAL, size_t SERIAL_SIZE, time_t REVOCATION_TIME)' 'INT *note gnutls_x509_crl_set_crt:: (gnutls_x509_crl_t CRL, gnutls_x509_crt_t CRT, time_t REVOCATION_TIME)' 'INT *note gnutls_x509_crl_set_next_update:: (gnutls_x509_crl_t CRL, time_t EXP_TIME)' 'INT *note gnutls_x509_crl_set_this_update:: (gnutls_x509_crl_t CRL, time_t ACT_TIME)' The *note gnutls_x509_crl_sign2:: and *note 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 structure ISSUER: is the certificate of the certificate issuer ISSUER_KEY: holds the issuer's private key DIG: The message digest to use. GNUTLS_DIG_SHA1 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. *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 structure ISSUER: is the certificate of the certificate issuer ISSUER_KEY: holds the issuer's private key DIG: The message digest to use. GNUTLS_DIG_SHA1 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. *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 *note gnutls_x509_crl_set_number:: (gnutls_x509_crl_t CRL, const void * NR, size_t NR_SIZE)' 'INT *note gnutls_x509_crl_set_authority_key_id:: (gnutls_x509_crl_t CRL, const void * ID, size_t ID_SIZE)'  File: gnutls.info, Node: OCSP certificate status checking, Next: Managing encrypted keys, Prev: PKIX certificate revocation lists, Up: More on certificate authentication 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 [_RIVESTCRL_]. The Online Certificate Status Protocol, or OCSP [_RFC2560_], is a widely implemented protocol to perform 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. Note that in the context of a TLS session the server may provide an OCSP response that will used during the TLS certificate verification (see *note gnutls_certificate_verify_peers3::). You may obtain this response using *note gnutls_ocsp_status_request_get::. 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 *note 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 create an OCSP request object, store some information about the certificate to check in the request, and then export 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 *note gnutls_ocsp_req_init:: (gnutls_ocsp_req_t * REQ)' 'VOID *note gnutls_ocsp_req_deinit:: (gnutls_ocsp_req_t REQ)' 'INT *note gnutls_ocsp_req_import:: (gnutls_ocsp_req_t REQ, const gnutls_datum_t * DATA)' 'INT *note gnutls_ocsp_req_export:: (gnutls_ocsp_req_t REQ, gnutls_datum_t * DATA)' 'INT *note gnutls_ocsp_req_print:: (gnutls_ocsp_req_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 *note 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 *note 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 *note gnutls_ocsp_req_get_cert_id:: (gnutls_ocsp_req_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 *note gnutls_ocsp_req_get_extension:: (gnutls_ocsp_req_t REQ, unsigned INDX, gnutls_datum_t * OID, unsigned int * CRITICAL, gnutls_datum_t * DATA)' 'INT *note 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 *note gnutls_ocsp_req_get_nonce:: (gnutls_ocsp_req_t REQ, unsigned int * CRITICAL, gnutls_datum_t * NONCE)' 'INT *note gnutls_ocsp_req_set_nonce:: (gnutls_ocsp_req_t REQ, unsigned int CRITICAL, const gnutls_datum_t * NONCE)' 'INT *note 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 *note Table 4.7: tab:ocsp-response. 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.7: The most important OCSP response fields. We provide basic functions for initialization, importing, exporting and deallocating OCSP responses. 'INT *note gnutls_ocsp_resp_init:: (gnutls_ocsp_resp_t * RESP)' 'VOID *note gnutls_ocsp_resp_deinit:: (gnutls_ocsp_resp_t RESP)' 'INT *note gnutls_ocsp_resp_import:: (gnutls_ocsp_resp_t RESP, const gnutls_datum_t * DATA)' 'INT *note gnutls_ocsp_resp_export:: (gnutls_ocsp_resp_t RESP, gnutls_datum_t * DATA)' 'INT *note gnutls_ocsp_resp_print:: (gnutls_ocsp_resp_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_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' structure 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.5: 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 *note gnutls_ocsp_resp_verify:: (gnutls_ocsp_resp_t RESP, gnutls_x509_trust_list_t TRUSTLIST, unsigned int * VERIFY, unsigned int FLAGS)' 'INT *note gnutls_ocsp_resp_verify_direct:: (gnutls_ocsp_resp_t RESP, gnutls_x509_crt_t ISSUER, unsigned int * VERIFY, unsigned int FLAGS)' 'INT *note gnutls_ocsp_resp_check_crt:: (gnutls_ocsp_resp_t RESP, unsigned int INDX, gnutls_x509_crt_t CRT)'  File: gnutls.info, Node: Managing encrypted keys, Next: certtool Invocation, Prev: OCSP certificate status checking, Up: More on certificate authentication 4.2.4 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 *note 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' structure. 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 structure 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. *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 *note gnutls_certificate_set_key::, or alternatively they can be directly imported using *note 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 *note 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 *note 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 *note 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_USE_PKCS12_3DES' PKCS-12 3DES. 'GNUTLS_PKCS_USE_PKCS12_ARCFOUR' PKCS-12 ARCFOUR. 'GNUTLS_PKCS_USE_PKCS12_RC2_40' PKCS-12 RC2-40. 'GNUTLS_PKCS_USE_PBES2_3DES' PBES2 3DES. 'GNUTLS_PKCS_USE_PBES2_AES_128' PBES2 AES-128. 'GNUTLS_PKCS_USE_PBES2_AES_192' PBES2 AES-192. 'GNUTLS_PKCS_USE_PBES2_AES_256' PBES2 AES-256. 'GNUTLS_PKCS_NULL_PASSWORD' Some schemas distinguish between an empty and a NULL password. Figure 4.6: Encryption flags PKCS #12 structures ................... A PKCS #12 structure [_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 *note 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 *note gnutls_pkcs12_simple_parse:: is provided. For more advanced uses, manual parsing of the structure is required using the functions below. 'INT *note gnutls_pkcs12_get_bag:: (gnutls_pkcs12_t PKCS12, int INDX, gnutls_pkcs12_bag_t BAG)' 'INT *note gnutls_pkcs12_verify_mac:: (gnutls_pkcs12_t PKCS12, const char * PASS)' 'INT *note gnutls_pkcs12_bag_decrypt:: (gnutls_pkcs12_bag_t BAG, const char * PASS)' 'INT *note 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: the PKCS12 blob. PASSWORD: optional password used to decrypt PKCS12 blob, 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 blob (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 blob in 'p12blob' and extracts the private key, the corresponding certificate chain, and any additional certificates and a CRL. The 'extra_certs_ret' and 'extra_certs_len' parameters are optional and both may be set to 'NULL' . If either is non-'NULL' , then both must be set. Encrypted PKCS12 bags and PKCS8 private keys are supported. However, only password based security, and the same password for all operations, are supported. A PKCS12 file may contain many keys and/or certificates, and there is no way to identify which key/certificate pair you want. You should make sure the PKCS12 file only contain one key/certificate pair and/or one CRL. It is believed that the limitations of this function are acceptable for common usage, and that any more flexibility would introduce complexity that would make it harder to use this functionality at all. 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. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.1 'INT *note gnutls_pkcs12_bag_get_data:: (gnutls_pkcs12_bag_t BAG, int INDX, gnutls_datum_t * DATA)' 'INT *note gnutls_pkcs12_bag_get_key_id:: (gnutls_pkcs12_bag_t BAG, int INDX, gnutls_datum_t * ID)' 'INT *note gnutls_pkcs12_bag_get_friendly_name:: (gnutls_pkcs12_bag_t BAG, int INDX, char ** NAME)' The functions below are used to generate a PKCS #12 structure. An example of their usage is shown at *note PKCS12 structure generation example::. 'INT *note gnutls_pkcs12_set_bag:: (gnutls_pkcs12_t PKCS12, gnutls_pkcs12_bag_t BAG)' 'INT *note gnutls_pkcs12_bag_encrypt:: (gnutls_pkcs12_bag_t BAG, const char * PASS, unsigned int FLAGS)' 'INT *note gnutls_pkcs12_generate_mac:: (gnutls_pkcs12_t PKCS12, const char * PASS)' 'INT *note gnutls_pkcs12_bag_set_data:: (gnutls_pkcs12_bag_t BAG, gnutls_pkcs12_bag_type_t TYPE, const gnutls_datum_t * DATA)' 'INT *note gnutls_pkcs12_bag_set_crl:: (gnutls_pkcs12_bag_t BAG, gnutls_x509_crl_t CRL)' 'INT *note gnutls_pkcs12_bag_set_crt:: (gnutls_pkcs12_bag_t BAG, gnutls_x509_crt_t CRT)' 'INT *note gnutls_pkcs12_bag_set_key_id:: (gnutls_pkcs12_bag_t BAG, int INDX, const gnutls_datum_t * ID)' 'INT *note gnutls_pkcs12_bag_set_friendly_name:: (gnutls_pkcs12_bag_t BAG, int 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 *note 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 structure 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.  File: gnutls.info, Node: certtool Invocation, Next: ocsptool Invocation, Prev: Managing encrypted keys, Up: More on certificate authentication 4.2.5 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. 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 [ - [] | --[{=| }] ]... -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 -s, --generate-self-signed Generate a self-signed certificate -c, --generate-certificate Generate a signed certificate --generate-proxy Generates a proxy certificate --generate-crl Generate a CRL -u, --update-certificate Update a signed certificate -p, --generate-privkey Generate a private key -q, --generate-request Generate a PKCS #10 certificate request - prohibits the option 'infile' -e, --verify-chain Verify a PEM encoded certificate chain --verify Verify a PEM encoded certificate chain using a trusted list --verify-crl Verify a CRL using a trusted list - requires the option 'load-ca-certificate' --generate-dh-params Generate PKCS #3 encoded Diffie-Hellman parameters --get-dh-params Get 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 --password=str Password to use --hex-numbers Print big number in an easier format to parse --cprint In certain operations it prints the information in C-friendly format --null-password Enforce a NULL password --empty-password Enforce an empty password -i, --certificate-info Print information on the given certificate --certificate-pubkey Print certificate's public key --pgp-certificate-info Print information on the given OpenPGP certificate --pgp-ring-info Print information on the given OpenPGP keyring structure -l, --crl-info Print information on the given CRL structure --crq-info Print information on the given certificate request --no-crq-extensions Do not use extensions in certificate requests --p12-info Print information on a PKCS #12 structure --p7-info Print information on a PKCS #7 structure --smime-to-p7 Convert S/MIME to PKCS #7 structure -k, --key-info Print information on a private key --pgp-key-info Print information on an OpenPGP private key --pubkey-info Print information on a public key --v1 Generate an X.509 version 1 certificate (with no extensions) --to-p12 Generate a PKCS #12 structure - requires the option 'load-certificate' -!, --to-p8 Generate a PKCS #8 structure -8, --pkcs8 Use PKCS #8 format for private keys -", --rsa Generate RSA key -#, --dsa Generate DSA key -$, --ecc Generate ECC (ECDSA) key -%, --ecdsa an alias for the 'ecc' option -&, --hash=str Hash algorithm to use for signing -', --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 -+, --bits=num Specify the number of bits for key generate -,, --sec-param=str Specify the security level [low, legacy, normal, high, ultra] --, --disable-quick-random No effect -., --template=str Template file to use for non-interactive operation -/, --ask-pass Enable interaction for entering password when in batch mode. -0, --pkcs-cipher=str Cipher to use for PKCS #8 and #12 operations -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. Please send bug reports to: <@PACKAGE_BUGREPORT@> debug option (-d) ................. This is the "enable debugging" option. This option takes a number argument. Specifies the debug level. 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. verify-chain option (-e) ........................ This is the "verify a pem encoded certificate chain" option. The last certificate in the chain must be a self signed one. verify option ............. This is the "verify a pem encoded certificate chain using a trusted list" option. The trusted certificate list can be loaded with -load-ca-certificate. If no certificate list is provided, then the system's certificate list is used. verify-crl option ................. This is the "verify a crl 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. get-dh-params option .................... This is the "get the included pkcs #3 encoded diffie-hellman parameters" option. Returns stored DH parameters in GnuTLS. Those parameters are used in the SRP protocol. The parameters returned by fresh generation are more efficient since GnuTLS 3.0.9. 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-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 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 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. 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. 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. 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. to-p12 option ............. This is the "generate a pkcs #12 structure" option. This option has some usage constraints. It: * must appear in combination with the following options: load-certificate. It requires a certificate, a private key and possibly a CA certificate to be specified. rsa option .......... This is the "generate rsa key" option. When combined with -generate-privkey generates an RSA private key. dsa option .......... This is the "generate dsa key" option. When combined with -generate-privkey generates a DSA private key. 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. ecdsa option ............ This is an alias for the 'ecc' option, *note the ecc option documentation: certtool ecc. 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. 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, *note the inder option documentation: certtool inder. 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, *note the outder option documentation: certtool outder. sec-param option ................ This is the "specify the security level [low, legacy, normal, high, ultra]" option. This option takes a string argument 'Security parameter'. This is alternative to the bits option. 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. 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) 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 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 Diffie-Hellman parameter generation ................................... To generate parameters for Diffie-Hellman key exchange, use the command: $ certtool --generate-dh-params --outfile dh.pem --sec-param normal 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=Nik,st=Attiki,C=GR,surName=Mavrogiannopoulos,2.5.4.9=Arkadias" # The serial number of the certificate # Comment the field for a time-based 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: # http://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" # A subject alternative name URI #uri = "http://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" # 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 = "http://www.getcrl.crl/getcrl/" # Whether this is a CA certificate or not #ca # for microsoft smart card logon # key_purpose_oid = 1.3.6.1.4.1.311.20.2.2 ### Other predefined key purpose OIDs # Whether this certificate will be used for a TLS client #tls_www_client # Whether this certificate will be used for a TLS server #tls_www_server # Whether this certificate will be used to sign data (needed # in TLS DHE ciphersuites). signing_key # Whether this certificate will be used to encrypt data (needed # in TLS RSA ciphersuites). Note that it is preferred to use different # keys for encryption and signing. encryption_key # Whether this key will be used to sign other certificates. #cert_signing_key # Whether this key will be used to sign CRLs. #crl_signing_key # Whether this key will be used to sign code. #code_signing_key # Whether this key will be used to sign OCSP data. #ocsp_signing_key # Whether this key will be used for time stamping. #time_stamping_key # Whether this key will be used for IPsec IKE operations. #ipsec_ike_key ### end of key purpose OIDs # 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 # Path length contraint. 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 = http://my.ocsp.server/ocsp # CA issuers URI # ca_issuers_uri = http://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 = http://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 = http://www.example.com/another-policy-to-read # Options for proxy certificates # proxy_policy_language = 1.3.6.1.5.5.7.21.1 # Options for generating a CRL # next CRL update will be in 43 days (wow) #crl_next_update = 43 # this is the 5th CRL by this CA #crl_number = 5  File: gnutls.info, Node: ocsptool Invocation, Next: danetool Invocation, Prev: certtool Invocation, Up: More on certificate authentication 4.2.6 Invoking ocsptool ----------------------- Ocsptool is a program that can parse and print information about OCSP requests/responses, generate requests and verify responses. 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 [ - [] | --[{=| }] ]... -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 - requires these options: load-cert load-issuer -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 Generate an OCSP request --nonce Use (or not) a nonce to OCSP request - disabled as '--no-nonce' --load-issuer=file Read issuer certificate from file - file must pre-exist --load-cert=file Read 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 Read 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' -Q, --load-request=file Read DER encoded OCSP request from file - file must pre-exist -S, --load-response=file Read DER encoded OCSP response from file - file must pre-exist -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. Please send bug reports to: <@PACKAGE_BUGREPORT@> 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'. This option has some usage constraints. It: * must appear in combination with the following options: load-cert, load-issuer. Connects to the specified HTTP OCSP server and queries on the validity of the loaded certificate. 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 --print-cert > chain.pem Use a text editor on 'chain.pem' to create three files for each separate certificates, called 'cert.pem' for the first certificate for the domain itself, secondly 'issuer.pem' for the intermediate certificate and 'root.pem' for the final root certificate. The domain certificate normally contains a pointer to where the OCSP responder is located, in the Authority Information Access Information extension. For example, from 'certtool -i < cert.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: http://ocsp.CAcert.org/ This means the CA support OCSP queries over HTTP. We are now ready to create a OCSP request for the certificate. $ ocsptool --ask ocsp.CAcert.org --load-issuer issuer.pem \ --load-cert cert.pem --outfile ocsp-response.der The request is sent via HTTP to the OCSP server address specified. If the address is ommited ocsptool will use the address stored in the certificate.  File: gnutls.info, Node: danetool Invocation, Prev: ocsptool Invocation, Up: More on certificate authentication 4.2.7 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 [ - [] | --[{=| }] ]... -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 --insecure Do not verify any DNSSEC signature --local-dns Use the local DNS server for DNSSEC resolving - disabled as '--no-local-dns' --inder Use DER format for input certificates and private keys - disabled as '--no-inder' --inraw an alias for the 'inder' option --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=num Specify the port number for the DANE data --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 -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. Please send bug reports to: <@PACKAGE_BUGREPORT@> 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 has to be provided using -load-certificate. 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. insecure option ............... This is the "do not verify any dnssec signature" option. Ignores any DNSSEC signature verification results. 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. 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, *note the inder option documentation: danetool inder. 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. 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, *note the domain option documentation: danetool domain. 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. 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 a server's DANE TLSA entry, use: $ danetool --check www.example.com --proto tcp --port 443 --load-certificate chain.pem  File: gnutls.info, Node: Shared-key and anonymous authentication, Next: Selecting an appropriate authentication method, Prev: More on certificate authentication, Up: Authentication methods 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. * Menu: * SRP authentication:: * PSK authentication:: * Anonymous authentication::  File: gnutls.info, Node: SRP authentication, Next: PSK authentication, Up: Shared-key and anonymous authentication 4.3.1 SRP authentication ------------------------ * Menu: * Authentication using SRP:: * srptool Invocation:: Invoking srptool  File: gnutls.info, Node: Authentication using SRP, Next: srptool Invocation, Up: SRP authentication 4.3.1.1 Authentication using SRP ................................ GnuTLS supports authentication via the Secure Remote Password or SRP protocol (see [_RFC2945,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. 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 [_TLSSRP_]. The supported key exchange methods are shown below. '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 *note gnutls_srp_base64_encode_alloc:: (const gnutls_datum_t * DATA, gnutls_datum_t * RESULT)' 'INT *note gnutls_srp_base64_decode_alloc:: (const gnutls_datum_t * B64_DATA, gnutls_datum_t * RESULT)'  File: gnutls.info, Node: srptool Invocation, Prev: Authentication using SRP, Up: SRP authentication 4.3.1.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 [ - [] | --[{=| }] ]... -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). Please send bug reports to: <@PACKAGE_BUGREPORT@> 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  File: gnutls.info, Node: PSK authentication, Next: Anonymous authentication, Prev: SRP authentication, Up: Shared-key and anonymous authentication 4.3.2 PSK authentication ------------------------ * Menu: * Authentication using PSK:: * psktool Invocation:: Invoking psktool  File: gnutls.info, Node: Authentication using PSK, Next: psktool Invocation, Up: PSK authentication 4.3.2.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. The implementation in GnuTLS is based on [_TLSPSK_]. The supported PSK key exchange methods are: 'PSK:' Authentication using the PSK protocol. 'DHE-PSK:' Authentication using the PSK protocol and Diffie-Hellman key exchange. This method offers perfect forward secrecy. '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. Helper functions to generate and maintain PSK keys are also included in GnuTLS. 'INT *note gnutls_key_generate:: (gnutls_datum_t * KEY, unsigned int KEY_SIZE)' 'INT *note gnutls_hex_encode:: (const gnutls_datum_t * DATA, char * RESULT, size_t * RESULT_SIZE)' 'INT *note gnutls_hex_decode:: (const gnutls_datum_t * HEX_DATA, void * RESULT, size_t * RESULT_SIZE)'  File: gnutls.info, Node: psktool Invocation, Prev: Authentication using PSK, Up: PSK authentication 4.3.2.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 [ - [] | --[{=| }] ]... -d, --debug=num Enable debugging - it must be in the range: 0 to 9999 -s, --keysize=num specify the key size in bytes - it must be in the range: 0 to 512 -u, --username=str specify a username -p, --passwd=str specify a password 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. Please send bug reports to: <@PACKAGE_BUGREPORT@> debug option (-d) ................. This is the "enable debugging" option. This option takes a number argument. Specifies the debug level. 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 'passwd.psk' for use with GnuTLS run: $ ./psktool -u psk_identity -p passwd.psk Generating a random key for user 'psk_identity' Key stored to passwd.psk $ cat psks.txt psk_identity:88f3824b3e5659f52d00e959bacab954b6540344 $ This command will create 'passwd.psk' if it does not exist and will add user 'psk_identity' (you will also be prompted for a password).  File: gnutls.info, Node: Anonymous authentication, Prev: PSK authentication, Up: Shared-key and anonymous authentication 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. 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 *note 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. '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.  File: gnutls.info, Node: Selecting an appropriate authentication method, Prev: Shared-key and anonymous authentication, Up: Authentication methods 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 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 *note 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 *note SRP authentication::). The client communicates to the server his username and password of choice and uses it to negotiate further sessions over the untrusted channel. * Public keys (see *note 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 *note 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 *note 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 *note 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 *note 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 *note 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 *note SRP authentication::). The client communicates to the server his 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 *note 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 *note Verifying a certificate using trust on first use authentication::).  File: gnutls.info, Node: Hardware security modules and abstract key types, Next: How to use GnuTLS in applications, Prev: Authentication methods, Up: Top 5 Hardware security modules and abstract key types ************************************************** 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 guarranteed. 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. * Menu: * Abstract key types:: * Smart cards and HSMs:: * Trusted Platform Module::  File: gnutls.info, Node: Abstract key types, Next: Smart cards and HSMs, Up: Hardware security modules and abstract key types 5.1 Abstract key types ====================== Since there are many forms of a public or private keys supported by GnuTLS such as X.509, OpenPGP, 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 must be used. #inlude 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_pkcs11_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); } * Menu: * Abstract public keys:: * Abstract private keys:: * Operations::  File: gnutls.info, Node: Abstract public keys, Next: Abstract private keys, Up: Abstract key types 5.1.1 Public keys ----------------- An abstract 'gnutls_pubkey_t' can be initialized using the functions below. It can be imported through an existing structure like 'gnutls_x509_crt_t', or through an ASN.1 encoding of the X.509 'SubjectPublicKeyInfo' sequence. 'INT *note gnutls_pubkey_import_x509:: (gnutls_pubkey_t KEY, gnutls_x509_crt_t CRT, unsigned int FLAGS)' 'INT *note gnutls_pubkey_import_openpgp:: (gnutls_pubkey_t KEY, gnutls_openpgp_crt_t CRT, unsigned int FLAGS)' 'INT *note gnutls_pubkey_import_pkcs11:: (gnutls_pubkey_t KEY, gnutls_pkcs11_obj_t OBJ, unsigned int FLAGS)' 'INT *note gnutls_pubkey_import_url:: (gnutls_pubkey_t KEY, const char * URL, unsigned int FLAGS)' 'INT *note gnutls_pubkey_import_privkey:: (gnutls_pubkey_t KEY, gnutls_privkey_t PKEY, unsigned int USAGE, unsigned int FLAGS)' 'INT *note gnutls_pubkey_import:: (gnutls_pubkey_t KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)' 'INT *note 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 or OpenPGP structures are shown below. 'INT *note gnutls_pubkey_import_x509_raw:: (gnutls_pubkey_t PKEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)' 'INT *note gnutls_pubkey_import_openpgp_raw:: (gnutls_pubkey_t PKEY, const gnutls_datum_t * DATA, gnutls_openpgp_crt_fmt_t FORMAT, const gnutls_openpgp_keyid_t KEYID, unsigned int FLAGS)' An important function is *note gnutls_pubkey_import_url:: which will import public keys from URLs that identify objects stored in tokens (see *note Smart cards and HSMs:: and *note Trusted Platform Module::). A function to check for a supported by GnuTLS URL is *note gnutls_url_is_supported::. -- Function: int gnutls_url_is_supported (const char * URL) URL: A PKCS 11 url Check whether url is supported. Depending on the system libraries GnuTLS may support pkcs11 or tpmkey 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 *note 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 [_RFC5280_] which calculates a digest on a part of the subjectPublicKeyInfo object. 'INT *note gnutls_pubkey_get_pk_algorithm:: (gnutls_pubkey_t KEY, unsigned int * BITS)' 'INT *note gnutls_pubkey_get_preferred_hash_algorithm:: (gnutls_pubkey_t KEY, gnutls_digest_algorithm_t * HASH, unsigned int * MAND)' 'INT *note gnutls_pubkey_get_key_id:: (gnutls_pubkey_t KEY, unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)' 'INT *note 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 *note gnutls_pubkey_get_pk_rsa_raw:: (gnutls_pubkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E)' 'INT *note gnutls_pubkey_get_pk_dsa_raw:: (gnutls_pubkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y)' 'INT *note gnutls_pubkey_get_pk_ecc_raw:: (gnutls_pubkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y)' 'INT *note gnutls_pubkey_get_pk_ecc_x962:: (gnutls_pubkey_t KEY, gnutls_datum_t * PARAMETERS, gnutls_datum_t * ECPOINT)'  File: gnutls.info, Node: Abstract private keys, Next: Operations, Prev: Abstract public keys, Up: Abstract key types 5.1.2 Private keys ------------------ An abstract 'gnutls_privkey_t' can be initialized using the functions below. It can be imported through 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 *note gnutls_privkey_import_x509:: (gnutls_privkey_t PKEY, gnutls_x509_privkey_t KEY, unsigned int FLAGS)' 'INT *note gnutls_privkey_import_openpgp:: (gnutls_privkey_t PKEY, gnutls_openpgp_privkey_t KEY, unsigned int FLAGS)' 'INT *note 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 or OpenPGP structures are shown below. Again, as with public keys, private keys can be imported from a hardware module using URLs. 'INT *note 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 *note gnutls_privkey_import_openpgp_raw:: (gnutls_privkey_t PKEY, const gnutls_datum_t * DATA, gnutls_openpgp_crt_fmt_t FORMAT, const gnutls_openpgp_keyid_t KEYID, const char * PASSWORD)' -- 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 *note gnutls_privkey_get_pk_algorithm:: (gnutls_privkey_t KEY, unsigned int * BITS)' 'GNUTLS_PRIVKEY_TYPE_T *note gnutls_privkey_get_type:: (gnutls_privkey_t KEY)' 'INT *note 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_ext2 (gnutls_privkey_t PKEY, gnutls_pk_algorithm_t PK, void * USERDATA, gnutls_privkey_sign_func SIGN_FUNC, gnutls_privkey_decrypt_func DECRYPT_FUNC, gnutls_privkey_deinit_func DEINIT_FUNC, unsigned int FLAGS) PKEY: The private key PK: The public key algorithm USERDATA: private data to be provided to the callbacks SIGN_FUNC: callback for signature operations DECRYPT_FUNC: callback for decryption operations DEINIT_FUNC: a deinitialization function FLAGS: Flags for the import This function will associate the given callbacks with the 'gnutls_privkey_t' structure. At least one of the two callbacks must be non-null. If a deinitialization function is provided then flags is assumed to contain 'GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE' . Note that the signing function is supposed to "raw" sign data, i.e., without any hashing or preprocessing. In case of RSA the DigestInfo will be provided, and the signing function is expected to do the PKCS '1' 1.5 padding and the exponentiation. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.1  File: gnutls.info, Node: Operations, Prev: Abstract private keys, Up: Abstract key types 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 one of 'gnutls_pubkey_flags_t' 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. *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 one of 'gnutls_pubkey_flags_t' 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. *Returns:* In case of a verification failure 'GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and zero or positive code on success. *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. *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 allocate with 'gnutls_malloc()' This function will sign the given data using a signature algorithm supported by the private key. Signature algorithms are always used together with a hash functions. Different hash functions may be used for the RSA algorithm, but only 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. Note that if 'GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA' flag is specified this function will ignore 'hash_algo' and perform a raw PKCS1 signature. *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' structure KEY: holds a public key This function will set the public parameters from the given public key to the request. *Returns:* On success, 'GNUTLS_E_SUCCESS' (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' structure KEY: holds a public key This function will set the public parameters from the given public key to the request. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 2.12.0 'INT *note 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 *note 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 *note gnutls_x509_crq_privkey_sign:: (gnutls_x509_crq_t CRQ, gnutls_privkey_t KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'  File: gnutls.info, Node: Smart cards and HSMs, Next: Trusted Platform Module, Prev: Abstract key types, Up: Hardware security modules and abstract key types 5.2 Smart cards and HSMs ======================== In this section we present the smart-card and hardware security module (HSM) support in GnuTLS using PKCS #11 [_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'. Moreover PKCS #11 can be (ab)used to allow all applications in the same operating system to access shared cryptographic keys and certificates in a uniform way, as in *note Figure 5.1: fig-pkcs11-vision. That way applications could load their trusted certificate list, as well as user certificates from a common PKCS #11 module. Such a provider exists in the Gnome system, being the Gnome Keyring. [image src="pkcs11-vision.png"] Figure 5.1: PKCS #11 module usage. * Menu: * PKCS11 Initialization:: * Accessing objects that require a PIN:: * Reading objects:: * Writing objects:: * Using a PKCS11 token with TLS:: * p11tool Invocation:: Invoking p11tool ---------- Footnotes ---------- (1)  File: gnutls.info, Node: PKCS11 Initialization, Next: Accessing objects that require a PIN, Up: Smart cards and HSMs 5.2.1 Initialization -------------------- To allow all GnuTLS applications to transparently access smard cards and tokens, PKCS #11 is automatically initialized during the global initialization (see *note gnutls_global_init::). The initialization function, to select which modules to load reads certain module configuration files. Those are stored in '/etc/pkcs11/modules/' and are the configuration files of p11-kit(1). For example a file that will 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 functions (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. In all cases, you can also manually initialize the PKCS #11 subsystem if the default settings are not desirable. To completely disable PKCS #11 support you need to call *note gnutls_pkcs11_init:: with the flag 'GNUTLS_PKCS11_FLAG_MANUAL' prior to *note gnutls_global_init::. -- Function: int gnutls_pkcs11_init (unsigned int FLAGS, const char * DEPRECATED_CONFIG_FILE) FLAGS: 'GNUTLS_PKCS11_FLAG_MANUAL' or 'GNUTLS_PKCS11_FLAG_AUTO' DEPRECATED_CONFIG_FILE: either NULL or the location of a deprecated configuration file This function will initialize the PKCS 11 subsystem in gnutls. It will read configuration files if 'GNUTLS_PKCS11_FLAG_AUTO' is used or allow you to independently load PKCS 11 modules using 'gnutls_pkcs11_add_provider()' if 'GNUTLS_PKCS11_FLAG_MANUAL' is specified. Normally you don't need to call this function since it is being called by 'gnutls_global_init()' using the 'GNUTLS_PKCS11_FLAG_AUTO' . If other option is required then it must be called before it. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 2.12.0 Note that PKCS #11 modules must be reinitialized on the child processes after a 'fork'. GnuTLS provides *note gnutls_pkcs11_reinit:: to be called for this purpose. -- Function: int gnutls_pkcs11_reinit ( VOID) This function will reinitialize the PKCS 11 subsystem in gnutls. This is required by PKCS 11 when an application uses 'fork()' . The reinitialization function must be called on the child. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.0 ---------- Footnotes ---------- (1)  File: gnutls.info, Node: Accessing objects that require a PIN, Next: Reading objects, Prev: PKCS11 Initialization, Up: Smart cards and HSMs 5.2.2 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 *note gnutls_pkcs11_set_token_function:: (gnutls_pkcs11_token_callback_t FN, void * USERDATA)' 'VOID *note gnutls_pkcs11_set_pin_function:: (gnutls_pin_callback_t FN, void * USERDATA)' 'INT *note gnutls_pkcs11_add_provider:: (const char * NAME, const char * PARAMS)' 'GNUTLS_PIN_CALLBACK_T *note 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, *note 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 *note gnutls_certificate_set_pin_function:: (gnutls_certificate_credentials_t CRED, gnutls_pin_callback_t FN, void * USERDATA)' 'VOID *note gnutls_pubkey_set_pin_function:: (gnutls_pubkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)' 'VOID *note gnutls_privkey_set_pin_function:: (gnutls_privkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)' 'VOID *note gnutls_pkcs11_obj_set_pin_function:: (gnutls_pkcs11_obj_t OBJ, gnutls_pin_callback_t FN, void * USERDATA)' 'VOID *note gnutls_x509_crt_set_pin_function:: (gnutls_x509_crt_t CRT, gnutls_pin_callback_t FN, void * USERDATA)'  File: gnutls.info, Node: Reading objects, Next: Writing objects, Prev: Accessing objects that require a PIN, Up: Smart cards and HSMs 5.2.3 Reading objects --------------------- All PKCS #11 objects are referenced by GnuTLS functions by URLs as described in [_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;objecttype=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 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 access objects are shown below. 'INT *note gnutls_pkcs11_obj_import_url:: (gnutls_pkcs11_obj_t OBJ, const char * URL, unsigned int FLAGS)' 'INT *note 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 CRT, gnutls_pkcs11_obj_info_t ITYPE, void * OUTPUT, size_t * OUTPUT_SIZE) CRT: should contain a 'gnutls_pkcs11_obj_t' structure ITYPE: Denotes the type of information requested OUTPUT: where output will be stored OUTPUT_SIZE: contains the maximum size of the output and will be overwritten with actual This function will return information about the PKCS11 certificate such as the label, id as well as token information where the key is stored. When output is text it returns null terminated string although 'output_size' contains the size of the actual data only. *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error code on error. *Since:* 2.12.0 'INT *note gnutls_x509_crt_import_pkcs11:: (gnutls_x509_crt_t CRT, gnutls_pkcs11_obj_t PKCS11_CRT)' 'INT *note gnutls_x509_crt_import_pkcs11_url:: (gnutls_x509_crt_t CRT, const char * URL, unsigned int FLAGS)' 'INT *note 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 *note gnutls_pkcs11_token_init:: (const char * TOKEN_URL, const char * SO_PIN, const char * LABEL)' 'INT *note gnutls_pkcs11_token_get_url:: (unsigned int SEQ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)' 'INT *note gnutls_pkcs11_token_get_info:: (const char * URL, gnutls_pkcs11_token_info_t TTYPE, void * OUTPUT, size_t * OUTPUT_SIZE)' 'INT *note gnutls_pkcs11_token_get_flags:: (const char * URL, unsigned int * FLAGS)' 'INT *note 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 #include #include #include #include #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; obj_list_size = 0; ret = gnutls_pkcs11_obj_list_import_url(NULL, &obj_list_size, URL, GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY, 0); if (ret < 0 && ret != GNUTLS_E_SHORT_MEMORY_BUFFER) return -1; /* no error checking from now on */ obj_list = malloc(sizeof(*obj_list) * obj_list_size); gnutls_pkcs11_obj_list_import_url(obj_list, &obj_list_size, URL, GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY, 0); /* 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); } return 0; }  File: gnutls.info, Node: Writing objects, Next: Using a PKCS11 token with TLS, Prev: Reading objects, Up: Smart cards and HSMs 5.2.4 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_privkey (const char * TOKEN_URL, gnutls_x509_privkey_t KEY, const char * LABEL, unsigned int KEY_USAGE, unsigned int FLAGS) TOKEN_URL: A PKCS '11' URL specifying a token KEY: A private key LABEL: A name to be used for the stored data KEY_USAGE: One of GNUTLS_KEY_* FLAGS: One of GNUTLS_PKCS11_OBJ_* flags This function will copy a private key into a PKCS '11' token specified by a URL. It is highly recommended flags to contain 'GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE' unless there is a strong reason not to. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 2.12.0 -- Function: int gnutls_pkcs11_copy_x509_crt (const char * TOKEN_URL, gnutls_x509_crt_t CRT, const char * LABEL, unsigned int FLAGS) TOKEN_URL: A PKCS '11' URL specifying a token CRT: A certificate LABEL: A name to be used for the stored data FLAGS: One of GNUTLS_PKCS11_OBJ_FLAG_* This function will copy a certificate into a PKCS '11' token specified by a URL. The certificate can be marked as trusted or not. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 2.12.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  File: gnutls.info, Node: Using a PKCS11 token with TLS, Next: p11tool Invocation, Prev: Writing objects, Up: Smart cards and HSMs 5.2.5 Using a PKCS #11 token with TLS ------------------------------------- It is possible to use a PKCS #11 token to a TLS session, as shown in *note ex-pkcs11-client::. In addition the following functions can be used to load PKCS #11 key and certificates by specifying a PKCS #11 URL instead of a filename. 'INT *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)' 'INT *note 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)' -- Function: int gnutls_certificate_set_x509_system_trust (gnutls_certificate_credentials_t CRED) CRED: is a 'gnutls_certificate_credentials_t' structure. This function adds the system's default trusted CAs in order to verify client or server certificates. In the case the system is currently unsupported 'GNUTLS_E_UNIMPLEMENTED_FEATURE' is returned. *Returns:* the number of certificates processed or a negative error code on error. *Since:* 3.0  File: gnutls.info, Node: p11tool Invocation, Prev: Using a PKCS11 token with TLS, Up: Smart cards and HSMs 5.2.6 Invoking p11tool ---------------------- Program that allows handling data from PKCS #11 smart cards and security modules. To use PKCS #11 tokens with gnutls 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'. Alternatively the p11-kit configuration files have to be setup. To provide the PIN for all the operations below use the environment variable GNUTLS_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 [ - [] | --[{=| }] ]... [url] -d, --debug=num Enable debugging - it must be in the range: 0 to 9999 --outfile=str Output file --list-tokens List all available tokens --export Export the object specified by the URL --export-chain Export the certificate specified by the URL and its chain of trust --list-mechanisms List all available mechanisms in a token --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 --initialize Initializes a PKCS #11 token --write Writes the loaded objects to a PKCS #11 token --delete Deletes the objects matching the PKCS #11 URL --generate-random=num Generate random data --generate-rsa Generate an RSA private-public key pair --generate-dsa Generate an RSA private-public key pair --generate-ecc Generate an RSA private-public key pair --label=str Sets a label for the write operation --trusted Marks the object to be written as trusted - disabled as '--no-trusted' --private Marks the object to be written as private - disabled as '--no-private' - enabled by default --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 --detailed-url Print detailed URLs - disabled as '--no-detailed-url' --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 -8, --pkcs8 Use PKCS #8 format for private keys --bits=num Specify the number of bits for key generate --sec-param=str Specify the security level -!, --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 - file must pre-exist -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 handling data from PKCS #11 smart cards and security modules. To use PKCS #11 tokens with gnutls 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'. Alternatively the p11-kit configuration files have to be setup. To provide the PIN for all the operations below use the environment variable GNUTLS_PIN. Please send bug reports to: <@PACKAGE_BUGREPORT@> debug option (-d) ................. This is the "enable debugging" option. This option takes a number argument. Specifies the debug level. export-chain option ................... This is the "export the certificate specified by the url and its chain of trust" option. Exports the certificate specified by the URL and generates its chain of trust based on the stored certificates in the module. 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, *note the list-all-privkeys option documentation: p11tool list-all-privkeys. list-keys option ................ This is an alias for the 'list-all-privkeys' option, *note the list-all-privkeys option documentation: p11tool list-all-privkeys. write option ............ This is the "writes the loaded objects to a pkcs #11 token" option. It can be used to write private keys, certificates or secret keys to a token. 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. 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. generate-dsa option ................... This is the "generate an rsa private-public key pair" option. Generates an RSA private-public key pair on the specified token. generate-ecc option ................... This is the "generate an rsa private-public key pair" option. Generates an RSA private-public key pair on the specified token. 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-private. * It is enabled by default. The written object will require a PIN to be used. 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, *note the so-login option documentation: p11tool so-login. 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, normal, high, ultra]. 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, *note the inder option documentation: p11tool inder. 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, *note the outder option documentation: p11tool outder. 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 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-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 a limited number of bits. 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  File: gnutls.info, Node: Trusted Platform Module, Prev: Smart cards and HSMs, Up: Hardware security modules and abstract key types 5.3 Trusted Platform Module (TPM) ================================= In this section we present the Trusted Platform Module (TPM) support in GnuTLS. There was a big hype when the TPM chip was introduced into computers. Briefly it is a co-processor in your PC that allows it to perform calculations independently of the main processor. This has good and bad side-effects. In this section we focus on the good ones; these are the fact that you can use the TPM chip to perform cryptographic operations on keys stored in it, without accessing them. That is very similar to the operation of a PKCS #11 smart card. The chip allows for storage and usage of RSA keys, but has quite some operational differences from PKCS #11 module, and thus require different handling. The basic TPM operations supported and used by GnuTLS, are key generation and signing. The next sections assume that the TPM chip in the system is already initialized and in a operational state. In GnuTLS the TPM functionality is available in 'gnutls/tpm.h'. * Menu: * Keys in TPM:: * Key generation:: * Using keys:: * tpmtool Invocation:: Invoking tpmtool  File: gnutls.info, Node: Keys in TPM, Next: Key generation, Up: Trusted Platform Module 5.3.1 Keys in TPM ----------------- The RSA keys in the TPM module may either be stored in a flash memory within TPM or stored in a file in disk. In the former case the key can provide operations as with PKCS #11 and is identified by a URL. The URL is described in [_TPMURI_] and is of the following form. tpmkey:uuid=42309df8-d101-11e1-a89a-97bb33c23ad1;storage=user It consists from a unique identifier of the key as well as the part of the flash memory the key is stored at. The two options for the storage field are 'user' and 'system'. The user keys are typically only available to the generating user and the system keys to all users. The stored in TPM keys are called registered keys. The keys that are stored in the disk are exported from the TPM but in an encrypted form. To access them two passwords are required. The first is the TPM Storage Root Key (SRK), and the other is a key-specific password. Also those keys are identified by a URL of the form: tpmkey:file=/path/to/file When objects require a PIN to be accessed the same callbacks as with PKCS #11 objects are expected (see *note Accessing objects that require a PIN::). Note that the PIN function may be called multiple times to unlock the SRK and the specific key in use. The label in the key function will then be set to 'SRK' when unlocking the SRK key, or to 'TPM' when unlocking any other key.  File: gnutls.info, Node: Key generation, Next: Using keys, Prev: Keys in TPM, Up: Trusted Platform Module 5.3.2 Key generation -------------------- All keys used by the TPM must be generated by the TPM. This can be done using *note gnutls_tpm_privkey_generate::. -- Function: int gnutls_tpm_privkey_generate (gnutls_pk_algorithm_t PK, unsigned int BITS, const char * SRK_PASSWORD, const char * KEY_PASSWORD, gnutls_tpmkey_fmt_t FORMAT, gnutls_x509_crt_fmt_t PUB_FORMAT, gnutls_datum_t * PRIVKEY, gnutls_datum_t * PUBKEY, unsigned int FLAGS) PK: the public key algorithm BITS: the security bits SRK_PASSWORD: a password to protect the exported key (optional) KEY_PASSWORD: the password for the TPM (optional) FORMAT: the format of the private key PUB_FORMAT: the format of the public key PRIVKEY: the generated key PUBKEY: the corresponding public key (may be null) FLAGS: should be a list of GNUTLS_TPM_* flags This function will generate a private key in the TPM chip. The private key will be generated within the chip and will be exported in a wrapped with TPM's master key form. Furthermore the wrapped key can be protected with the provided 'password' . Note that bits in TPM is quantized value. If the input value is not one of the allowed values, then it will be quantized to one of 512, 1024, 2048, 4096, 8192 and 16384. Allowed flags are: *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.1.0 'INT *note gnutls_tpm_get_registered:: (gnutls_tpm_key_list_t * LIST)' 'VOID *note gnutls_tpm_key_list_deinit:: (gnutls_tpm_key_list_t LIST)' 'INT *note gnutls_tpm_key_list_get_url:: (gnutls_tpm_key_list_t LIST, unsigned int IDX, char ** URL, unsigned int FLAGS)' -- Function: int gnutls_tpm_privkey_delete (const char * URL, const char * SRK_PASSWORD) URL: the URL describing the key SRK_PASSWORD: a password for the SRK key This function will unregister the private key from the TPM chip. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.1.0  File: gnutls.info, Node: Using keys, Next: tpmtool Invocation, Prev: Key generation, Up: Trusted Platform Module 5.3.3 Using keys ---------------- Importing keys .............. The TPM keys can be used directly by the abstract key types and do not require any special structures. Moreover functions like *note gnutls_certificate_set_x509_key_file2:: can access TPM URLs. 'INT *note gnutls_privkey_import_tpm_raw:: (gnutls_privkey_t PKEY, const gnutls_datum_t * FDATA, gnutls_tpmkey_fmt_t FORMAT, const char * SRK_PASSWORD, const char * KEY_PASSWORD, unsigned int FLAGS)' 'INT *note gnutls_pubkey_import_tpm_raw:: (gnutls_pubkey_t PKEY, const gnutls_datum_t * FDATA, gnutls_tpmkey_fmt_t FORMAT, const char * SRK_PASSWORD, unsigned int FLAGS)' -- Function: int gnutls_privkey_import_tpm_url (gnutls_privkey_t PKEY, const char * URL, const char * SRK_PASSWORD, const char * KEY_PASSWORD, unsigned int FLAGS) PKEY: The private key URL: The URL of the TPM key to be imported SRK_PASSWORD: The password for the SRK key (optional) KEY_PASSWORD: A password for the key (optional) FLAGS: One of the GNUTLS_PRIVKEY_* flags This function will import the given private key to the abstract 'gnutls_privkey_t' structure. Note that unless 'GNUTLS_PRIVKEY_DISABLE_CALLBACKS' is specified, if incorrect (or NULL) passwords are given the PKCS11 callback functions will be used to obtain the correct passwords. Otherwise if the SRK password is wrong 'GNUTLS_E_TPM_SRK_PASSWORD_ERROR' is returned and if the key password is wrong or not provided then 'GNUTLS_E_TPM_KEY_PASSWORD_ERROR' is returned. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.1.0 -- Function: int gnutls_pubkey_import_tpm_url (gnutls_pubkey_t PKEY, const char * URL, const char * SRK_PASSWORD, unsigned int FLAGS) PKEY: The public key URL: The URL of the TPM key to be imported SRK_PASSWORD: The password for the SRK key (optional) FLAGS: should be zero This function will import the given private key to the abstract 'gnutls_privkey_t' structure. Note that unless 'GNUTLS_PUBKEY_DISABLE_CALLBACKS' is specified, if incorrect (or NULL) passwords are given the PKCS11 callback functions will be used to obtain the correct passwords. Otherwise if the SRK password is wrong 'GNUTLS_E_TPM_SRK_PASSWORD_ERROR' is returned. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.1.0 Listing and deleting keys ......................... The registered keys (that are stored in the TPM) can be listed using one of the following functions. Those keys are unfortunately only identified by their UUID and have no label or other human friendly identifier. Keys can be deleted from permament storage using *note gnutls_tpm_privkey_delete::. 'INT *note gnutls_tpm_get_registered:: (gnutls_tpm_key_list_t * LIST)' 'VOID *note gnutls_tpm_key_list_deinit:: (gnutls_tpm_key_list_t LIST)' 'INT *note gnutls_tpm_key_list_get_url:: (gnutls_tpm_key_list_t LIST, unsigned int IDX, char ** URL, unsigned int FLAGS)' -- Function: int gnutls_tpm_privkey_delete (const char * URL, const char * SRK_PASSWORD) URL: the URL describing the key SRK_PASSWORD: a password for the SRK key This function will unregister the private key from the TPM chip. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error value. *Since:* 3.1.0  File: gnutls.info, Node: tpmtool Invocation, Prev: Using keys, Up: Trusted Platform Module 5.3.4 Invoking tpmtool ---------------------- Program that allows handling cryptographic data from the TPM chip. This section was generated by *AutoGen*, using the 'agtexi-cmd' template and the option descriptions for the 'tpmtool' program. This software is released under the GNU General Public License, version 3 or later. tpmtool help/usage ('--help') ............................. This is the automatically generated usage text for tpmtool. 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. tpmtool - GnuTLS TPM tool Usage: tpmtool [ - [] | --[{=| }] ]... -d, --debug=num Enable debugging - it must be in the range: 0 to 9999 --infile=file Input file - file must pre-exist --outfile=str Output file --generate-rsa Generate an RSA private-public key pair --register Any generated key will be registered in the TPM - requires the option 'generate-rsa' --signing Any generated key will be a signing key - requires the option 'generate-rsa' -- and prohibits the option 'legacy' --legacy Any generated key will be a legacy key - requires the option 'generate-rsa' -- and prohibits the option 'signing' --user Any registered key will be a user key - requires the option 'register' -- and prohibits the option 'system' --system Any registred key will be a system key - requires the option 'register' -- and prohibits the option 'user' --pubkey=str Prints the public key of the provided key --list Lists all stored keys in the TPM --delete=str Delete the key identified by the given URL (UUID). --sec-param=str Specify the security level [low, legacy, normal, high, ultra]. --bits=num Specify the number of bits for key generate --inder Use the DER format for keys. - disabled as '--no-inder' --outder Use DER format for output keys - disabled as '--no-outder' -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 allows handling cryptographic data from the TPM chip. Please send bug reports to: <@PACKAGE_BUGREPORT@> debug option (-d) ................. This is the "enable debugging" option. This option takes a number argument. Specifies the debug level. generate-rsa option ................... This is the "generate an rsa private-public key pair" option. Generates an RSA private-public key pair in the TPM chip. The key may be stored in filesystem and protected by a PIN, or stored (registered) in the TPM chip flash. user option ........... This is the "any registered key will be a user key" option. This option has some usage constraints. It: * must appear in combination with the following options: register. * must not appear in combination with any of the following options: system. The generated key will be stored in a user specific persistent storage. system option ............. This is the "any registred key will be a system key" option. This option has some usage constraints. It: * must appear in combination with the following options: register. * must not appear in combination with any of the following options: user. The generated key will be stored in system persistent storage. sec-param option ................ This is the "specify the security level [low, legacy, normal, high, ultra]." option. This option takes a string argument 'Security parameter'. This is alternative to the bits option. Note however that the values allowed by the TPM chip are quantized and given values may be rounded up. inder option ............ This is the "use the der format for keys." option. This option has some usage constraints. It: * can be disabled with -no-inder. The input files will be assumed to be in the portable DER format of TPM. The default format is a custom format used by various TPM tools outder option ............. This is the "use der format for output keys" option. This option has some usage constraints. It: * can be disabled with -no-outder. The output will be in the TPM portable DER format. tpmtool 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. tpmtool See Also ................ p11tool (1), certtool (1) tpmtool Examples ................ To generate a key that is to be stored in filesystem use: $ tpmtool --generate-rsa --bits 2048 --outfile tpmkey.pem To generate a key that is to be stored in TPM's flash use: $ tpmtool --generate-rsa --bits 2048 --register --user To get the public key of a TPM key use: $ tpmtool --pubkey tpmkey:uuid=58ad734b-bde6-45c7-89d8-756a55ad1891;storage=user \ --outfile pubkey.pem or if the key is stored in the filesystem: $ tpmtool --pubkey tpmkey:file=tmpkey.pem --outfile pubkey.pem To list all keys stored in TPM use: $ tpmtool --list  File: gnutls.info, Node: How to use GnuTLS in applications, Next: GnuTLS application examples, Prev: Hardware security modules and abstract key types, Up: Top 6 How to use GnuTLS in applications *********************************** * Menu: * Introduction to the library:: * Preparation:: * Session initialization:: * Associating the credentials:: * Setting up the transport layer:: * TLS handshake:: * Data transfer and termination:: * Buffered data transfer:: * Handling alerts:: * Priority Strings:: * Selecting cryptographic key sizes:: * Advanced topics::  File: gnutls.info, Node: Introduction to the library, Next: Preparation, Up: How to use GnuTLS in applications 6.1 Introduction ================ This chapter tries to explain the basic functionality of the current GnuTLS library. Note that there may be additional functionality not discussed here but included in the library. Checking the header files in '/usr/include/gnutls/' and the manpages is recommended. * Menu: * General idea:: * Error handling:: * Common types:: * Debugging and auditing:: * Thread safety:: * Callback functions::  File: gnutls.info, Node: General idea, Next: Error handling, Up: Introduction to the library 6.1.1 General idea ------------------ A brief description of how GnuTLS sessions operate is shown at *note Figure 6.1: fig-gnutls-design. This section will become more clear when it is completely read. As shown in the figure, there is a read-only global state that is initialized once by the global initialization function. This global structure, among others, contains the memory allocation functions used, structures needed for the ASN.1 parser and depending on the system's CPU, pointers to hardware accelerated encryption functions. This structure is never modified by any GnuTLS function, except for the deinitialization function which frees all allocated memory and must be called after the program has permanently finished using GnuTLS. [image src="gnutls-internals.png"] Figure 6.1: High level design of GnuTLS. The credentials structures are used by the authentication methods, such as certificate authentication. They store certificates, privates keys, and other information that is needed to prove the identity to the peer, and/or verify the indentity of the peer. The information stored in the credentials structures is initialized once and then can be shared by many TLS sessions. A GnuTLS session contains all the required information to handle one secure connection. The session communicates with the peers using the provided functions of the transport layer. Every session has a unique session ID shared with the peer. Since TLS sessions can be resumed, servers need a database back-end to hold the session's parameters. Every GnuTLS session after a successful handshake calls the appropriate back-end function (see *note resume::) to store the newly negotiated session. The session database is examined by the server just after having received the client hello(1), and if the session ID sent by the client, matches a stored session, the stored session will be retrieved, and the new session will be a resumed one, and will share the same session ID with the previous one. ---------- Footnotes ---------- (1) The first message in a TLS handshake  File: gnutls.info, Node: Error handling, Next: Common types, Prev: General idea, Up: Introduction to the library 6.1.2 Error handling -------------------- In GnuTLS most functions return an integer type as a result. In almost all cases a zero or a positive number means success, and a negative number indicates failure, or a situation that some action has to be taken. Thus negative error codes may be fatal or not. Fatal errors terminate the connection immediately and further sends and receives will be disallowed. Such an example is 'GNUTLS_E_DECRYPTION_FAILED'. Non-fatal errors may warn about something, i.e., a warning alert was received, or indicate the some action has to be taken. This is the case with the error code 'GNUTLS_E_REHANDSHAKE' returned by *note gnutls_record_recv::. This error code indicates that the server requests a re-handshake. The client may ignore this request, or may reply with an alert. You can test if an error code is a fatal one by using the *note gnutls_error_is_fatal::. All errors can be converted to a descriptive string using *note gnutls_strerror::. If any non fatal errors, that require an action, are to be returned by a function, these error codes will be documented in the function's reference. For example the error codes 'GNUTLS_E_WARNING_ALERT_RECEIVED' and 'GNUTLS_E_FATAL_ALERT_RECEIVED' that may returned when receiving data, should be handled by notifying the user of the alert (as explained in *note Handling alerts::). See *note Error codes::, for a description of the available error codes.  File: gnutls.info, Node: Common types, Next: Debugging and auditing, Prev: Error handling, Up: Introduction to the library 6.1.3 Common types ------------------ All strings that are to provided as input to GnuTLS functions should be in UTF-8 unless otherwise specified. Output strings are also in UTF-8 format unless otherwise specified. When data of a fixed size are provided to GnuTLS functions then the helper structure 'gnutls_datum_t' is often used. Its definition is shown below. typedef struct { unsigned char *data; unsigned int size; } gnutls_datum_t; Other functions that require data for scattered read use a structure similar to 'struct iovec' typically used by 'readv'. It is shown below. typedef struct { void *iov_base; /* Starting address */ size_t iov_len; /* Number of bytes to transfer */ } giovec_t;  File: gnutls.info, Node: Debugging and auditing, Next: Thread safety, Prev: Common types, Up: Introduction to the library 6.1.4 Debugging and auditing ---------------------------- In many cases things may not go as expected and further information, to assist debugging, from GnuTLS is desired. Those are the cases where the *note gnutls_global_set_log_level:: and *note gnutls_global_set_log_function:: are to be used. Those will print verbose information on the GnuTLS functions internal flow. 'VOID *note gnutls_global_set_log_level:: (int LEVEL)' 'VOID *note gnutls_global_set_log_function:: (gnutls_log_func LOG_FUNC)' Alternatively the environment variable 'GNUTLS_DEBUG_LEVEL' can be set to a logging level and GnuTLS will output debugging output to standard error. When debugging is not required, important issues, such as detected attacks on the protocol still need to be logged. This is provided by the logging function set by *note gnutls_global_set_audit_log_function::. The provided function will receive an message and the corresponding TLS session. The session information might be used to derive IP addresses or other information about the peer involved. -- Function: void gnutls_global_set_audit_log_function (gnutls_audit_log_func LOG_FUNC) LOG_FUNC: it is the audit log function This is the function to set the audit logging function. This is a function to report important issues, such as possible attacks in the protocol. This is different from 'gnutls_global_set_log_function()' because it will report also session-specific events. The session parameter will be null if there is no corresponding TLS session. 'gnutls_audit_log_func' is of the form, void (*gnutls_audit_log_func)( gnutls_session_t, const char*); *Since:* 3.0  File: gnutls.info, Node: Thread safety, Next: Callback functions, Prev: Debugging and auditing, Up: Introduction to the library 6.1.5 Thread safety ------------------- The GnuTLS library is thread safe by design, meaning that objects of the library such as TLS sessions, can be safely divided across threads as long as a single thread accesses a single object. This is sufficient to support a server which handles several sessions per thread. If, however, an object needs to be shared across threads then access must be protected with a mutex. Read-only access to objects, for example the credentials holding structures, is also thread-safe. The random generator of the cryptographic back-end, is not thread safe and requires mutex locks which are setup by GnuTLS. Applications can either call *note gnutls_global_init:: which will initialize the default operating system provided locks (i.e. 'pthreads' on GNU/Linux and 'CriticalSection' on Windows), or manually specify the locking system using the function *note gnutls_global_set_mutex:: before calling *note gnutls_global_init::. Setting mutexes manually is recommended only for applications that have full control of the underlying libraries. If this is not the case, the use of the operating system defaults is recommended. An example of non-native thread usage is shown below. #include int main() { /* When the system mutexes are not to be used * gnutls_global_set_mutex() must be called explicitly */ gnutls_global_set_mutex (mutex_init, mutex_deinit, mutex_lock, mutex_unlock); gnutls_global_init(); } Note that *note gnutls_global_init:: is itself not thread safe. It is also not recommended to initialize it on every available thread, but if need to, it should be protected using mutex locks. -- Function: void gnutls_global_set_mutex (mutex_init_func INIT, mutex_deinit_func DEINIT, mutex_lock_func LOCK, mutex_unlock_func UNLOCK) INIT: mutex initialization function DEINIT: mutex deinitialization function LOCK: mutex locking function UNLOCK: mutex unlocking function With this function you are allowed to override the default mutex locks used in some parts of gnutls and dependent libraries. This function should be used if you have complete control of your program and libraries. Do not call this function from a library. Instead only initialize gnutls and the default OS mutex locks will be used. This function must be called before 'gnutls_global_init()' . *Since:* 2.12.0  File: gnutls.info, Node: Callback functions, Prev: Thread safety, Up: Introduction to the library 6.1.6 Callback functions ------------------------ There are several cases where GnuTLS may need out of band input from your program. This is now implemented using some callback functions, which your program is expected to register. An example of this type of functions are the push and pull callbacks which are used to specify the functions that will retrieve and send data to the transport layer. 'VOID *note gnutls_transport_set_push_function:: (gnutls_session_t SESSION, gnutls_push_func PUSH_FUNC)' 'VOID *note gnutls_transport_set_pull_function:: (gnutls_session_t SESSION, gnutls_pull_func PULL_FUNC)' Other callback functions may require more complicated input and data to be allocated. Such an example is *note gnutls_srp_set_server_credentials_function::. All callbacks should allocate and free memory using 'gnutls_malloc' and 'gnutls_free'.  File: gnutls.info, Node: Preparation, Next: Session initialization, Prev: Introduction to the library, Up: How to use GnuTLS in applications 6.2 Preparation =============== To use GnuTLS, you have to perform some changes to your sources and your build system. The necessary changes are explained in the following subsections. * Menu: * Headers:: * Initialization:: * Version check:: * Building the source::  File: gnutls.info, Node: Headers, Next: Initialization, Up: Preparation 6.2.1 Headers ------------- All the data types and functions of the GnuTLS library are defined in the header file 'gnutls/gnutls.h'. This must be included in all programs that make use of the GnuTLS library.  File: gnutls.info, Node: Initialization, Next: Version check, Prev: Headers, Up: Preparation 6.2.2 Initialization -------------------- GnuTLS must be initialized before it can be used. The library is initialized by calling *note gnutls_global_init::. That call typically enables CPU-specific acceleration, performs any required precalculations needed, and initializes subsystems that could be used later (e.g., PKCS #11 - see *note PKCS11 Initialization::). The resources allocated by the initialization process can be released if the application no longer has a need to call GnuTLS functions, this is done by calling *note gnutls_global_deinit::. In order to take advantage of the internationalization features in GnuTLS, such as translated error messages, the application must set the current locale using 'setlocale' before initializing GnuTLS.  File: gnutls.info, Node: Version check, Next: Building the source, Prev: Initialization, Up: Preparation 6.2.3 Version check ------------------- It is often desirable to check that the version of 'gnutls' used is indeed one which fits all requirements. Even with binary compatibility new features may have been introduced but due to problem with the dynamic linker an old version is actually used. So you may want to check that the version is okay right after program start-up. See the function *note gnutls_check_version::. On the other hand, it is often desirable to support more than one versions of the library. In that case you could utilize compile-time feature checks using the the 'GNUTLS_VERSION_NUMBER' macro. For example, to conditionally add code for GnuTLS 3.2.1 or later, you may use: #if GNUTLS_VERSION_NUMBER >= 0x030201 ... #endif  File: gnutls.info, Node: Building the source, Prev: Version check, Up: Preparation 6.2.4 Building the source ------------------------- If you want to compile a source file including the 'gnutls/gnutls.h' header file, you must make sure that the compiler can find it in the directory hierarchy. This is accomplished by adding the path to the directory in which the header file is located to the compilers include file search path (via the '-I' option). However, the path to the include file is determined at the time the source is configured. To solve this problem, the library uses the external package 'pkg-config' that knows the path to the include file and other configuration options. The options that need to be added to the compiler invocation at compile time are output by the '--cflags' option to 'pkg-config gnutls'. The following example shows how it can be used at the command line: gcc -c foo.c `pkg-config gnutls --cflags` Adding the output of 'pkg-config gnutls --cflags' to the compilers command line will ensure that the compiler can find the 'gnutls/gnutls.h' header file. A similar problem occurs when linking the program with the library. Again, the compiler has to find the library files. For this to work, the path to the library files has to be added to the library search path (via the '-L' option). For this, the option '--libs' to 'pkg-config gnutls' can be used. For convenience, this option also outputs all other options that are required to link the program with the library (for instance, the '-ltasn1' option). The example shows how to link 'foo.o' with the library to a program 'foo'. gcc -o foo foo.o `pkg-config gnutls --libs` Of course you can also combine both examples to a single command by specifying both options to 'pkg-config': gcc -o foo foo.c `pkg-config gnutls --cflags --libs` When a program uses the GNU autoconf system, then the following line or similar can be used to detect the presence of GnuTLS. PKG_CHECK_MODULES([LIBGNUTLS], [gnutls >= 3.0.0]) AC_SUBST([LIBGNUTLS_CFLAGS]) AC_SUBST([LIBGNUTLS_LIBS])  File: gnutls.info, Node: Session initialization, Next: Associating the credentials, Prev: Preparation, Up: How to use GnuTLS in applications 6.3 Session initialization ========================== In the previous sections we have discussed the global initialization required for GnuTLS as well as the initialization required for each authentication method's credentials (see *note Authentication::). In this section we elaborate on the TLS or DTLS session initiation. Each session is initialized using *note gnutls_init:: which among others is used to specify the type of the connection (server or client), and the underlying protocol type, i.e., datagram (UDP) or reliable (TCP). -- Function: int gnutls_init (gnutls_session_t * SESSION, unsigned int FLAGS) SESSION: is a pointer to a 'gnutls_session_t' structure. FLAGS: indicate if this session is to be used for server or client. This function initializes the current session to null. Every session must be initialized before use, so internal structures can be allocated. This function allocates structures which can only be free'd by calling 'gnutls_deinit()' . Returns 'GNUTLS_E_SUCCESS' (0) on success. 'flags' can be one of 'GNUTLS_CLIENT' and 'GNUTLS_SERVER' . For a DTLS entity, the flags 'GNUTLS_DATAGRAM' and 'GNUTLS_NONBLOCK' are also available. The latter flag will enable a non-blocking operation of the DTLS timers. The flag 'GNUTLS_NO_REPLAY_PROTECTION' will disable any replay protection in DTLS mode. That must only used when replay protection is achieved using other means. Note that since version 3.1.2 this function enables some common TLS extensions such as session tickets and OCSP certificate status request in client side by default. To prevent that use the 'GNUTLS_NO_EXTENSIONS' flag. *Returns:* 'GNUTLS_E_SUCCESS' on success, or an error code. After the session initialization details on the allowed ciphersuites and protocol versions should be set using the priority functions such as *note gnutls_priority_set_direct::. We elaborate on them in *note Priority Strings::. The credentials used for the key exchange method, such as certificates or usernames and passwords should also be associated with the session current session using *note gnutls_credentials_set::. -- Function: int gnutls_credentials_set (gnutls_session_t SESSION, gnutls_credentials_type_t TYPE, void * CRED) SESSION: is a 'gnutls_session_t' structure. TYPE: is the type of the credentials CRED: is a pointer to a structure. Sets the needed credentials for the specified type. Eg username, password - or public and private keys etc. The 'cred' parameter is a structure that depends on the specified type and on the current session (client or server). In order to minimize memory usage, and share credentials between several threads gnutls keeps a pointer to cred, and not the whole cred structure. Thus you will have to keep the structure allocated until you call 'gnutls_deinit()' . For 'GNUTLS_CRD_ANON' , 'cred' should be 'gnutls_anon_client_credentials_t' in case of a client. In case of a server it should be 'gnutls_anon_server_credentials_t' . For 'GNUTLS_CRD_SRP' , 'cred' should be 'gnutls_srp_client_credentials_t' in case of a client, and 'gnutls_srp_server_credentials_t' , in case of a server. For 'GNUTLS_CRD_CERTIFICATE' , 'cred' should be 'gnutls_certificate_credentials_t' . *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise a negative error code is returned.  File: gnutls.info, Node: Associating the credentials, Next: Setting up the transport layer, Prev: Session initialization, Up: How to use GnuTLS in applications 6.4 Associating the credentials =============================== * Menu: * Certificate credentials:: * SRP credentials:: * PSK credentials:: * Anonymous credentials:: Each authentication method is associated with a key exchange method, and a credentials type. The contents of the credentials is method-dependent, e.g. certificates for certificate authentication and should be initialized and associated with a session (see *note gnutls_credentials_set::). A mapping of the key exchange methods with the credential types is shown in *note Table 6.1: tab:key-exchange-cred. Authentication Key exchange Client Server method credentials credentials -------------------------------------------------------------------- Certificate 'KX_RSA', 'CRD_CERTIFICATE''CRD_CERTIFICATE' 'KX_DHE_RSA', 'KX_DHE_DSS', 'KX_ECDHE_RSA', 'KX_ECDHE_ECDSA', 'KX_RSA_EXPORT' Password and 'KX_SRP_RSA', 'CRD_SRP' 'CRD_CERTIFICATE', certificate 'KX_SRP_DSS' 'CRD_SRP' Password 'KX_SRP' 'CRD_SRP' 'CRD_SRP' Anonymous 'KX_ANON_DH', 'CRD_ANON' 'CRD_ANON' 'KX_ANON_ECDH' Pre-shared key 'KX_PSK', 'CRD_PSK' 'CRD_PSK' 'KX_DHE_PSK', 'KX_ECDHE_PSK' Table 6.1: Key exchange algorithms and the corresponding credential types.  File: gnutls.info, Node: Certificate credentials, Next: SRP credentials, Up: Associating the credentials 6.4.1 Certificates ------------------ Server certificate authentication ................................. When using certificates the server is required to have at least one certificate and private key pair. Clients may not hold such a pair, but a server could require it. In this section we discuss general issues applying to both client and server certificates. The next section will elaborate on issues arising from client authentication only. 'INT *note gnutls_certificate_allocate_credentials:: (gnutls_certificate_credentials_t * RES)' 'VOID *note gnutls_certificate_free_credentials:: (gnutls_certificate_credentials_t SC)' After the credentials structures are initialized, the certificate and key pair must be loaded. This occurs before any TLS session is initialized, and the same structures are reused for multiple sessions. Depending on the certificate type different loading functions are available, as shown below. For X.509 certificates, the functions will accept and use a certificate chain that leads to a trusted authority. The certificate chain must be ordered in such way that every certificate certifies the one before it. The trusted authority's certificate need not to be included since the peer should possess it already. 'INT *note gnutls_certificate_set_x509_key_mem2:: (gnutls_certificate_credentials_t RES, const gnutls_datum_t * CERT, const gnutls_datum_t * KEY, gnutls_x509_crt_fmt_t TYPE, const char * PASS, unsigned int FLAGS)' 'INT *note gnutls_certificate_set_x509_key:: (gnutls_certificate_credentials_t RES, gnutls_x509_crt_t * CERT_LIST, int CERT_LIST_SIZE, gnutls_x509_privkey_t KEY)' 'INT *note 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)' 'INT *note gnutls_certificate_set_openpgp_key_mem:: (gnutls_certificate_credentials_t RES, const gnutls_datum_t * CERT, const gnutls_datum_t * KEY, gnutls_openpgp_crt_fmt_t FORMAT)' 'INT *note gnutls_certificate_set_openpgp_key:: (gnutls_certificate_credentials_t RES, gnutls_openpgp_crt_t CRT, gnutls_openpgp_privkey_t PKEY)' 'INT *note gnutls_certificate_set_openpgp_key_file:: (gnutls_certificate_credentials_t RES, const char * CERTFILE, const char * KEYFILE, gnutls_openpgp_crt_fmt_t FORMAT)' Note however, that since functions like *note gnutls_certificate_set_x509_key_file2:: may accept URLs that specify objects stored in token, another important function is *note gnutls_certificate_set_pin_function::. That allows setting a callback function to retrieve a PIN if the input keys are protected by PIN by the token. -- Function: void gnutls_certificate_set_pin_function (gnutls_certificate_credentials_t CRED, gnutls_pin_callback_t FN, void * USERDATA) CRED: is a 'gnutls_certificate_credentials_t' structure. FN: A PIN callback USERDATA: Data to be passed in the callback This function will set a callback function to be used when required to access a protected object. This function overrides any other global PIN functions. Note that this function must be called right after initialization to have effect. *Since:* 3.1.0 If the imported keys and certificates need to be accessed before any TLS session is established, it is convenient to use *note gnutls_certificate_set_key:: in combination with *note gnutls_pcert_import_x509_raw:: and *note gnutls_privkey_import_x509_raw::. -- Function: int gnutls_certificate_set_key (gnutls_certificate_credentials_t RES, const char ** NAMES, int NAMES_SIZE, gnutls_pcert_st * PCERT_LIST, int PCERT_LIST_SIZE, gnutls_privkey_t KEY) RES: is a 'gnutls_certificate_credentials_t' structure. NAMES: is an array of DNS name of the certificate (NULL if none) NAMES_SIZE: holds the size of the names list PCERT_LIST: contains a certificate list (path) for the specified private key PCERT_LIST_SIZE: holds the size of the certificate list KEY: is a 'gnutls_privkey_t' key This function sets a certificate/private key pair in the gnutls_certificate_credentials_t structure. This function may be called more than once, in case multiple keys/certificates exist for the server. For clients that wants to send more than its own end entity certificate (e.g., also an intermediate CA cert) then put the certificate chain in 'pcert_list' . Note that the 'pcert_list' and 'key' will become part of the credentials structure and must not be deallocated. They will be automatically deallocated when the 'res' structure is deinitialized. *Returns:* 'GNUTLS_E_SUCCESS' (0) on success, or a negative error code. *Since:* 3.0 If multiple certificates are used with the functions above each client's request will be served with the certificate that matches the requested name (see *note Server name indication::). As an alternative to loading from files or buffers, a callback may be used for the server or the client to specify the certificate and the key at the handshake time. In that case a certificate should be selected according the peer's signature algorithm preferences. To get those preferences use *note gnutls_sign_algorithm_get_requested::. Both functions are shown below. 'VOID *note gnutls_certificate_set_retrieve_function:: (gnutls_certificate_credentials_t CRED, gnutls_certificate_retrieve_function * FUNC)' 'VOID *note gnutls_certificate_set_retrieve_function2:: (gnutls_certificate_credentials_t CRED, gnutls_certificate_retrieve_function2 * FUNC)' 'INT *note gnutls_sign_algorithm_get_requested:: (gnutls_session_t SESSION, size_t INDX, gnutls_sign_algorithm_t * ALGO)' The functions above do not handle the requested server name automatically. A server would need to check the name requested by the client using *note gnutls_server_name_get::, and serve the appropriate certificate. Note that some of these functions require the 'gnutls_pcert_st' structure to be filled in. Helper functions to make the required structures are listed below. typedef struct gnutls_pcert_st { gnutls_pubkey_t pubkey; gnutls_datum_t cert; gnutls_certificate_type_t type; } gnutls_pcert_st; 'INT *note gnutls_pcert_import_x509:: (gnutls_pcert_st * PCERT, gnutls_x509_crt_t CRT, unsigned int FLAGS)' 'INT *note gnutls_pcert_import_openpgp:: (gnutls_pcert_st * PCERT, gnutls_openpgp_crt_t CRT, unsigned int FLAGS)' 'INT *note gnutls_pcert_import_x509_raw:: (gnutls_pcert_st * PCERT, const gnutls_datum_t * CERT, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)' 'INT *note gnutls_pcert_import_openpgp_raw:: (gnutls_pcert_st * PCERT, const gnutls_datum_t * CERT, gnutls_openpgp_crt_fmt_t FORMAT, gnutls_openpgp_keyid_t KEYID, unsigned int FLAGS)' 'VOID *note gnutls_pcert_deinit:: (gnutls_pcert_st * PCERT)' In a handshake, the negotiated cipher suite depends on the certificate's parameters, so some key exchange methods might not be available with all certificates. GnuTLS will disable ciphersuites that are not compatible with the key, or the enabled authentication methods. For example keys marked as sign-only, will not be able to access the plain RSA ciphersuites, that require decryption. It is not recommended to use RSA keys for both signing and encryption. If possible use a different key for the 'DHE-RSA' which uses signing and 'RSA' that requires decryption. All the key exchange methods shown in *note Table 4.1: tab:key-exchange. are available in certificate authentication. Client certificate authentication ................................. If a certificate is to be requested from the client during the handshake, the server will send a certificate request message. This behavior is controlled *note gnutls_certificate_server_set_request::. The request contains a list of the acceptable by the server certificate signers. This list is constructed using the trusted certificate authorities of the server. In cases where the server supports a large number of certificate authorities it makes sense not to advertise all of the names to save bandwidth. That can be controlled using the function *note gnutls_certificate_send_x509_rdn_sequence::. This however will have the side-effect of not restricting the client to certificates signed by server's acceptable signers. -- Function: void gnutls_certificate_server_set_request (gnutls_session_t SESSION, gnutls_certificate_request_t REQ) SESSION: is a 'gnutls_session_t' structure. REQ: is one of GNUTLS_CERT_REQUEST, GNUTLS_CERT_REQUIRE This function specifies if we (in case of a server) are going to send a certificate request message to the client. If 'req' is GNUTLS_CERT_REQUIRE then the server will return an error if the peer does not provide a certificate. If you do not call this function then the client will not be asked to send a certificate. -- Function: void gnutls_certificate_send_x509_rdn_sequence (gnutls_session_t SESSION, int STATUS) SESSION: is a pointer to a 'gnutls_session_t' structure. STATUS: is 0 or 1 If status is non zero, this function will order gnutls not to send the rdnSequence in the certificate request message. That is the server will not advertise its trusted CAs to the peer. If status is zero then the default behaviour will take effect, which is to advertise the server's trusted CAs. This function has no effect in clients, and in authentication methods other than certificate with X.509 certificates. Client or server certificate verification ......................................... Certificate verification is possible by loading the trusted authorities into the credentials structure by using the following functions, applicable to X.509 and OpenPGP certificates. 'INT *note gnutls_certificate_set_x509_system_trust:: (gnutls_certificate_credentials_t CRED)' 'INT *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)' 'INT *note gnutls_certificate_set_openpgp_keyring_file:: (gnutls_certificate_credentials_t C, const char * FILE, gnutls_openpgp_crt_fmt_t FORMAT)' The peer's certificate is not automatically verified and one must call *note gnutls_certificate_verify_peers3:: after a successful handshake to verify the certificate's signature and the owner of the certificate. The verification status returned can be printed using *note gnutls_certificate_verification_status_print::. Alternatively the verification can occur during the handshake by using *note gnutls_certificate_set_verify_function::. The functions above provide a brief verification output. If a detailed output is required one should call *note gnutls_certificate_get_peers:: to obtain the raw certificate of the peer and verify it using the functions discussed in *note X.509 certificates::. -- Function: int gnutls_certificate_verify_peers3 (gnutls_session_t SESSION, const char * HOSTNAME, unsigned int * STATUS) SESSION: is a gnutls session HOSTNAME: is the expected name of the peer; may be 'NULL' STATUS: is the output of the verification This function will verify the peer's certificate and store the status in the 'status' variable as a bitwise or'd gnutls_certificate_status_t values or zero if the certificate is trusted. Note that value in 'status' is set only when the return value of this function is success (i.e, failure to trust a certificate does not imply a negative return value). If the 'hostname' provided is non-NULL then this function will compare the hostname in the certificate against the given. If they do not match the 'GNUTLS_CERT_UNEXPECTED_OWNER' status flag will be set. If available the OCSP Certificate Status extension will be utilized by this function. To avoid denial of service attacks some default upper limits regarding the certificate key size and chain size are set. To override them use 'gnutls_certificate_set_verify_limits()' . *Returns:* a negative error code on error and 'GNUTLS_E_SUCCESS' (0) on success. *Since:* 3.1.4 -- Function: void gnutls_certificate_set_verify_function (gnutls_certificate_credentials_t CRED, gnutls_certificate_verify_function * FUNC) CRED: is a 'gnutls_certificate_credentials_t' structure. FUNC: is the callback function This function sets a callback to be called when peer's certificate has been received in order to verify it on receipt rather than doing after the handshake is completed. The callback's function prototype is: int (*callback)(gnutls_session_t); If the callback function is provided then gnutls will call it, in the handshake, just after the certificate message has been received. To verify or obtain the certificate the 'gnutls_certificate_verify_peers2()' , 'gnutls_certificate_type_get()' , 'gnutls_certificate_get_peers()' functions can be used. The callback function should return 0 for the handshake to continue or non-zero to terminate. *Since:* 2.10.0  File: gnutls.info, Node: SRP credentials, Next: PSK credentials, Prev: Certificate credentials, Up: Associating the credentials 6.4.2 SRP --------- The initialization functions in SRP credentials differ between client and server. Clients supporting SRP should set the username and password prior to connection, to the credentials structure. Alternatively *note gnutls_srp_set_client_credentials_function:: may be used instead, to specify a callback function that should return the SRP username and password. The callback is called once during the TLS handshake. 'INT *note gnutls_srp_allocate_server_credentials:: (gnutls_srp_server_credentials_t * SC)' 'INT *note gnutls_srp_allocate_client_credentials:: (gnutls_srp_client_credentials_t * SC)' 'VOID *note gnutls_srp_free_server_credentials:: (gnutls_srp_server_credentials_t SC)' 'VOID *note gnutls_srp_free_client_credentials:: (gnutls_srp_client_credentials_t SC)' 'INT *note gnutls_srp_set_client_credentials:: (gnutls_srp_client_credentials_t RES, const char * USERNAME, const char * PASSWORD)' -- Function: void gnutls_srp_set_client_credentials_function (gnutls_srp_client_credentials_t CRED, gnutls_srp_client_credentials_function * FUNC) CRED: is a 'gnutls_srp_server_credentials_t' structure. FUNC: is the callback function This function can be used to set a callback to retrieve the username and password for client SRP authentication. The callback's function form is: int (*callback)(gnutls_session_t, char** username, char**password); The 'username' and 'password' must be allocated using 'gnutls_malloc()' . 'username' and 'password' should be ASCII strings or UTF-8 strings prepared using the "SASLprep" profile of "stringprep". The callback function will be called once per handshake before the initial hello message is sent. The callback should not return a negative error code the second time called, since the handshake procedure will be aborted. The callback function should return 0 on success. -1 indicates an error. In server side the default behavior of GnuTLS is to read the usernames and SRP verifiers from password files. These password file format is compatible the with the _Stanford srp libraries_ format. If a different password file format is to be used, then *note gnutls_srp_set_server_credentials_function:: should be called, to set an appropriate callback. -- Function: int gnutls_srp_set_server_credentials_file (gnutls_srp_server_credentials_t RES, const char * PASSWORD_FILE, const char * PASSWORD_CONF_FILE) RES: is a 'gnutls_srp_server_credentials_t' structure. PASSWORD_FILE: is the SRP password file (tpasswd) PASSWORD_CONF_FILE: is the SRP password conf file (tpasswd.conf) This function sets the password files, in a 'gnutls_srp_server_credentials_t' structure. Those password files hold usernames and verifiers and will be used for SRP authentication. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, or an error code. -- Function: void gnutls_srp_set_server_credentials_function (gnutls_srp_server_credentials_t CRED, gnutls_srp_server_credentials_function * FUNC) CRED: is a 'gnutls_srp_server_credentials_t' structure. FUNC: is the callback function This function can be used to set a callback to retrieve the user's SRP credentials. The callback's function form is: int (*callback)(gnutls_session_t, const char* username, gnutls_datum_t* salt, gnutls_datum_t *verifier, gnutls_datum_t* generator, gnutls_datum_t* prime); 'username' contains the actual username. The 'salt' , 'verifier' , 'generator' and 'prime' must be filled in using the 'gnutls_malloc()' . For convenience 'prime' and 'generator' may also be one of the static parameters defined in gnutls.h. In case the callback returned a negative number then gnutls will assume that the username does not exist. In order to prevent attackers from guessing valid usernames, if a user does not exist, g and n values should be filled in using a random user's parameters. In that case the callback must return the special value (1). The callback function will only be called once per handshake. The callback function should return 0 on success, while -1 indicates an error.  File: gnutls.info, Node: PSK credentials, Next: Anonymous credentials, Prev: SRP credentials, Up: Associating the credentials 6.4.3 PSK --------- The initialization functions in PSK credentials differ between client and server. 'INT *note gnutls_psk_allocate_server_credentials:: (gnutls_psk_server_credentials_t * SC)' 'INT *note gnutls_psk_allocate_client_credentials:: (gnutls_psk_client_credentials_t * SC)' 'VOID *note gnutls_psk_free_server_credentials:: (gnutls_psk_server_credentials_t SC)' 'VOID *note gnutls_psk_free_client_credentials:: (gnutls_psk_client_credentials_t SC)' Clients supporting PSK should supply the username and key before a TLS session is established. Alternatively *note gnutls_psk_set_client_credentials_function:: can be used to specify a callback function. This has the advantage that the callback will be called only if PSK has been negotiated. 'INT *note gnutls_psk_set_client_credentials:: (gnutls_psk_client_credentials_t RES, const char * USERNAME, const gnutls_datum_t * KEY, gnutls_psk_key_flags FLAGS)' -- Function: void gnutls_psk_set_client_credentials_function (gnutls_psk_client_credentials_t CRED, gnutls_psk_client_credentials_function * FUNC) CRED: is a 'gnutls_psk_server_credentials_t' structure. FUNC: is the callback function This function can be used to set a callback to retrieve the username and password for client PSK authentication. The callback's function form is: int (*callback)(gnutls_session_t, char** username, gnutls_datum_t* key); The 'username' and 'key' ->data must be allocated using 'gnutls_malloc()' . 'username' should be ASCII strings or UTF-8 strings prepared using the "SASLprep" profile of "stringprep". The callback function will be called once per handshake. The callback function should return 0 on success. -1 indicates an error. In server side the default behavior of GnuTLS is to read the usernames and PSK keys from a password file. The password file should contain usernames and keys in hexadecimal format. The name of the password file can be stored to the credentials structure by calling *note gnutls_psk_set_server_credentials_file::. If a different password file format is to be used, then a callback should be set instead by *note gnutls_psk_set_server_credentials_function::. The server can help the client chose a suitable username and password, by sending a hint. Note that there is no common profile for the PSK hint and applications are discouraged to use it. A server, may specify the hint by calling *note gnutls_psk_set_server_credentials_hint::. The client can retrieve the hint, for example in the callback function, using *note gnutls_psk_client_get_hint::. -- Function: int gnutls_psk_set_server_credentials_file (gnutls_psk_server_credentials_t RES, const char * PASSWORD_FILE) RES: is a 'gnutls_psk_server_credentials_t' structure. PASSWORD_FILE: is the PSK password file (passwd.psk) This function sets the password file, in a 'gnutls_psk_server_credentials_t' structure. This password file holds usernames and keys and will be used for PSK authentication. *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, otherwise an error code is returned. 'VOID *note gnutls_psk_set_server_credentials_function:: (gnutls_psk_server_credentials_t CRED, gnutls_psk_server_credentials_function * FUNC)' 'INT *note gnutls_psk_set_server_credentials_hint:: (gnutls_psk_server_credentials_t RES, const char * HINT)' 'CONST CHAR * *note gnutls_psk_client_get_hint:: (gnutls_session_t SESSION)'  File: gnutls.info, Node: Anonymous credentials, Prev: PSK credentials, Up: Associating the credentials 6.4.4 Anonymous --------------- The key exchange methods for anonymous authentication might require Diffie-Hellman parameters to be generated by the server and associated with an anonymous credentials structure. Check *note Parameter generation:: for more information. The initialization functions for the credentials are shown below. 'INT *note gnutls_anon_allocate_server_credentials:: (gnutls_anon_server_credentials_t * SC)' 'INT *note gnutls_anon_allocate_client_credentials:: (gnutls_anon_client_credentials_t * SC)' 'VOID *note gnutls_anon_free_server_credentials:: (gnutls_anon_server_credentials_t SC)' 'VOID *note gnutls_anon_free_client_credentials:: (gnutls_anon_client_credentials_t SC)'  File: gnutls.info, Node: Setting up the transport layer, Next: TLS handshake, Prev: Associating the credentials, Up: How to use GnuTLS in applications 6.5 Setting up the transport layer ================================== The next step is to setup the underlying transport layer details. The Berkeley sockets are implicitly used by GnuTLS, thus a call to *note gnutls_transport_set_int:: would be sufficient to specify the socket descriptor. 'VOID *note gnutls_transport_set_int:: (gnutls_session_t SESSION, int I)' 'VOID *note gnutls_transport_set_int2:: (gnutls_session_t SESSION, int RECV_INT, int SEND_INT)' If however another transport layer than TCP is selected, then a pointer should be used instead to express the parameter to be passed to custom functions. In that case the following functions should be used instead. 'VOID *note gnutls_transport_set_ptr:: (gnutls_session_t SESSION, gnutls_transport_ptr_t PTR)' 'VOID *note gnutls_transport_set_ptr2:: (gnutls_session_t SESSION, gnutls_transport_ptr_t RECV_PTR, gnutls_transport_ptr_t SEND_PTR)' Moreover all of the following push and pull callbacks should be set. -- Function: void gnutls_transport_set_push_function (gnutls_session_t SESSION, gnutls_push_func PUSH_FUNC) SESSION: is a 'gnutls_session_t' structure. PUSH_FUNC: a callback function similar to 'write()' This is the function where you set a push function for gnutls to use in order to send data. If you are going to use berkeley style sockets, you do not need to use this function since the default send(2) will probably be ok. Otherwise you should specify this function for gnutls to be able to send data. The callback should return a positive number indicating the bytes sent, and -1 on error. 'push_func' is of the form, ssize_t (*gnutls_push_func)(gnutls_transport_ptr_t, const void*, size_t); -- Function: void gnutls_transport_set_vec_push_function (gnutls_session_t SESSION, gnutls_vec_push_func VEC_FUNC) SESSION: is a 'gnutls_session_t' structure. VEC_FUNC: a callback function similar to 'writev()' Using this function you can override the default writev(2) function for gnutls to send data. Setting this callback instead of 'gnutls_transport_set_push_function()' is recommended since it introduces less overhead in the TLS handshake process. 'vec_func' is of the form, ssize_t (*gnutls_vec_push_func) (gnutls_transport_ptr_t, const giovec_t * iov, int iovcnt); *Since:* 2.12.0 -- Function: void gnutls_transport_set_pull_function (gnutls_session_t SESSION, gnutls_pull_func PULL_FUNC) SESSION: is a 'gnutls_session_t' structure. PULL_FUNC: a callback function similar to 'read()' This is the function where you set a function for gnutls to receive data. Normally, if you use berkeley style sockets, do not need to use this function since the default recv(2) will probably be ok. The callback should return 0 on connection termination, a positive number indicating the number of bytes received, and -1 on error. 'gnutls_pull_func' is of the form, ssize_t (*gnutls_pull_func)(gnutls_transport_ptr_t, void*, size_t); -- Function: void gnutls_transport_set_pull_timeout_function (gnutls_session_t SESSION, gnutls_pull_timeout_func FUNC) SESSION: is a 'gnutls_session_t' structure. FUNC: a callback function This is the function where you set a function for gnutls to know whether data are ready to be received. It should wait for data a given time frame in milliseconds. The callback should return 0 on timeout, a positive number if data can be received, and -1 on error. You'll need to override this function if 'select()' is not suitable for the provided transport calls. As with 'select()' , if the timeout value is zero the callback should return zero if no data are immediately available. 'gnutls_pull_timeout_func' is of the form, int (*gnutls_pull_timeout_func)(gnutls_transport_ptr_t, unsigned int ms); *Since:* 3.0 The functions above accept a callback function which should return the number of bytes written, or -1 on error and should set 'errno' appropriately. In some environments, setting 'errno' is unreliable. For example Windows have several errno variables in different CRTs, or in other systems it may be a non thread-local variable. If this is a concern to you, call *note gnutls_transport_set_errno:: with the intended errno value instead of setting 'errno' directly. -- Function: void gnutls_transport_set_errno (gnutls_session_t SESSION, int ERR) SESSION: is a 'gnutls_session_t' structure. ERR: error value to store in session-specific errno variable. Store 'err' in the session-specific errno variable. Useful values for 'err' is EAGAIN and EINTR, other values are treated will be treated as real errors in the push/pull function. This function is useful in replacement push and pull functions set by 'gnutls_transport_set_push_function()' and 'gnutls_transport_set_pull_function()' under Windows, where the replacements may not have access to the same 'errno' variable that is used by GnuTLS (e.g., the application is linked to msvcr71.dll and gnutls is linked to msvcrt.dll). GnuTLS currently only interprets the EINTR, EAGAIN and EMSGSIZE errno values and returns the corresponding GnuTLS error codes: * 'GNUTLS_E_INTERRUPTED' * 'GNUTLS_E_AGAIN' * 'GNUTLS_E_LARGE_PACKET' The EINTR and EAGAIN values are returned by interrupted system calls, or when non blocking IO is used. All GnuTLS functions can be resumed (called again), if any of the above error codes is returned. The EMSGSIZE value is returned when attempting to send a large datagram. In the case of DTLS it is also desirable to override the generic transport functions with functions that emulate the operation of 'recvfrom' and 'sendto'. In addition DTLS requires timers during the receive of a handshake message, set using the *note gnutls_transport_set_pull_timeout_function:: function. To check the retransmission timers the function *note gnutls_dtls_get_timeout:: is provided, which returns the time remaining until the next retransmission, or better the time until *note gnutls_handshake:: should be called again. -- Function: void gnutls_transport_set_pull_timeout_function (gnutls_session_t SESSION, gnutls_pull_timeout_func FUNC) SESSION: is a 'gnutls_session_t' structure. FUNC: a callback function This is the function where you set a function for gnutls to know whether data are ready to be received. It should wait for data a given time frame in milliseconds. The callback should return 0 on timeout, a positive number if data can be received, and -1 on error. You'll need to override this function if 'select()' is not suitable for the provided transport calls. As with 'select()' , if the timeout value is zero the callback should return zero if no data are immediately available. 'gnutls_pull_timeout_func' is of the form, int (*gnutls_pull_timeout_func)(gnutls_transport_ptr_t, unsigned int ms); *Since:* 3.0 -- Function: unsigned int gnutls_dtls_get_timeout (gnutls_session_t SESSION) SESSION: is a 'gnutls_session_t' structure. This function will return the milliseconds remaining for a retransmission of the previously sent handshake message. This function is useful when DTLS is used in non-blocking mode, to estimate when to call 'gnutls_handshake()' if no packets have been received. *Returns:* the remaining time in milliseconds. *Since:* 3.0 * Menu: * Asynchronous operation:: * DTLS sessions::